1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements extra semantic analysis beyond what is enforced 11 // by the C type system. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/AST/APValue.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/AttrIterator.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclBase.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclarationName.h" 25 #include "clang/AST/EvaluatedExprVisitor.h" 26 #include "clang/AST/Expr.h" 27 #include "clang/AST/ExprCXX.h" 28 #include "clang/AST/ExprObjC.h" 29 #include "clang/AST/ExprOpenMP.h" 30 #include "clang/AST/FormatString.h" 31 #include "clang/AST/NSAPI.h" 32 #include "clang/AST/NonTrivialTypeVisitor.h" 33 #include "clang/AST/OperationKinds.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSwitch.h" 79 #include "llvm/ADT/Triple.h" 80 #include "llvm/Support/AtomicOrdering.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/ConvertUTF.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/Format.h" 86 #include "llvm/Support/Locale.h" 87 #include "llvm/Support/MathExtras.h" 88 #include "llvm/Support/raw_ostream.h" 89 #include <algorithm> 90 #include <cassert> 91 #include <cstddef> 92 #include <cstdint> 93 #include <functional> 94 #include <limits> 95 #include <string> 96 #include <tuple> 97 #include <utility> 98 99 using namespace clang; 100 using namespace sema; 101 102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 103 unsigned ByteNo) const { 104 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 105 Context.getTargetInfo()); 106 } 107 108 /// Checks that a call expression's argument count is the desired number. 109 /// This is useful when doing custom type-checking. Returns true on error. 110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 111 unsigned argCount = call->getNumArgs(); 112 if (argCount == desiredArgCount) return false; 113 114 if (argCount < desiredArgCount) 115 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 116 << 0 /*function call*/ << desiredArgCount << argCount 117 << call->getSourceRange(); 118 119 // Highlight all the excess arguments. 120 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 121 call->getArg(argCount - 1)->getEndLoc()); 122 123 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 124 << 0 /*function call*/ << desiredArgCount << argCount 125 << call->getArg(1)->getSourceRange(); 126 } 127 128 /// Check that the first argument to __builtin_annotation is an integer 129 /// and the second argument is a non-wide string literal. 130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 131 if (checkArgCount(S, TheCall, 2)) 132 return true; 133 134 // First argument should be an integer. 135 Expr *ValArg = TheCall->getArg(0); 136 QualType Ty = ValArg->getType(); 137 if (!Ty->isIntegerType()) { 138 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 139 << ValArg->getSourceRange(); 140 return true; 141 } 142 143 // Second argument should be a constant string. 144 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 145 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 146 if (!Literal || !Literal->isAscii()) { 147 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 148 << StrArg->getSourceRange(); 149 return true; 150 } 151 152 TheCall->setType(Ty); 153 return false; 154 } 155 156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 157 // We need at least one argument. 158 if (TheCall->getNumArgs() < 1) { 159 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 160 << 0 << 1 << TheCall->getNumArgs() 161 << TheCall->getCallee()->getSourceRange(); 162 return true; 163 } 164 165 // All arguments should be wide string literals. 166 for (Expr *Arg : TheCall->arguments()) { 167 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 168 if (!Literal || !Literal->isWide()) { 169 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 170 << Arg->getSourceRange(); 171 return true; 172 } 173 } 174 175 return false; 176 } 177 178 /// Check that the argument to __builtin_addressof is a glvalue, and set the 179 /// result type to the corresponding pointer type. 180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 181 if (checkArgCount(S, TheCall, 1)) 182 return true; 183 184 ExprResult Arg(TheCall->getArg(0)); 185 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 186 if (ResultType.isNull()) 187 return true; 188 189 TheCall->setArg(0, Arg.get()); 190 TheCall->setType(ResultType); 191 return false; 192 } 193 194 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 195 if (checkArgCount(S, TheCall, 3)) 196 return true; 197 198 // First two arguments should be integers. 199 for (unsigned I = 0; I < 2; ++I) { 200 ExprResult Arg = TheCall->getArg(I); 201 QualType Ty = Arg.get()->getType(); 202 if (!Ty->isIntegerType()) { 203 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 204 << Ty << Arg.get()->getSourceRange(); 205 return true; 206 } 207 InitializedEntity Entity = InitializedEntity::InitializeParameter( 208 S.getASTContext(), Ty, /*consume*/ false); 209 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 210 if (Arg.isInvalid()) 211 return true; 212 TheCall->setArg(I, Arg.get()); 213 } 214 215 // Third argument should be a pointer to a non-const integer. 216 // IRGen correctly handles volatile, restrict, and address spaces, and 217 // the other qualifiers aren't possible. 218 { 219 ExprResult Arg = TheCall->getArg(2); 220 QualType Ty = Arg.get()->getType(); 221 const auto *PtrTy = Ty->getAs<PointerType>(); 222 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 223 !PtrTy->getPointeeType().isConstQualified())) { 224 S.Diag(Arg.get()->getBeginLoc(), 225 diag::err_overflow_builtin_must_be_ptr_int) 226 << Ty << Arg.get()->getSourceRange(); 227 return true; 228 } 229 InitializedEntity Entity = InitializedEntity::InitializeParameter( 230 S.getASTContext(), Ty, /*consume*/ false); 231 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 232 if (Arg.isInvalid()) 233 return true; 234 TheCall->setArg(2, Arg.get()); 235 } 236 return false; 237 } 238 239 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 240 CallExpr *TheCall, unsigned SizeIdx, 241 unsigned DstSizeIdx, 242 StringRef LikelyMacroName) { 243 if (TheCall->getNumArgs() <= SizeIdx || 244 TheCall->getNumArgs() <= DstSizeIdx) 245 return; 246 247 const Expr *SizeArg = TheCall->getArg(SizeIdx); 248 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 249 250 Expr::EvalResult SizeResult, DstSizeResult; 251 252 // find out if both sizes are known at compile time 253 if (!SizeArg->EvaluateAsInt(SizeResult, S.Context) || 254 !DstSizeArg->EvaluateAsInt(DstSizeResult, S.Context)) 255 return; 256 257 llvm::APSInt Size = SizeResult.Val.getInt(); 258 llvm::APSInt DstSize = DstSizeResult.Val.getInt(); 259 260 if (Size.ule(DstSize)) 261 return; 262 263 // Confirmed overflow, so generate the diagnostic. 264 StringRef FunctionName = FDecl->getName(); 265 SourceLocation SL = TheCall->getBeginLoc(); 266 SourceManager &SM = S.getSourceManager(); 267 // If we're in an expansion of a macro whose name corresponds to this builtin, 268 // use the simple macro name and location. 269 if (SL.isMacroID() && Lexer::getImmediateMacroName(SL, SM, S.getLangOpts()) == 270 LikelyMacroName) { 271 FunctionName = LikelyMacroName; 272 SL = SM.getImmediateMacroCallerLoc(SL); 273 } 274 275 S.Diag(SL, diag::warn_memcpy_chk_overflow) 276 << FunctionName << DstSize.toString(/*Radix=*/10) 277 << Size.toString(/*Radix=*/10); 278 } 279 280 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 281 if (checkArgCount(S, BuiltinCall, 2)) 282 return true; 283 284 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 285 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 286 Expr *Call = BuiltinCall->getArg(0); 287 Expr *Chain = BuiltinCall->getArg(1); 288 289 if (Call->getStmtClass() != Stmt::CallExprClass) { 290 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 291 << Call->getSourceRange(); 292 return true; 293 } 294 295 auto CE = cast<CallExpr>(Call); 296 if (CE->getCallee()->getType()->isBlockPointerType()) { 297 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 298 << Call->getSourceRange(); 299 return true; 300 } 301 302 const Decl *TargetDecl = CE->getCalleeDecl(); 303 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 304 if (FD->getBuiltinID()) { 305 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 306 << Call->getSourceRange(); 307 return true; 308 } 309 310 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 311 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 312 << Call->getSourceRange(); 313 return true; 314 } 315 316 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 317 if (ChainResult.isInvalid()) 318 return true; 319 if (!ChainResult.get()->getType()->isPointerType()) { 320 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 321 << Chain->getSourceRange(); 322 return true; 323 } 324 325 QualType ReturnTy = CE->getCallReturnType(S.Context); 326 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 327 QualType BuiltinTy = S.Context.getFunctionType( 328 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 329 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 330 331 Builtin = 332 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 333 334 BuiltinCall->setType(CE->getType()); 335 BuiltinCall->setValueKind(CE->getValueKind()); 336 BuiltinCall->setObjectKind(CE->getObjectKind()); 337 BuiltinCall->setCallee(Builtin); 338 BuiltinCall->setArg(1, ChainResult.get()); 339 340 return false; 341 } 342 343 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 344 Scope::ScopeFlags NeededScopeFlags, 345 unsigned DiagID) { 346 // Scopes aren't available during instantiation. Fortunately, builtin 347 // functions cannot be template args so they cannot be formed through template 348 // instantiation. Therefore checking once during the parse is sufficient. 349 if (SemaRef.inTemplateInstantiation()) 350 return false; 351 352 Scope *S = SemaRef.getCurScope(); 353 while (S && !S->isSEHExceptScope()) 354 S = S->getParent(); 355 if (!S || !(S->getFlags() & NeededScopeFlags)) { 356 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 357 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 358 << DRE->getDecl()->getIdentifier(); 359 return true; 360 } 361 362 return false; 363 } 364 365 static inline bool isBlockPointer(Expr *Arg) { 366 return Arg->getType()->isBlockPointerType(); 367 } 368 369 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 370 /// void*, which is a requirement of device side enqueue. 371 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 372 const BlockPointerType *BPT = 373 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 374 ArrayRef<QualType> Params = 375 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 376 unsigned ArgCounter = 0; 377 bool IllegalParams = false; 378 // Iterate through the block parameters until either one is found that is not 379 // a local void*, or the block is valid. 380 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 381 I != E; ++I, ++ArgCounter) { 382 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 383 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 384 LangAS::opencl_local) { 385 // Get the location of the error. If a block literal has been passed 386 // (BlockExpr) then we can point straight to the offending argument, 387 // else we just point to the variable reference. 388 SourceLocation ErrorLoc; 389 if (isa<BlockExpr>(BlockArg)) { 390 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 391 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 392 } else if (isa<DeclRefExpr>(BlockArg)) { 393 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 394 } 395 S.Diag(ErrorLoc, 396 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 397 IllegalParams = true; 398 } 399 } 400 401 return IllegalParams; 402 } 403 404 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 405 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 406 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 407 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 408 return true; 409 } 410 return false; 411 } 412 413 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 414 if (checkArgCount(S, TheCall, 2)) 415 return true; 416 417 if (checkOpenCLSubgroupExt(S, TheCall)) 418 return true; 419 420 // First argument is an ndrange_t type. 421 Expr *NDRangeArg = TheCall->getArg(0); 422 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 423 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 424 << TheCall->getDirectCallee() << "'ndrange_t'"; 425 return true; 426 } 427 428 Expr *BlockArg = TheCall->getArg(1); 429 if (!isBlockPointer(BlockArg)) { 430 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 431 << TheCall->getDirectCallee() << "block"; 432 return true; 433 } 434 return checkOpenCLBlockArgs(S, BlockArg); 435 } 436 437 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 438 /// get_kernel_work_group_size 439 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 440 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 441 if (checkArgCount(S, TheCall, 1)) 442 return true; 443 444 Expr *BlockArg = TheCall->getArg(0); 445 if (!isBlockPointer(BlockArg)) { 446 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 447 << TheCall->getDirectCallee() << "block"; 448 return true; 449 } 450 return checkOpenCLBlockArgs(S, BlockArg); 451 } 452 453 /// Diagnose integer type and any valid implicit conversion to it. 454 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 455 const QualType &IntType); 456 457 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 458 unsigned Start, unsigned End) { 459 bool IllegalParams = false; 460 for (unsigned I = Start; I <= End; ++I) 461 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 462 S.Context.getSizeType()); 463 return IllegalParams; 464 } 465 466 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 467 /// 'local void*' parameter of passed block. 468 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 469 Expr *BlockArg, 470 unsigned NumNonVarArgs) { 471 const BlockPointerType *BPT = 472 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 473 unsigned NumBlockParams = 474 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 475 unsigned TotalNumArgs = TheCall->getNumArgs(); 476 477 // For each argument passed to the block, a corresponding uint needs to 478 // be passed to describe the size of the local memory. 479 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 480 S.Diag(TheCall->getBeginLoc(), 481 diag::err_opencl_enqueue_kernel_local_size_args); 482 return true; 483 } 484 485 // Check that the sizes of the local memory are specified by integers. 486 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 487 TotalNumArgs - 1); 488 } 489 490 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 491 /// overload formats specified in Table 6.13.17.1. 492 /// int enqueue_kernel(queue_t queue, 493 /// kernel_enqueue_flags_t flags, 494 /// const ndrange_t ndrange, 495 /// void (^block)(void)) 496 /// int enqueue_kernel(queue_t queue, 497 /// kernel_enqueue_flags_t flags, 498 /// const ndrange_t ndrange, 499 /// uint num_events_in_wait_list, 500 /// clk_event_t *event_wait_list, 501 /// clk_event_t *event_ret, 502 /// void (^block)(void)) 503 /// int enqueue_kernel(queue_t queue, 504 /// kernel_enqueue_flags_t flags, 505 /// const ndrange_t ndrange, 506 /// void (^block)(local void*, ...), 507 /// uint size0, ...) 508 /// int enqueue_kernel(queue_t queue, 509 /// kernel_enqueue_flags_t flags, 510 /// const ndrange_t ndrange, 511 /// uint num_events_in_wait_list, 512 /// clk_event_t *event_wait_list, 513 /// clk_event_t *event_ret, 514 /// void (^block)(local void*, ...), 515 /// uint size0, ...) 516 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 517 unsigned NumArgs = TheCall->getNumArgs(); 518 519 if (NumArgs < 4) { 520 S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args); 521 return true; 522 } 523 524 Expr *Arg0 = TheCall->getArg(0); 525 Expr *Arg1 = TheCall->getArg(1); 526 Expr *Arg2 = TheCall->getArg(2); 527 Expr *Arg3 = TheCall->getArg(3); 528 529 // First argument always needs to be a queue_t type. 530 if (!Arg0->getType()->isQueueT()) { 531 S.Diag(TheCall->getArg(0)->getBeginLoc(), 532 diag::err_opencl_builtin_expected_type) 533 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 534 return true; 535 } 536 537 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 538 if (!Arg1->getType()->isIntegerType()) { 539 S.Diag(TheCall->getArg(1)->getBeginLoc(), 540 diag::err_opencl_builtin_expected_type) 541 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 542 return true; 543 } 544 545 // Third argument is always an ndrange_t type. 546 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 547 S.Diag(TheCall->getArg(2)->getBeginLoc(), 548 diag::err_opencl_builtin_expected_type) 549 << TheCall->getDirectCallee() << "'ndrange_t'"; 550 return true; 551 } 552 553 // With four arguments, there is only one form that the function could be 554 // called in: no events and no variable arguments. 555 if (NumArgs == 4) { 556 // check that the last argument is the right block type. 557 if (!isBlockPointer(Arg3)) { 558 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 559 << TheCall->getDirectCallee() << "block"; 560 return true; 561 } 562 // we have a block type, check the prototype 563 const BlockPointerType *BPT = 564 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 565 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 566 S.Diag(Arg3->getBeginLoc(), 567 diag::err_opencl_enqueue_kernel_blocks_no_args); 568 return true; 569 } 570 return false; 571 } 572 // we can have block + varargs. 573 if (isBlockPointer(Arg3)) 574 return (checkOpenCLBlockArgs(S, Arg3) || 575 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 576 // last two cases with either exactly 7 args or 7 args and varargs. 577 if (NumArgs >= 7) { 578 // check common block argument. 579 Expr *Arg6 = TheCall->getArg(6); 580 if (!isBlockPointer(Arg6)) { 581 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 582 << TheCall->getDirectCallee() << "block"; 583 return true; 584 } 585 if (checkOpenCLBlockArgs(S, Arg6)) 586 return true; 587 588 // Forth argument has to be any integer type. 589 if (!Arg3->getType()->isIntegerType()) { 590 S.Diag(TheCall->getArg(3)->getBeginLoc(), 591 diag::err_opencl_builtin_expected_type) 592 << TheCall->getDirectCallee() << "integer"; 593 return true; 594 } 595 // check remaining common arguments. 596 Expr *Arg4 = TheCall->getArg(4); 597 Expr *Arg5 = TheCall->getArg(5); 598 599 // Fifth argument is always passed as a pointer to clk_event_t. 600 if (!Arg4->isNullPointerConstant(S.Context, 601 Expr::NPC_ValueDependentIsNotNull) && 602 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 603 S.Diag(TheCall->getArg(4)->getBeginLoc(), 604 diag::err_opencl_builtin_expected_type) 605 << TheCall->getDirectCallee() 606 << S.Context.getPointerType(S.Context.OCLClkEventTy); 607 return true; 608 } 609 610 // Sixth argument is always passed as a pointer to clk_event_t. 611 if (!Arg5->isNullPointerConstant(S.Context, 612 Expr::NPC_ValueDependentIsNotNull) && 613 !(Arg5->getType()->isPointerType() && 614 Arg5->getType()->getPointeeType()->isClkEventT())) { 615 S.Diag(TheCall->getArg(5)->getBeginLoc(), 616 diag::err_opencl_builtin_expected_type) 617 << TheCall->getDirectCallee() 618 << S.Context.getPointerType(S.Context.OCLClkEventTy); 619 return true; 620 } 621 622 if (NumArgs == 7) 623 return false; 624 625 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 626 } 627 628 // None of the specific case has been detected, give generic error 629 S.Diag(TheCall->getBeginLoc(), 630 diag::err_opencl_enqueue_kernel_incorrect_args); 631 return true; 632 } 633 634 /// Returns OpenCL access qual. 635 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 636 return D->getAttr<OpenCLAccessAttr>(); 637 } 638 639 /// Returns true if pipe element type is different from the pointer. 640 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 641 const Expr *Arg0 = Call->getArg(0); 642 // First argument type should always be pipe. 643 if (!Arg0->getType()->isPipeType()) { 644 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 645 << Call->getDirectCallee() << Arg0->getSourceRange(); 646 return true; 647 } 648 OpenCLAccessAttr *AccessQual = 649 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 650 // Validates the access qualifier is compatible with the call. 651 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 652 // read_only and write_only, and assumed to be read_only if no qualifier is 653 // specified. 654 switch (Call->getDirectCallee()->getBuiltinID()) { 655 case Builtin::BIread_pipe: 656 case Builtin::BIreserve_read_pipe: 657 case Builtin::BIcommit_read_pipe: 658 case Builtin::BIwork_group_reserve_read_pipe: 659 case Builtin::BIsub_group_reserve_read_pipe: 660 case Builtin::BIwork_group_commit_read_pipe: 661 case Builtin::BIsub_group_commit_read_pipe: 662 if (!(!AccessQual || AccessQual->isReadOnly())) { 663 S.Diag(Arg0->getBeginLoc(), 664 diag::err_opencl_builtin_pipe_invalid_access_modifier) 665 << "read_only" << Arg0->getSourceRange(); 666 return true; 667 } 668 break; 669 case Builtin::BIwrite_pipe: 670 case Builtin::BIreserve_write_pipe: 671 case Builtin::BIcommit_write_pipe: 672 case Builtin::BIwork_group_reserve_write_pipe: 673 case Builtin::BIsub_group_reserve_write_pipe: 674 case Builtin::BIwork_group_commit_write_pipe: 675 case Builtin::BIsub_group_commit_write_pipe: 676 if (!(AccessQual && AccessQual->isWriteOnly())) { 677 S.Diag(Arg0->getBeginLoc(), 678 diag::err_opencl_builtin_pipe_invalid_access_modifier) 679 << "write_only" << Arg0->getSourceRange(); 680 return true; 681 } 682 break; 683 default: 684 break; 685 } 686 return false; 687 } 688 689 /// Returns true if pipe element type is different from the pointer. 690 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 691 const Expr *Arg0 = Call->getArg(0); 692 const Expr *ArgIdx = Call->getArg(Idx); 693 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 694 const QualType EltTy = PipeTy->getElementType(); 695 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 696 // The Idx argument should be a pointer and the type of the pointer and 697 // the type of pipe element should also be the same. 698 if (!ArgTy || 699 !S.Context.hasSameType( 700 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 701 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 702 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 703 << ArgIdx->getType() << ArgIdx->getSourceRange(); 704 return true; 705 } 706 return false; 707 } 708 709 // Performs semantic analysis for the read/write_pipe call. 710 // \param S Reference to the semantic analyzer. 711 // \param Call A pointer to the builtin call. 712 // \return True if a semantic error has been found, false otherwise. 713 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 714 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 715 // functions have two forms. 716 switch (Call->getNumArgs()) { 717 case 2: 718 if (checkOpenCLPipeArg(S, Call)) 719 return true; 720 // The call with 2 arguments should be 721 // read/write_pipe(pipe T, T*). 722 // Check packet type T. 723 if (checkOpenCLPipePacketType(S, Call, 1)) 724 return true; 725 break; 726 727 case 4: { 728 if (checkOpenCLPipeArg(S, Call)) 729 return true; 730 // The call with 4 arguments should be 731 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 732 // Check reserve_id_t. 733 if (!Call->getArg(1)->getType()->isReserveIDT()) { 734 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 735 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 736 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 737 return true; 738 } 739 740 // Check the index. 741 const Expr *Arg2 = Call->getArg(2); 742 if (!Arg2->getType()->isIntegerType() && 743 !Arg2->getType()->isUnsignedIntegerType()) { 744 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 745 << Call->getDirectCallee() << S.Context.UnsignedIntTy 746 << Arg2->getType() << Arg2->getSourceRange(); 747 return true; 748 } 749 750 // Check packet type T. 751 if (checkOpenCLPipePacketType(S, Call, 3)) 752 return true; 753 } break; 754 default: 755 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 756 << Call->getDirectCallee() << Call->getSourceRange(); 757 return true; 758 } 759 760 return false; 761 } 762 763 // Performs a semantic analysis on the {work_group_/sub_group_ 764 // /_}reserve_{read/write}_pipe 765 // \param S Reference to the semantic analyzer. 766 // \param Call The call to the builtin function to be analyzed. 767 // \return True if a semantic error was found, false otherwise. 768 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 769 if (checkArgCount(S, Call, 2)) 770 return true; 771 772 if (checkOpenCLPipeArg(S, Call)) 773 return true; 774 775 // Check the reserve size. 776 if (!Call->getArg(1)->getType()->isIntegerType() && 777 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 778 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 779 << Call->getDirectCallee() << S.Context.UnsignedIntTy 780 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 781 return true; 782 } 783 784 // Since return type of reserve_read/write_pipe built-in function is 785 // reserve_id_t, which is not defined in the builtin def file , we used int 786 // as return type and need to override the return type of these functions. 787 Call->setType(S.Context.OCLReserveIDTy); 788 789 return false; 790 } 791 792 // Performs a semantic analysis on {work_group_/sub_group_ 793 // /_}commit_{read/write}_pipe 794 // \param S Reference to the semantic analyzer. 795 // \param Call The call to the builtin function to be analyzed. 796 // \return True if a semantic error was found, false otherwise. 797 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 798 if (checkArgCount(S, Call, 2)) 799 return true; 800 801 if (checkOpenCLPipeArg(S, Call)) 802 return true; 803 804 // Check reserve_id_t. 805 if (!Call->getArg(1)->getType()->isReserveIDT()) { 806 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 807 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 808 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 809 return true; 810 } 811 812 return false; 813 } 814 815 // Performs a semantic analysis on the call to built-in Pipe 816 // Query Functions. 817 // \param S Reference to the semantic analyzer. 818 // \param Call The call to the builtin function to be analyzed. 819 // \return True if a semantic error was found, false otherwise. 820 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 821 if (checkArgCount(S, Call, 1)) 822 return true; 823 824 if (!Call->getArg(0)->getType()->isPipeType()) { 825 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 826 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 827 return true; 828 } 829 830 return false; 831 } 832 833 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 834 // Performs semantic analysis for the to_global/local/private call. 835 // \param S Reference to the semantic analyzer. 836 // \param BuiltinID ID of the builtin function. 837 // \param Call A pointer to the builtin call. 838 // \return True if a semantic error has been found, false otherwise. 839 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 840 CallExpr *Call) { 841 if (Call->getNumArgs() != 1) { 842 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 843 << Call->getDirectCallee() << Call->getSourceRange(); 844 return true; 845 } 846 847 auto RT = Call->getArg(0)->getType(); 848 if (!RT->isPointerType() || RT->getPointeeType() 849 .getAddressSpace() == LangAS::opencl_constant) { 850 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 851 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 852 return true; 853 } 854 855 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 856 S.Diag(Call->getArg(0)->getBeginLoc(), 857 diag::warn_opencl_generic_address_space_arg) 858 << Call->getDirectCallee()->getNameInfo().getAsString() 859 << Call->getArg(0)->getSourceRange(); 860 } 861 862 RT = RT->getPointeeType(); 863 auto Qual = RT.getQualifiers(); 864 switch (BuiltinID) { 865 case Builtin::BIto_global: 866 Qual.setAddressSpace(LangAS::opencl_global); 867 break; 868 case Builtin::BIto_local: 869 Qual.setAddressSpace(LangAS::opencl_local); 870 break; 871 case Builtin::BIto_private: 872 Qual.setAddressSpace(LangAS::opencl_private); 873 break; 874 default: 875 llvm_unreachable("Invalid builtin function"); 876 } 877 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 878 RT.getUnqualifiedType(), Qual))); 879 880 return false; 881 } 882 883 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 884 if (checkArgCount(S, TheCall, 1)) 885 return ExprError(); 886 887 // Compute __builtin_launder's parameter type from the argument. 888 // The parameter type is: 889 // * The type of the argument if it's not an array or function type, 890 // Otherwise, 891 // * The decayed argument type. 892 QualType ParamTy = [&]() { 893 QualType ArgTy = TheCall->getArg(0)->getType(); 894 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 895 return S.Context.getPointerType(Ty->getElementType()); 896 if (ArgTy->isFunctionType()) { 897 return S.Context.getPointerType(ArgTy); 898 } 899 return ArgTy; 900 }(); 901 902 TheCall->setType(ParamTy); 903 904 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 905 if (!ParamTy->isPointerType()) 906 return 0; 907 if (ParamTy->isFunctionPointerType()) 908 return 1; 909 if (ParamTy->isVoidPointerType()) 910 return 2; 911 return llvm::Optional<unsigned>{}; 912 }(); 913 if (DiagSelect.hasValue()) { 914 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 915 << DiagSelect.getValue() << TheCall->getSourceRange(); 916 return ExprError(); 917 } 918 919 // We either have an incomplete class type, or we have a class template 920 // whose instantiation has not been forced. Example: 921 // 922 // template <class T> struct Foo { T value; }; 923 // Foo<int> *p = nullptr; 924 // auto *d = __builtin_launder(p); 925 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 926 diag::err_incomplete_type)) 927 return ExprError(); 928 929 assert(ParamTy->getPointeeType()->isObjectType() && 930 "Unhandled non-object pointer case"); 931 932 InitializedEntity Entity = 933 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 934 ExprResult Arg = 935 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 936 if (Arg.isInvalid()) 937 return ExprError(); 938 TheCall->setArg(0, Arg.get()); 939 940 return TheCall; 941 } 942 943 // Emit an error and return true if the current architecture is not in the list 944 // of supported architectures. 945 static bool 946 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 947 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 948 llvm::Triple::ArchType CurArch = 949 S.getASTContext().getTargetInfo().getTriple().getArch(); 950 if (llvm::is_contained(SupportedArchs, CurArch)) 951 return false; 952 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 953 << TheCall->getSourceRange(); 954 return true; 955 } 956 957 ExprResult 958 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 959 CallExpr *TheCall) { 960 ExprResult TheCallResult(TheCall); 961 962 // Find out if any arguments are required to be integer constant expressions. 963 unsigned ICEArguments = 0; 964 ASTContext::GetBuiltinTypeError Error; 965 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 966 if (Error != ASTContext::GE_None) 967 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 968 969 // If any arguments are required to be ICE's, check and diagnose. 970 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 971 // Skip arguments not required to be ICE's. 972 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 973 974 llvm::APSInt Result; 975 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 976 return true; 977 ICEArguments &= ~(1 << ArgNo); 978 } 979 980 switch (BuiltinID) { 981 case Builtin::BI__builtin___CFStringMakeConstantString: 982 assert(TheCall->getNumArgs() == 1 && 983 "Wrong # arguments to builtin CFStringMakeConstantString"); 984 if (CheckObjCString(TheCall->getArg(0))) 985 return ExprError(); 986 break; 987 case Builtin::BI__builtin_ms_va_start: 988 case Builtin::BI__builtin_stdarg_start: 989 case Builtin::BI__builtin_va_start: 990 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 991 return ExprError(); 992 break; 993 case Builtin::BI__va_start: { 994 switch (Context.getTargetInfo().getTriple().getArch()) { 995 case llvm::Triple::aarch64: 996 case llvm::Triple::arm: 997 case llvm::Triple::thumb: 998 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 999 return ExprError(); 1000 break; 1001 default: 1002 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1003 return ExprError(); 1004 break; 1005 } 1006 break; 1007 } 1008 1009 // The acquire, release, and no fence variants are ARM and AArch64 only. 1010 case Builtin::BI_interlockedbittestandset_acq: 1011 case Builtin::BI_interlockedbittestandset_rel: 1012 case Builtin::BI_interlockedbittestandset_nf: 1013 case Builtin::BI_interlockedbittestandreset_acq: 1014 case Builtin::BI_interlockedbittestandreset_rel: 1015 case Builtin::BI_interlockedbittestandreset_nf: 1016 if (CheckBuiltinTargetSupport( 1017 *this, BuiltinID, TheCall, 1018 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1019 return ExprError(); 1020 break; 1021 1022 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1023 case Builtin::BI_bittest64: 1024 case Builtin::BI_bittestandcomplement64: 1025 case Builtin::BI_bittestandreset64: 1026 case Builtin::BI_bittestandset64: 1027 case Builtin::BI_interlockedbittestandreset64: 1028 case Builtin::BI_interlockedbittestandset64: 1029 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1030 {llvm::Triple::x86_64, llvm::Triple::arm, 1031 llvm::Triple::thumb, llvm::Triple::aarch64})) 1032 return ExprError(); 1033 break; 1034 1035 case Builtin::BI__builtin_isgreater: 1036 case Builtin::BI__builtin_isgreaterequal: 1037 case Builtin::BI__builtin_isless: 1038 case Builtin::BI__builtin_islessequal: 1039 case Builtin::BI__builtin_islessgreater: 1040 case Builtin::BI__builtin_isunordered: 1041 if (SemaBuiltinUnorderedCompare(TheCall)) 1042 return ExprError(); 1043 break; 1044 case Builtin::BI__builtin_fpclassify: 1045 if (SemaBuiltinFPClassification(TheCall, 6)) 1046 return ExprError(); 1047 break; 1048 case Builtin::BI__builtin_isfinite: 1049 case Builtin::BI__builtin_isinf: 1050 case Builtin::BI__builtin_isinf_sign: 1051 case Builtin::BI__builtin_isnan: 1052 case Builtin::BI__builtin_isnormal: 1053 case Builtin::BI__builtin_signbit: 1054 case Builtin::BI__builtin_signbitf: 1055 case Builtin::BI__builtin_signbitl: 1056 if (SemaBuiltinFPClassification(TheCall, 1)) 1057 return ExprError(); 1058 break; 1059 case Builtin::BI__builtin_shufflevector: 1060 return SemaBuiltinShuffleVector(TheCall); 1061 // TheCall will be freed by the smart pointer here, but that's fine, since 1062 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1063 case Builtin::BI__builtin_prefetch: 1064 if (SemaBuiltinPrefetch(TheCall)) 1065 return ExprError(); 1066 break; 1067 case Builtin::BI__builtin_alloca_with_align: 1068 if (SemaBuiltinAllocaWithAlign(TheCall)) 1069 return ExprError(); 1070 break; 1071 case Builtin::BI__assume: 1072 case Builtin::BI__builtin_assume: 1073 if (SemaBuiltinAssume(TheCall)) 1074 return ExprError(); 1075 break; 1076 case Builtin::BI__builtin_assume_aligned: 1077 if (SemaBuiltinAssumeAligned(TheCall)) 1078 return ExprError(); 1079 break; 1080 case Builtin::BI__builtin_object_size: 1081 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1082 return ExprError(); 1083 break; 1084 case Builtin::BI__builtin_longjmp: 1085 if (SemaBuiltinLongjmp(TheCall)) 1086 return ExprError(); 1087 break; 1088 case Builtin::BI__builtin_setjmp: 1089 if (SemaBuiltinSetjmp(TheCall)) 1090 return ExprError(); 1091 break; 1092 case Builtin::BI_setjmp: 1093 case Builtin::BI_setjmpex: 1094 if (checkArgCount(*this, TheCall, 1)) 1095 return true; 1096 break; 1097 case Builtin::BI__builtin_classify_type: 1098 if (checkArgCount(*this, TheCall, 1)) return true; 1099 TheCall->setType(Context.IntTy); 1100 break; 1101 case Builtin::BI__builtin_constant_p: 1102 if (checkArgCount(*this, TheCall, 1)) return true; 1103 TheCall->setType(Context.IntTy); 1104 break; 1105 case Builtin::BI__builtin_launder: 1106 return SemaBuiltinLaunder(*this, TheCall); 1107 case Builtin::BI__sync_fetch_and_add: 1108 case Builtin::BI__sync_fetch_and_add_1: 1109 case Builtin::BI__sync_fetch_and_add_2: 1110 case Builtin::BI__sync_fetch_and_add_4: 1111 case Builtin::BI__sync_fetch_and_add_8: 1112 case Builtin::BI__sync_fetch_and_add_16: 1113 case Builtin::BI__sync_fetch_and_sub: 1114 case Builtin::BI__sync_fetch_and_sub_1: 1115 case Builtin::BI__sync_fetch_and_sub_2: 1116 case Builtin::BI__sync_fetch_and_sub_4: 1117 case Builtin::BI__sync_fetch_and_sub_8: 1118 case Builtin::BI__sync_fetch_and_sub_16: 1119 case Builtin::BI__sync_fetch_and_or: 1120 case Builtin::BI__sync_fetch_and_or_1: 1121 case Builtin::BI__sync_fetch_and_or_2: 1122 case Builtin::BI__sync_fetch_and_or_4: 1123 case Builtin::BI__sync_fetch_and_or_8: 1124 case Builtin::BI__sync_fetch_and_or_16: 1125 case Builtin::BI__sync_fetch_and_and: 1126 case Builtin::BI__sync_fetch_and_and_1: 1127 case Builtin::BI__sync_fetch_and_and_2: 1128 case Builtin::BI__sync_fetch_and_and_4: 1129 case Builtin::BI__sync_fetch_and_and_8: 1130 case Builtin::BI__sync_fetch_and_and_16: 1131 case Builtin::BI__sync_fetch_and_xor: 1132 case Builtin::BI__sync_fetch_and_xor_1: 1133 case Builtin::BI__sync_fetch_and_xor_2: 1134 case Builtin::BI__sync_fetch_and_xor_4: 1135 case Builtin::BI__sync_fetch_and_xor_8: 1136 case Builtin::BI__sync_fetch_and_xor_16: 1137 case Builtin::BI__sync_fetch_and_nand: 1138 case Builtin::BI__sync_fetch_and_nand_1: 1139 case Builtin::BI__sync_fetch_and_nand_2: 1140 case Builtin::BI__sync_fetch_and_nand_4: 1141 case Builtin::BI__sync_fetch_and_nand_8: 1142 case Builtin::BI__sync_fetch_and_nand_16: 1143 case Builtin::BI__sync_add_and_fetch: 1144 case Builtin::BI__sync_add_and_fetch_1: 1145 case Builtin::BI__sync_add_and_fetch_2: 1146 case Builtin::BI__sync_add_and_fetch_4: 1147 case Builtin::BI__sync_add_and_fetch_8: 1148 case Builtin::BI__sync_add_and_fetch_16: 1149 case Builtin::BI__sync_sub_and_fetch: 1150 case Builtin::BI__sync_sub_and_fetch_1: 1151 case Builtin::BI__sync_sub_and_fetch_2: 1152 case Builtin::BI__sync_sub_and_fetch_4: 1153 case Builtin::BI__sync_sub_and_fetch_8: 1154 case Builtin::BI__sync_sub_and_fetch_16: 1155 case Builtin::BI__sync_and_and_fetch: 1156 case Builtin::BI__sync_and_and_fetch_1: 1157 case Builtin::BI__sync_and_and_fetch_2: 1158 case Builtin::BI__sync_and_and_fetch_4: 1159 case Builtin::BI__sync_and_and_fetch_8: 1160 case Builtin::BI__sync_and_and_fetch_16: 1161 case Builtin::BI__sync_or_and_fetch: 1162 case Builtin::BI__sync_or_and_fetch_1: 1163 case Builtin::BI__sync_or_and_fetch_2: 1164 case Builtin::BI__sync_or_and_fetch_4: 1165 case Builtin::BI__sync_or_and_fetch_8: 1166 case Builtin::BI__sync_or_and_fetch_16: 1167 case Builtin::BI__sync_xor_and_fetch: 1168 case Builtin::BI__sync_xor_and_fetch_1: 1169 case Builtin::BI__sync_xor_and_fetch_2: 1170 case Builtin::BI__sync_xor_and_fetch_4: 1171 case Builtin::BI__sync_xor_and_fetch_8: 1172 case Builtin::BI__sync_xor_and_fetch_16: 1173 case Builtin::BI__sync_nand_and_fetch: 1174 case Builtin::BI__sync_nand_and_fetch_1: 1175 case Builtin::BI__sync_nand_and_fetch_2: 1176 case Builtin::BI__sync_nand_and_fetch_4: 1177 case Builtin::BI__sync_nand_and_fetch_8: 1178 case Builtin::BI__sync_nand_and_fetch_16: 1179 case Builtin::BI__sync_val_compare_and_swap: 1180 case Builtin::BI__sync_val_compare_and_swap_1: 1181 case Builtin::BI__sync_val_compare_and_swap_2: 1182 case Builtin::BI__sync_val_compare_and_swap_4: 1183 case Builtin::BI__sync_val_compare_and_swap_8: 1184 case Builtin::BI__sync_val_compare_and_swap_16: 1185 case Builtin::BI__sync_bool_compare_and_swap: 1186 case Builtin::BI__sync_bool_compare_and_swap_1: 1187 case Builtin::BI__sync_bool_compare_and_swap_2: 1188 case Builtin::BI__sync_bool_compare_and_swap_4: 1189 case Builtin::BI__sync_bool_compare_and_swap_8: 1190 case Builtin::BI__sync_bool_compare_and_swap_16: 1191 case Builtin::BI__sync_lock_test_and_set: 1192 case Builtin::BI__sync_lock_test_and_set_1: 1193 case Builtin::BI__sync_lock_test_and_set_2: 1194 case Builtin::BI__sync_lock_test_and_set_4: 1195 case Builtin::BI__sync_lock_test_and_set_8: 1196 case Builtin::BI__sync_lock_test_and_set_16: 1197 case Builtin::BI__sync_lock_release: 1198 case Builtin::BI__sync_lock_release_1: 1199 case Builtin::BI__sync_lock_release_2: 1200 case Builtin::BI__sync_lock_release_4: 1201 case Builtin::BI__sync_lock_release_8: 1202 case Builtin::BI__sync_lock_release_16: 1203 case Builtin::BI__sync_swap: 1204 case Builtin::BI__sync_swap_1: 1205 case Builtin::BI__sync_swap_2: 1206 case Builtin::BI__sync_swap_4: 1207 case Builtin::BI__sync_swap_8: 1208 case Builtin::BI__sync_swap_16: 1209 return SemaBuiltinAtomicOverloaded(TheCallResult); 1210 case Builtin::BI__sync_synchronize: 1211 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1212 << TheCall->getCallee()->getSourceRange(); 1213 break; 1214 case Builtin::BI__builtin_nontemporal_load: 1215 case Builtin::BI__builtin_nontemporal_store: 1216 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1217 #define BUILTIN(ID, TYPE, ATTRS) 1218 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1219 case Builtin::BI##ID: \ 1220 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1221 #include "clang/Basic/Builtins.def" 1222 case Builtin::BI__annotation: 1223 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1224 return ExprError(); 1225 break; 1226 case Builtin::BI__builtin_annotation: 1227 if (SemaBuiltinAnnotation(*this, TheCall)) 1228 return ExprError(); 1229 break; 1230 case Builtin::BI__builtin_addressof: 1231 if (SemaBuiltinAddressof(*this, TheCall)) 1232 return ExprError(); 1233 break; 1234 case Builtin::BI__builtin_add_overflow: 1235 case Builtin::BI__builtin_sub_overflow: 1236 case Builtin::BI__builtin_mul_overflow: 1237 if (SemaBuiltinOverflow(*this, TheCall)) 1238 return ExprError(); 1239 break; 1240 case Builtin::BI__builtin_operator_new: 1241 case Builtin::BI__builtin_operator_delete: { 1242 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1243 ExprResult Res = 1244 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1245 if (Res.isInvalid()) 1246 CorrectDelayedTyposInExpr(TheCallResult.get()); 1247 return Res; 1248 } 1249 case Builtin::BI__builtin_dump_struct: { 1250 // We first want to ensure we are called with 2 arguments 1251 if (checkArgCount(*this, TheCall, 2)) 1252 return ExprError(); 1253 // Ensure that the first argument is of type 'struct XX *' 1254 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1255 const QualType PtrArgType = PtrArg->getType(); 1256 if (!PtrArgType->isPointerType() || 1257 !PtrArgType->getPointeeType()->isRecordType()) { 1258 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1259 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1260 << "structure pointer"; 1261 return ExprError(); 1262 } 1263 1264 // Ensure that the second argument is of type 'FunctionType' 1265 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1266 const QualType FnPtrArgType = FnPtrArg->getType(); 1267 if (!FnPtrArgType->isPointerType()) { 1268 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1269 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1270 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1271 return ExprError(); 1272 } 1273 1274 const auto *FuncType = 1275 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1276 1277 if (!FuncType) { 1278 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1279 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1280 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1281 return ExprError(); 1282 } 1283 1284 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1285 if (!FT->getNumParams()) { 1286 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1287 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1288 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1289 return ExprError(); 1290 } 1291 QualType PT = FT->getParamType(0); 1292 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1293 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1294 !PT->getPointeeType().isConstQualified()) { 1295 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1296 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1297 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1298 return ExprError(); 1299 } 1300 } 1301 1302 TheCall->setType(Context.IntTy); 1303 break; 1304 } 1305 1306 // check secure string manipulation functions where overflows 1307 // are detectable at compile time 1308 case Builtin::BI__builtin___memcpy_chk: 1309 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memcpy"); 1310 break; 1311 case Builtin::BI__builtin___memmove_chk: 1312 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memmove"); 1313 break; 1314 case Builtin::BI__builtin___memset_chk: 1315 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memset"); 1316 break; 1317 case Builtin::BI__builtin___strlcat_chk: 1318 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcat"); 1319 break; 1320 case Builtin::BI__builtin___strlcpy_chk: 1321 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcpy"); 1322 break; 1323 case Builtin::BI__builtin___strncat_chk: 1324 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncat"); 1325 break; 1326 case Builtin::BI__builtin___strncpy_chk: 1327 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncpy"); 1328 break; 1329 case Builtin::BI__builtin___stpncpy_chk: 1330 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "stpncpy"); 1331 break; 1332 case Builtin::BI__builtin___memccpy_chk: 1333 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4, "memccpy"); 1334 break; 1335 case Builtin::BI__builtin___snprintf_chk: 1336 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "snprintf"); 1337 break; 1338 case Builtin::BI__builtin___vsnprintf_chk: 1339 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "vsnprintf"); 1340 break; 1341 case Builtin::BI__builtin_call_with_static_chain: 1342 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1343 return ExprError(); 1344 break; 1345 case Builtin::BI__exception_code: 1346 case Builtin::BI_exception_code: 1347 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1348 diag::err_seh___except_block)) 1349 return ExprError(); 1350 break; 1351 case Builtin::BI__exception_info: 1352 case Builtin::BI_exception_info: 1353 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1354 diag::err_seh___except_filter)) 1355 return ExprError(); 1356 break; 1357 case Builtin::BI__GetExceptionInfo: 1358 if (checkArgCount(*this, TheCall, 1)) 1359 return ExprError(); 1360 1361 if (CheckCXXThrowOperand( 1362 TheCall->getBeginLoc(), 1363 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1364 TheCall)) 1365 return ExprError(); 1366 1367 TheCall->setType(Context.VoidPtrTy); 1368 break; 1369 // OpenCL v2.0, s6.13.16 - Pipe functions 1370 case Builtin::BIread_pipe: 1371 case Builtin::BIwrite_pipe: 1372 // Since those two functions are declared with var args, we need a semantic 1373 // check for the argument. 1374 if (SemaBuiltinRWPipe(*this, TheCall)) 1375 return ExprError(); 1376 break; 1377 case Builtin::BIreserve_read_pipe: 1378 case Builtin::BIreserve_write_pipe: 1379 case Builtin::BIwork_group_reserve_read_pipe: 1380 case Builtin::BIwork_group_reserve_write_pipe: 1381 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1382 return ExprError(); 1383 break; 1384 case Builtin::BIsub_group_reserve_read_pipe: 1385 case Builtin::BIsub_group_reserve_write_pipe: 1386 if (checkOpenCLSubgroupExt(*this, TheCall) || 1387 SemaBuiltinReserveRWPipe(*this, TheCall)) 1388 return ExprError(); 1389 break; 1390 case Builtin::BIcommit_read_pipe: 1391 case Builtin::BIcommit_write_pipe: 1392 case Builtin::BIwork_group_commit_read_pipe: 1393 case Builtin::BIwork_group_commit_write_pipe: 1394 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1395 return ExprError(); 1396 break; 1397 case Builtin::BIsub_group_commit_read_pipe: 1398 case Builtin::BIsub_group_commit_write_pipe: 1399 if (checkOpenCLSubgroupExt(*this, TheCall) || 1400 SemaBuiltinCommitRWPipe(*this, TheCall)) 1401 return ExprError(); 1402 break; 1403 case Builtin::BIget_pipe_num_packets: 1404 case Builtin::BIget_pipe_max_packets: 1405 if (SemaBuiltinPipePackets(*this, TheCall)) 1406 return ExprError(); 1407 break; 1408 case Builtin::BIto_global: 1409 case Builtin::BIto_local: 1410 case Builtin::BIto_private: 1411 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1412 return ExprError(); 1413 break; 1414 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1415 case Builtin::BIenqueue_kernel: 1416 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1417 return ExprError(); 1418 break; 1419 case Builtin::BIget_kernel_work_group_size: 1420 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1421 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1422 return ExprError(); 1423 break; 1424 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1425 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1426 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1427 return ExprError(); 1428 break; 1429 case Builtin::BI__builtin_os_log_format: 1430 case Builtin::BI__builtin_os_log_format_buffer_size: 1431 if (SemaBuiltinOSLogFormat(TheCall)) 1432 return ExprError(); 1433 break; 1434 } 1435 1436 // Since the target specific builtins for each arch overlap, only check those 1437 // of the arch we are compiling for. 1438 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1439 switch (Context.getTargetInfo().getTriple().getArch()) { 1440 case llvm::Triple::arm: 1441 case llvm::Triple::armeb: 1442 case llvm::Triple::thumb: 1443 case llvm::Triple::thumbeb: 1444 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1445 return ExprError(); 1446 break; 1447 case llvm::Triple::aarch64: 1448 case llvm::Triple::aarch64_be: 1449 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1450 return ExprError(); 1451 break; 1452 case llvm::Triple::hexagon: 1453 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1454 return ExprError(); 1455 break; 1456 case llvm::Triple::mips: 1457 case llvm::Triple::mipsel: 1458 case llvm::Triple::mips64: 1459 case llvm::Triple::mips64el: 1460 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1461 return ExprError(); 1462 break; 1463 case llvm::Triple::systemz: 1464 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1465 return ExprError(); 1466 break; 1467 case llvm::Triple::x86: 1468 case llvm::Triple::x86_64: 1469 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1470 return ExprError(); 1471 break; 1472 case llvm::Triple::ppc: 1473 case llvm::Triple::ppc64: 1474 case llvm::Triple::ppc64le: 1475 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1476 return ExprError(); 1477 break; 1478 default: 1479 break; 1480 } 1481 } 1482 1483 return TheCallResult; 1484 } 1485 1486 // Get the valid immediate range for the specified NEON type code. 1487 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1488 NeonTypeFlags Type(t); 1489 int IsQuad = ForceQuad ? true : Type.isQuad(); 1490 switch (Type.getEltType()) { 1491 case NeonTypeFlags::Int8: 1492 case NeonTypeFlags::Poly8: 1493 return shift ? 7 : (8 << IsQuad) - 1; 1494 case NeonTypeFlags::Int16: 1495 case NeonTypeFlags::Poly16: 1496 return shift ? 15 : (4 << IsQuad) - 1; 1497 case NeonTypeFlags::Int32: 1498 return shift ? 31 : (2 << IsQuad) - 1; 1499 case NeonTypeFlags::Int64: 1500 case NeonTypeFlags::Poly64: 1501 return shift ? 63 : (1 << IsQuad) - 1; 1502 case NeonTypeFlags::Poly128: 1503 return shift ? 127 : (1 << IsQuad) - 1; 1504 case NeonTypeFlags::Float16: 1505 assert(!shift && "cannot shift float types!"); 1506 return (4 << IsQuad) - 1; 1507 case NeonTypeFlags::Float32: 1508 assert(!shift && "cannot shift float types!"); 1509 return (2 << IsQuad) - 1; 1510 case NeonTypeFlags::Float64: 1511 assert(!shift && "cannot shift float types!"); 1512 return (1 << IsQuad) - 1; 1513 } 1514 llvm_unreachable("Invalid NeonTypeFlag!"); 1515 } 1516 1517 /// getNeonEltType - Return the QualType corresponding to the elements of 1518 /// the vector type specified by the NeonTypeFlags. This is used to check 1519 /// the pointer arguments for Neon load/store intrinsics. 1520 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1521 bool IsPolyUnsigned, bool IsInt64Long) { 1522 switch (Flags.getEltType()) { 1523 case NeonTypeFlags::Int8: 1524 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1525 case NeonTypeFlags::Int16: 1526 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1527 case NeonTypeFlags::Int32: 1528 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1529 case NeonTypeFlags::Int64: 1530 if (IsInt64Long) 1531 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1532 else 1533 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1534 : Context.LongLongTy; 1535 case NeonTypeFlags::Poly8: 1536 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1537 case NeonTypeFlags::Poly16: 1538 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1539 case NeonTypeFlags::Poly64: 1540 if (IsInt64Long) 1541 return Context.UnsignedLongTy; 1542 else 1543 return Context.UnsignedLongLongTy; 1544 case NeonTypeFlags::Poly128: 1545 break; 1546 case NeonTypeFlags::Float16: 1547 return Context.HalfTy; 1548 case NeonTypeFlags::Float32: 1549 return Context.FloatTy; 1550 case NeonTypeFlags::Float64: 1551 return Context.DoubleTy; 1552 } 1553 llvm_unreachable("Invalid NeonTypeFlag!"); 1554 } 1555 1556 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1557 llvm::APSInt Result; 1558 uint64_t mask = 0; 1559 unsigned TV = 0; 1560 int PtrArgNum = -1; 1561 bool HasConstPtr = false; 1562 switch (BuiltinID) { 1563 #define GET_NEON_OVERLOAD_CHECK 1564 #include "clang/Basic/arm_neon.inc" 1565 #include "clang/Basic/arm_fp16.inc" 1566 #undef GET_NEON_OVERLOAD_CHECK 1567 } 1568 1569 // For NEON intrinsics which are overloaded on vector element type, validate 1570 // the immediate which specifies which variant to emit. 1571 unsigned ImmArg = TheCall->getNumArgs()-1; 1572 if (mask) { 1573 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1574 return true; 1575 1576 TV = Result.getLimitedValue(64); 1577 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1578 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 1579 << TheCall->getArg(ImmArg)->getSourceRange(); 1580 } 1581 1582 if (PtrArgNum >= 0) { 1583 // Check that pointer arguments have the specified type. 1584 Expr *Arg = TheCall->getArg(PtrArgNum); 1585 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1586 Arg = ICE->getSubExpr(); 1587 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1588 QualType RHSTy = RHS.get()->getType(); 1589 1590 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1591 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1592 Arch == llvm::Triple::aarch64_be; 1593 bool IsInt64Long = 1594 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1595 QualType EltTy = 1596 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1597 if (HasConstPtr) 1598 EltTy = EltTy.withConst(); 1599 QualType LHSTy = Context.getPointerType(EltTy); 1600 AssignConvertType ConvTy; 1601 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1602 if (RHS.isInvalid()) 1603 return true; 1604 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 1605 RHS.get(), AA_Assigning)) 1606 return true; 1607 } 1608 1609 // For NEON intrinsics which take an immediate value as part of the 1610 // instruction, range check them here. 1611 unsigned i = 0, l = 0, u = 0; 1612 switch (BuiltinID) { 1613 default: 1614 return false; 1615 #define GET_NEON_IMMEDIATE_CHECK 1616 #include "clang/Basic/arm_neon.inc" 1617 #include "clang/Basic/arm_fp16.inc" 1618 #undef GET_NEON_IMMEDIATE_CHECK 1619 } 1620 1621 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1622 } 1623 1624 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1625 unsigned MaxWidth) { 1626 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1627 BuiltinID == ARM::BI__builtin_arm_ldaex || 1628 BuiltinID == ARM::BI__builtin_arm_strex || 1629 BuiltinID == ARM::BI__builtin_arm_stlex || 1630 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1631 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1632 BuiltinID == AArch64::BI__builtin_arm_strex || 1633 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1634 "unexpected ARM builtin"); 1635 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1636 BuiltinID == ARM::BI__builtin_arm_ldaex || 1637 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1638 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1639 1640 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1641 1642 // Ensure that we have the proper number of arguments. 1643 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1644 return true; 1645 1646 // Inspect the pointer argument of the atomic builtin. This should always be 1647 // a pointer type, whose element is an integral scalar or pointer type. 1648 // Because it is a pointer type, we don't have to worry about any implicit 1649 // casts here. 1650 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1651 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1652 if (PointerArgRes.isInvalid()) 1653 return true; 1654 PointerArg = PointerArgRes.get(); 1655 1656 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1657 if (!pointerType) { 1658 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 1659 << PointerArg->getType() << PointerArg->getSourceRange(); 1660 return true; 1661 } 1662 1663 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1664 // task is to insert the appropriate casts into the AST. First work out just 1665 // what the appropriate type is. 1666 QualType ValType = pointerType->getPointeeType(); 1667 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1668 if (IsLdrex) 1669 AddrType.addConst(); 1670 1671 // Issue a warning if the cast is dodgy. 1672 CastKind CastNeeded = CK_NoOp; 1673 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1674 CastNeeded = CK_BitCast; 1675 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 1676 << PointerArg->getType() << Context.getPointerType(AddrType) 1677 << AA_Passing << PointerArg->getSourceRange(); 1678 } 1679 1680 // Finally, do the cast and replace the argument with the corrected version. 1681 AddrType = Context.getPointerType(AddrType); 1682 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1683 if (PointerArgRes.isInvalid()) 1684 return true; 1685 PointerArg = PointerArgRes.get(); 1686 1687 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1688 1689 // In general, we allow ints, floats and pointers to be loaded and stored. 1690 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1691 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1692 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1693 << PointerArg->getType() << PointerArg->getSourceRange(); 1694 return true; 1695 } 1696 1697 // But ARM doesn't have instructions to deal with 128-bit versions. 1698 if (Context.getTypeSize(ValType) > MaxWidth) { 1699 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1700 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 1701 << PointerArg->getType() << PointerArg->getSourceRange(); 1702 return true; 1703 } 1704 1705 switch (ValType.getObjCLifetime()) { 1706 case Qualifiers::OCL_None: 1707 case Qualifiers::OCL_ExplicitNone: 1708 // okay 1709 break; 1710 1711 case Qualifiers::OCL_Weak: 1712 case Qualifiers::OCL_Strong: 1713 case Qualifiers::OCL_Autoreleasing: 1714 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 1715 << ValType << PointerArg->getSourceRange(); 1716 return true; 1717 } 1718 1719 if (IsLdrex) { 1720 TheCall->setType(ValType); 1721 return false; 1722 } 1723 1724 // Initialize the argument to be stored. 1725 ExprResult ValArg = TheCall->getArg(0); 1726 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1727 Context, ValType, /*consume*/ false); 1728 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1729 if (ValArg.isInvalid()) 1730 return true; 1731 TheCall->setArg(0, ValArg.get()); 1732 1733 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1734 // but the custom checker bypasses all default analysis. 1735 TheCall->setType(Context.IntTy); 1736 return false; 1737 } 1738 1739 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1740 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1741 BuiltinID == ARM::BI__builtin_arm_ldaex || 1742 BuiltinID == ARM::BI__builtin_arm_strex || 1743 BuiltinID == ARM::BI__builtin_arm_stlex) { 1744 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1745 } 1746 1747 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1748 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1749 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1750 } 1751 1752 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1753 BuiltinID == ARM::BI__builtin_arm_wsr64) 1754 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1755 1756 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1757 BuiltinID == ARM::BI__builtin_arm_rsrp || 1758 BuiltinID == ARM::BI__builtin_arm_wsr || 1759 BuiltinID == ARM::BI__builtin_arm_wsrp) 1760 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1761 1762 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1763 return true; 1764 1765 // For intrinsics which take an immediate value as part of the instruction, 1766 // range check them here. 1767 // FIXME: VFP Intrinsics should error if VFP not present. 1768 switch (BuiltinID) { 1769 default: return false; 1770 case ARM::BI__builtin_arm_ssat: 1771 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1772 case ARM::BI__builtin_arm_usat: 1773 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1774 case ARM::BI__builtin_arm_ssat16: 1775 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1776 case ARM::BI__builtin_arm_usat16: 1777 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1778 case ARM::BI__builtin_arm_vcvtr_f: 1779 case ARM::BI__builtin_arm_vcvtr_d: 1780 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1781 case ARM::BI__builtin_arm_dmb: 1782 case ARM::BI__builtin_arm_dsb: 1783 case ARM::BI__builtin_arm_isb: 1784 case ARM::BI__builtin_arm_dbg: 1785 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1786 } 1787 } 1788 1789 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1790 CallExpr *TheCall) { 1791 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1792 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1793 BuiltinID == AArch64::BI__builtin_arm_strex || 1794 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1795 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1796 } 1797 1798 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1799 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1800 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1801 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1802 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1803 } 1804 1805 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1806 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1807 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1808 1809 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1810 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1811 BuiltinID == AArch64::BI__builtin_arm_wsr || 1812 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1813 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1814 1815 // Only check the valid encoding range. Any constant in this range would be 1816 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 1817 // an exception for incorrect registers. This matches MSVC behavior. 1818 if (BuiltinID == AArch64::BI_ReadStatusReg || 1819 BuiltinID == AArch64::BI_WriteStatusReg) 1820 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 1821 1822 if (BuiltinID == AArch64::BI__getReg) 1823 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 1824 1825 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1826 return true; 1827 1828 // For intrinsics which take an immediate value as part of the instruction, 1829 // range check them here. 1830 unsigned i = 0, l = 0, u = 0; 1831 switch (BuiltinID) { 1832 default: return false; 1833 case AArch64::BI__builtin_arm_dmb: 1834 case AArch64::BI__builtin_arm_dsb: 1835 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1836 } 1837 1838 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1839 } 1840 1841 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 1842 struct BuiltinAndString { 1843 unsigned BuiltinID; 1844 const char *Str; 1845 }; 1846 1847 static BuiltinAndString ValidCPU[] = { 1848 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" }, 1849 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" }, 1850 { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" }, 1851 { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" }, 1852 { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" }, 1853 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" }, 1854 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" }, 1855 { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" }, 1856 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" }, 1857 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" }, 1858 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" }, 1859 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" }, 1860 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" }, 1861 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" }, 1862 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" }, 1863 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" }, 1864 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" }, 1865 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" }, 1866 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" }, 1867 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" }, 1868 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" }, 1869 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" }, 1870 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" }, 1871 }; 1872 1873 static BuiltinAndString ValidHVX[] = { 1874 { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" }, 1875 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" }, 1876 { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" }, 1877 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" }, 1878 { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" }, 1879 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" }, 1880 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" }, 1881 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" }, 1882 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" }, 1883 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" }, 1884 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" }, 1885 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" }, 1886 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" }, 1887 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" }, 1888 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" }, 1889 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" }, 1890 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" }, 1891 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" }, 1892 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" }, 1893 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" }, 1894 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" }, 1895 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" }, 1896 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" }, 1897 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" }, 1898 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" }, 1899 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" }, 1900 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" }, 1901 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" }, 1902 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" }, 1903 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" }, 1904 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" }, 1905 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" }, 1906 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" }, 1907 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" }, 1908 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" }, 1909 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" }, 1910 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" }, 1911 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" }, 1912 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" }, 1913 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" }, 1914 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" }, 1915 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" }, 1916 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" }, 1917 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" }, 1918 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" }, 1919 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" }, 1920 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" }, 1921 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" }, 1922 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" }, 1923 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" }, 1924 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" }, 1925 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" }, 1926 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" }, 1927 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" }, 1928 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" }, 1929 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" }, 1930 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" }, 1931 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" }, 1932 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" }, 1933 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" }, 1934 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" }, 1935 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" }, 1936 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" }, 1937 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" }, 1938 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" }, 1939 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" }, 1940 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" }, 1941 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" }, 1942 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" }, 1943 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" }, 1944 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" }, 1945 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" }, 1946 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" }, 1947 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" }, 1948 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" }, 1949 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" }, 1950 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" }, 1951 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" }, 1952 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" }, 1953 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" }, 1954 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" }, 1955 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" }, 1956 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" }, 1957 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" }, 1958 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" }, 1959 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" }, 1960 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" }, 1961 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" }, 1962 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" }, 1963 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" }, 1964 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" }, 1965 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" }, 1966 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" }, 1967 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" }, 1968 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" }, 1969 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" }, 1970 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" }, 1971 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" }, 1972 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" }, 1973 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" }, 1974 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" }, 1975 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" }, 1976 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" }, 1977 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" }, 1978 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" }, 1979 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" }, 1980 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" }, 1981 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" }, 1982 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" }, 1983 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" }, 1984 { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" }, 1985 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" }, 1986 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" }, 1987 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" }, 1988 { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" }, 1989 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" }, 1990 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" }, 1991 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" }, 1992 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" }, 1993 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" }, 1994 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" }, 1995 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" }, 1996 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" }, 1997 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" }, 1998 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" }, 1999 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" }, 2000 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" }, 2001 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" }, 2002 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" }, 2003 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" }, 2004 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" }, 2005 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" }, 2006 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" }, 2007 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" }, 2008 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" }, 2009 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" }, 2010 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" }, 2011 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" }, 2012 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" }, 2013 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" }, 2014 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" }, 2015 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" }, 2016 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" }, 2017 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" }, 2018 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" }, 2019 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" }, 2020 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" }, 2021 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" }, 2022 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" }, 2023 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" }, 2024 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" }, 2025 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" }, 2026 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" }, 2027 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" }, 2028 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" }, 2029 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" }, 2030 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" }, 2031 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" }, 2032 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" }, 2033 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" }, 2034 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" }, 2035 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" }, 2036 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" }, 2037 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" }, 2038 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" }, 2039 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" }, 2040 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" }, 2041 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" }, 2042 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" }, 2043 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" }, 2044 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" }, 2045 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" }, 2046 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" }, 2047 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" }, 2048 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" }, 2049 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" }, 2050 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" }, 2051 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" }, 2052 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" }, 2053 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" }, 2054 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" }, 2055 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" }, 2056 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" }, 2057 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" }, 2058 { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" }, 2059 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" }, 2060 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" }, 2061 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" }, 2062 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" }, 2063 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" }, 2064 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" }, 2065 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" }, 2066 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" }, 2067 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" }, 2068 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" }, 2069 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" }, 2070 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" }, 2071 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" }, 2072 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" }, 2073 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" }, 2074 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" }, 2075 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" }, 2076 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" }, 2077 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" }, 2078 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" }, 2079 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" }, 2080 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" }, 2081 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" }, 2082 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" }, 2083 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" }, 2084 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" }, 2085 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" }, 2086 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" }, 2087 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" }, 2088 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" }, 2089 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" }, 2090 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" }, 2091 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" }, 2092 { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" }, 2093 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" }, 2094 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" }, 2095 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" }, 2096 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" }, 2097 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" }, 2098 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" }, 2099 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" }, 2100 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" }, 2101 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" }, 2102 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" }, 2103 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" }, 2104 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" }, 2105 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" }, 2106 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" }, 2107 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" }, 2108 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" }, 2109 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" }, 2110 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" }, 2111 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" }, 2112 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" }, 2113 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" }, 2114 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" }, 2115 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" }, 2116 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" }, 2117 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" }, 2118 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" }, 2119 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" }, 2120 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" }, 2121 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" }, 2122 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" }, 2123 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" }, 2124 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" }, 2125 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" }, 2126 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" }, 2127 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" }, 2128 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" }, 2129 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2130 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" }, 2131 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" }, 2132 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" }, 2133 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" }, 2134 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" }, 2135 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" }, 2136 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" }, 2137 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" }, 2138 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" }, 2139 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" }, 2140 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" }, 2141 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" }, 2142 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" }, 2143 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" }, 2144 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" }, 2145 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" }, 2146 { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" }, 2147 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" }, 2148 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" }, 2149 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" }, 2150 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" }, 2151 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" }, 2152 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" }, 2153 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" }, 2154 { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" }, 2155 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" }, 2156 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" }, 2157 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" }, 2158 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" }, 2159 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" }, 2160 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" }, 2161 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" }, 2162 { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" }, 2163 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" }, 2164 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" }, 2165 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" }, 2166 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" }, 2167 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" }, 2168 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" }, 2169 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" }, 2170 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" }, 2171 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" }, 2172 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" }, 2173 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" }, 2174 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" }, 2175 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" }, 2176 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" }, 2177 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" }, 2178 { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" }, 2179 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" }, 2180 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" }, 2181 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" }, 2182 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" }, 2183 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" }, 2184 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" }, 2185 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" }, 2186 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" }, 2187 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" }, 2188 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" }, 2189 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" }, 2190 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" }, 2191 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" }, 2192 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" }, 2193 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" }, 2194 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" }, 2195 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" }, 2196 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" }, 2197 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" }, 2198 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" }, 2199 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" }, 2200 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" }, 2201 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" }, 2202 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" }, 2203 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" }, 2204 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" }, 2205 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" }, 2206 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" }, 2207 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" }, 2208 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" }, 2209 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" }, 2210 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" }, 2211 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" }, 2212 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" }, 2213 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" }, 2214 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" }, 2215 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" }, 2216 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" }, 2217 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" }, 2218 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" }, 2219 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" }, 2220 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" }, 2221 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" }, 2222 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" }, 2223 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" }, 2224 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" }, 2225 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" }, 2226 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" }, 2227 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" }, 2228 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" }, 2229 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" }, 2230 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" }, 2231 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" }, 2232 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" }, 2233 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" }, 2234 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" }, 2235 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" }, 2236 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" }, 2237 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" }, 2238 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" }, 2239 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" }, 2240 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" }, 2241 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" }, 2242 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" }, 2243 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" }, 2244 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" }, 2245 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" }, 2246 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" }, 2247 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" }, 2248 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" }, 2249 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" }, 2250 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" }, 2251 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" }, 2252 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" }, 2253 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" }, 2254 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" }, 2255 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" }, 2256 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" }, 2257 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" }, 2258 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" }, 2259 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" }, 2260 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" }, 2261 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" }, 2262 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" }, 2263 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" }, 2264 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" }, 2265 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" }, 2266 { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" }, 2267 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" }, 2268 { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" }, 2269 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" }, 2270 { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" }, 2271 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" }, 2272 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" }, 2273 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" }, 2274 { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" }, 2275 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" }, 2276 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" }, 2277 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" }, 2278 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" }, 2279 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" }, 2280 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" }, 2281 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" }, 2282 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" }, 2283 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" }, 2284 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" }, 2285 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" }, 2286 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" }, 2287 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" }, 2288 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" }, 2289 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" }, 2290 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" }, 2291 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" }, 2292 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" }, 2293 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" }, 2294 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" }, 2295 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" }, 2296 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" }, 2297 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" }, 2298 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" }, 2299 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" }, 2300 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" }, 2301 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" }, 2302 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" }, 2303 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" }, 2304 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" }, 2305 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" }, 2306 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" }, 2307 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" }, 2308 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" }, 2309 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" }, 2310 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" }, 2311 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" }, 2312 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" }, 2313 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" }, 2314 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" }, 2315 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" }, 2316 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" }, 2317 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" }, 2318 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" }, 2319 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" }, 2320 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" }, 2321 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" }, 2322 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" }, 2323 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2324 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" }, 2325 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" }, 2326 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" }, 2327 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" }, 2328 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" }, 2329 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" }, 2330 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" }, 2331 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" }, 2332 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" }, 2333 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" }, 2334 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" }, 2335 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" }, 2336 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" }, 2337 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" }, 2338 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" }, 2339 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" }, 2340 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" }, 2341 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" }, 2342 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" }, 2343 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" }, 2344 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" }, 2345 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" }, 2346 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" }, 2347 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" }, 2348 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" }, 2349 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" }, 2350 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" }, 2351 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" }, 2352 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" }, 2353 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" }, 2354 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" }, 2355 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" }, 2356 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" }, 2357 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" }, 2358 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" }, 2359 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" }, 2360 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" }, 2361 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" }, 2362 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" }, 2363 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" }, 2364 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" }, 2365 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" }, 2366 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" }, 2367 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" }, 2368 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" }, 2369 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" }, 2370 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" }, 2371 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" }, 2372 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" }, 2373 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" }, 2374 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" }, 2375 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" }, 2376 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" }, 2377 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" }, 2378 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" }, 2379 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" }, 2380 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" }, 2381 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" }, 2382 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" }, 2383 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" }, 2384 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" }, 2385 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" }, 2386 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" }, 2387 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" }, 2388 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" }, 2389 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" }, 2390 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" }, 2391 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" }, 2392 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" }, 2393 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" }, 2394 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" }, 2395 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" }, 2396 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" }, 2397 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" }, 2398 { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" }, 2399 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" }, 2400 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" }, 2401 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" }, 2402 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" }, 2403 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" }, 2404 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" }, 2405 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" }, 2406 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" }, 2407 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" }, 2408 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" }, 2409 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" }, 2410 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" }, 2411 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" }, 2412 { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" }, 2413 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" }, 2414 { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" }, 2415 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" }, 2416 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" }, 2417 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" }, 2418 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" }, 2419 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" }, 2420 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" }, 2421 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" }, 2422 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" }, 2423 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" }, 2424 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" }, 2425 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" }, 2426 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" }, 2427 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" }, 2428 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" }, 2429 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" }, 2430 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" }, 2431 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" }, 2432 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" }, 2433 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" }, 2434 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" }, 2435 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" }, 2436 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" }, 2437 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" }, 2438 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" }, 2439 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" }, 2440 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" }, 2441 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" }, 2442 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" }, 2443 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" }, 2444 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" }, 2445 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" }, 2446 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" }, 2447 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" }, 2448 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" }, 2449 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" }, 2450 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" }, 2451 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" }, 2452 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" }, 2453 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" }, 2454 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" }, 2455 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" }, 2456 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" }, 2457 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" }, 2458 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" }, 2459 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" }, 2460 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" }, 2461 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" }, 2462 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" }, 2463 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" }, 2464 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" }, 2465 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" }, 2466 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" }, 2467 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" }, 2468 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" }, 2469 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" }, 2470 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" }, 2471 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" }, 2472 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" }, 2473 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" }, 2474 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" }, 2475 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" }, 2476 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" }, 2477 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" }, 2478 { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" }, 2479 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" }, 2480 { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" }, 2481 { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" }, 2482 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" }, 2483 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" }, 2484 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" }, 2485 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" }, 2486 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" }, 2487 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" }, 2488 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" }, 2489 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" }, 2490 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" }, 2491 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" }, 2492 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" }, 2493 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" }, 2494 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" }, 2495 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" }, 2496 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" }, 2497 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" }, 2498 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" }, 2499 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" }, 2500 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" }, 2501 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" }, 2502 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" }, 2503 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" }, 2504 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" }, 2505 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" }, 2506 { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" }, 2507 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" }, 2508 { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" }, 2509 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" }, 2510 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" }, 2511 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" }, 2512 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" }, 2513 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" }, 2514 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" }, 2515 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" }, 2516 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" }, 2517 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" }, 2518 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" }, 2519 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" }, 2520 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" }, 2521 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" }, 2522 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" }, 2523 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" }, 2524 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" }, 2525 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" }, 2526 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" }, 2527 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" }, 2528 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" }, 2529 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" }, 2530 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" }, 2531 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" }, 2532 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" }, 2533 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" }, 2534 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" }, 2535 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" }, 2536 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" }, 2537 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" }, 2538 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" }, 2539 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" }, 2540 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" }, 2541 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" }, 2542 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" }, 2543 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" }, 2544 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" }, 2545 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" }, 2546 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" }, 2547 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" }, 2548 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" }, 2549 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" }, 2550 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" }, 2551 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" }, 2552 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" }, 2553 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" }, 2554 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" }, 2555 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" }, 2556 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" }, 2557 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" }, 2558 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" }, 2559 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" }, 2560 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" }, 2561 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" }, 2562 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" }, 2563 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" }, 2564 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" }, 2565 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" }, 2566 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" }, 2567 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" }, 2568 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" }, 2569 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" }, 2570 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" }, 2571 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" }, 2572 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" }, 2573 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" }, 2574 { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" }, 2575 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" }, 2576 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" }, 2577 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" }, 2578 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" }, 2579 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" }, 2580 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" }, 2581 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" }, 2582 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" }, 2583 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" }, 2584 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" }, 2585 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" }, 2586 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" }, 2587 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" }, 2588 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" }, 2589 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" }, 2590 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" }, 2591 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" }, 2592 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" }, 2593 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" }, 2594 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" }, 2595 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" }, 2596 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" }, 2597 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" }, 2598 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" }, 2599 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" }, 2600 { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" }, 2601 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" }, 2602 { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" }, 2603 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" }, 2604 { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" }, 2605 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" }, 2606 }; 2607 2608 // Sort the tables on first execution so we can binary search them. 2609 auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) { 2610 return LHS.BuiltinID < RHS.BuiltinID; 2611 }; 2612 static const bool SortOnce = 2613 (llvm::sort(ValidCPU, SortCmp), 2614 llvm::sort(ValidHVX, SortCmp), true); 2615 (void)SortOnce; 2616 auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) { 2617 return BI.BuiltinID < BuiltinID; 2618 }; 2619 2620 const TargetInfo &TI = Context.getTargetInfo(); 2621 2622 const BuiltinAndString *FC = 2623 std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID, 2624 LowerBoundCmp); 2625 if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) { 2626 const TargetOptions &Opts = TI.getTargetOpts(); 2627 StringRef CPU = Opts.CPU; 2628 if (!CPU.empty()) { 2629 assert(CPU.startswith("hexagon") && "Unexpected CPU name"); 2630 CPU.consume_front("hexagon"); 2631 SmallVector<StringRef, 3> CPUs; 2632 StringRef(FC->Str).split(CPUs, ','); 2633 if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; })) 2634 return Diag(TheCall->getBeginLoc(), 2635 diag::err_hexagon_builtin_unsupported_cpu); 2636 } 2637 } 2638 2639 const BuiltinAndString *FH = 2640 std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID, 2641 LowerBoundCmp); 2642 if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) { 2643 if (!TI.hasFeature("hvx")) 2644 return Diag(TheCall->getBeginLoc(), 2645 diag::err_hexagon_builtin_requires_hvx); 2646 2647 SmallVector<StringRef, 3> HVXs; 2648 StringRef(FH->Str).split(HVXs, ','); 2649 bool IsValid = llvm::any_of(HVXs, 2650 [&TI] (StringRef V) { 2651 std::string F = "hvx" + V.str(); 2652 return TI.hasFeature(F); 2653 }); 2654 if (!IsValid) 2655 return Diag(TheCall->getBeginLoc(), 2656 diag::err_hexagon_builtin_unsupported_hvx); 2657 } 2658 2659 return false; 2660 } 2661 2662 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2663 struct ArgInfo { 2664 uint8_t OpNum; 2665 bool IsSigned; 2666 uint8_t BitWidth; 2667 uint8_t Align; 2668 }; 2669 struct BuiltinInfo { 2670 unsigned BuiltinID; 2671 ArgInfo Infos[2]; 2672 }; 2673 2674 static BuiltinInfo Infos[] = { 2675 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2676 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2677 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2678 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, 2679 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2680 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2681 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2682 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2683 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2684 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2685 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2686 2687 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2688 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2689 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2690 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2691 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2692 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2693 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2694 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2695 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2696 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2697 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2698 2699 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2700 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2701 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2702 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2703 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2704 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2705 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2706 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2707 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2708 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2709 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2710 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2711 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2712 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2713 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2714 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2715 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2716 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2717 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2718 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2719 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2720 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2721 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2722 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2723 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2724 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2725 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2726 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2727 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2728 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2729 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2730 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2731 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2732 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2733 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2734 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2735 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2736 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2737 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2738 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2739 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2740 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2741 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2742 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2743 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2744 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2745 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2746 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2747 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2748 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2749 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2750 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2751 {{ 1, false, 6, 0 }} }, 2752 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2753 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2754 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2755 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2756 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2757 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2758 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2759 {{ 1, false, 5, 0 }} }, 2760 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2761 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2762 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2763 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2764 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2765 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2766 { 2, false, 5, 0 }} }, 2767 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2768 { 2, false, 6, 0 }} }, 2769 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2770 { 3, false, 5, 0 }} }, 2771 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2772 { 3, false, 6, 0 }} }, 2773 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2789 {{ 2, false, 4, 0 }, 2790 { 3, false, 5, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2792 {{ 2, false, 4, 0 }, 2793 { 3, false, 5, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2795 {{ 2, false, 4, 0 }, 2796 { 3, false, 5, 0 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2798 {{ 2, false, 4, 0 }, 2799 { 3, false, 5, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2811 { 2, false, 5, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2813 { 2, false, 6, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2823 {{ 1, false, 4, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2826 {{ 1, false, 4, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2847 {{ 3, false, 1, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2849 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2852 {{ 3, false, 1, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2857 {{ 3, false, 1, 0 }} }, 2858 }; 2859 2860 // Use a dynamically initialized static to sort the table exactly once on 2861 // first run. 2862 static const bool SortOnce = 2863 (llvm::sort(Infos, 2864 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2865 return LHS.BuiltinID < RHS.BuiltinID; 2866 }), 2867 true); 2868 (void)SortOnce; 2869 2870 const BuiltinInfo *F = 2871 std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID, 2872 [](const BuiltinInfo &BI, unsigned BuiltinID) { 2873 return BI.BuiltinID < BuiltinID; 2874 }); 2875 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2876 return false; 2877 2878 bool Error = false; 2879 2880 for (const ArgInfo &A : F->Infos) { 2881 // Ignore empty ArgInfo elements. 2882 if (A.BitWidth == 0) 2883 continue; 2884 2885 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2886 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2887 if (!A.Align) { 2888 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2889 } else { 2890 unsigned M = 1 << A.Align; 2891 Min *= M; 2892 Max *= M; 2893 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2894 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2895 } 2896 } 2897 return Error; 2898 } 2899 2900 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2901 CallExpr *TheCall) { 2902 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) || 2903 CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2904 } 2905 2906 2907 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 2908 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2909 // ordering for DSP is unspecified. MSA is ordered by the data format used 2910 // by the underlying instruction i.e., df/m, df/n and then by size. 2911 // 2912 // FIXME: The size tests here should instead be tablegen'd along with the 2913 // definitions from include/clang/Basic/BuiltinsMips.def. 2914 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2915 // be too. 2916 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2917 unsigned i = 0, l = 0, u = 0, m = 0; 2918 switch (BuiltinID) { 2919 default: return false; 2920 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2921 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2922 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2923 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2924 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2925 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2926 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2927 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 2928 // df/m field. 2929 // These intrinsics take an unsigned 3 bit immediate. 2930 case Mips::BI__builtin_msa_bclri_b: 2931 case Mips::BI__builtin_msa_bnegi_b: 2932 case Mips::BI__builtin_msa_bseti_b: 2933 case Mips::BI__builtin_msa_sat_s_b: 2934 case Mips::BI__builtin_msa_sat_u_b: 2935 case Mips::BI__builtin_msa_slli_b: 2936 case Mips::BI__builtin_msa_srai_b: 2937 case Mips::BI__builtin_msa_srari_b: 2938 case Mips::BI__builtin_msa_srli_b: 2939 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 2940 case Mips::BI__builtin_msa_binsli_b: 2941 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 2942 // These intrinsics take an unsigned 4 bit immediate. 2943 case Mips::BI__builtin_msa_bclri_h: 2944 case Mips::BI__builtin_msa_bnegi_h: 2945 case Mips::BI__builtin_msa_bseti_h: 2946 case Mips::BI__builtin_msa_sat_s_h: 2947 case Mips::BI__builtin_msa_sat_u_h: 2948 case Mips::BI__builtin_msa_slli_h: 2949 case Mips::BI__builtin_msa_srai_h: 2950 case Mips::BI__builtin_msa_srari_h: 2951 case Mips::BI__builtin_msa_srli_h: 2952 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 2953 case Mips::BI__builtin_msa_binsli_h: 2954 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2955 // These intrinsics take an unsigned 5 bit immediate. 2956 // The first block of intrinsics actually have an unsigned 5 bit field, 2957 // not a df/n field. 2958 case Mips::BI__builtin_msa_clei_u_b: 2959 case Mips::BI__builtin_msa_clei_u_h: 2960 case Mips::BI__builtin_msa_clei_u_w: 2961 case Mips::BI__builtin_msa_clei_u_d: 2962 case Mips::BI__builtin_msa_clti_u_b: 2963 case Mips::BI__builtin_msa_clti_u_h: 2964 case Mips::BI__builtin_msa_clti_u_w: 2965 case Mips::BI__builtin_msa_clti_u_d: 2966 case Mips::BI__builtin_msa_maxi_u_b: 2967 case Mips::BI__builtin_msa_maxi_u_h: 2968 case Mips::BI__builtin_msa_maxi_u_w: 2969 case Mips::BI__builtin_msa_maxi_u_d: 2970 case Mips::BI__builtin_msa_mini_u_b: 2971 case Mips::BI__builtin_msa_mini_u_h: 2972 case Mips::BI__builtin_msa_mini_u_w: 2973 case Mips::BI__builtin_msa_mini_u_d: 2974 case Mips::BI__builtin_msa_addvi_b: 2975 case Mips::BI__builtin_msa_addvi_h: 2976 case Mips::BI__builtin_msa_addvi_w: 2977 case Mips::BI__builtin_msa_addvi_d: 2978 case Mips::BI__builtin_msa_bclri_w: 2979 case Mips::BI__builtin_msa_bnegi_w: 2980 case Mips::BI__builtin_msa_bseti_w: 2981 case Mips::BI__builtin_msa_sat_s_w: 2982 case Mips::BI__builtin_msa_sat_u_w: 2983 case Mips::BI__builtin_msa_slli_w: 2984 case Mips::BI__builtin_msa_srai_w: 2985 case Mips::BI__builtin_msa_srari_w: 2986 case Mips::BI__builtin_msa_srli_w: 2987 case Mips::BI__builtin_msa_srlri_w: 2988 case Mips::BI__builtin_msa_subvi_b: 2989 case Mips::BI__builtin_msa_subvi_h: 2990 case Mips::BI__builtin_msa_subvi_w: 2991 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2992 case Mips::BI__builtin_msa_binsli_w: 2993 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2994 // These intrinsics take an unsigned 6 bit immediate. 2995 case Mips::BI__builtin_msa_bclri_d: 2996 case Mips::BI__builtin_msa_bnegi_d: 2997 case Mips::BI__builtin_msa_bseti_d: 2998 case Mips::BI__builtin_msa_sat_s_d: 2999 case Mips::BI__builtin_msa_sat_u_d: 3000 case Mips::BI__builtin_msa_slli_d: 3001 case Mips::BI__builtin_msa_srai_d: 3002 case Mips::BI__builtin_msa_srari_d: 3003 case Mips::BI__builtin_msa_srli_d: 3004 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3005 case Mips::BI__builtin_msa_binsli_d: 3006 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3007 // These intrinsics take a signed 5 bit immediate. 3008 case Mips::BI__builtin_msa_ceqi_b: 3009 case Mips::BI__builtin_msa_ceqi_h: 3010 case Mips::BI__builtin_msa_ceqi_w: 3011 case Mips::BI__builtin_msa_ceqi_d: 3012 case Mips::BI__builtin_msa_clti_s_b: 3013 case Mips::BI__builtin_msa_clti_s_h: 3014 case Mips::BI__builtin_msa_clti_s_w: 3015 case Mips::BI__builtin_msa_clti_s_d: 3016 case Mips::BI__builtin_msa_clei_s_b: 3017 case Mips::BI__builtin_msa_clei_s_h: 3018 case Mips::BI__builtin_msa_clei_s_w: 3019 case Mips::BI__builtin_msa_clei_s_d: 3020 case Mips::BI__builtin_msa_maxi_s_b: 3021 case Mips::BI__builtin_msa_maxi_s_h: 3022 case Mips::BI__builtin_msa_maxi_s_w: 3023 case Mips::BI__builtin_msa_maxi_s_d: 3024 case Mips::BI__builtin_msa_mini_s_b: 3025 case Mips::BI__builtin_msa_mini_s_h: 3026 case Mips::BI__builtin_msa_mini_s_w: 3027 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3028 // These intrinsics take an unsigned 8 bit immediate. 3029 case Mips::BI__builtin_msa_andi_b: 3030 case Mips::BI__builtin_msa_nori_b: 3031 case Mips::BI__builtin_msa_ori_b: 3032 case Mips::BI__builtin_msa_shf_b: 3033 case Mips::BI__builtin_msa_shf_h: 3034 case Mips::BI__builtin_msa_shf_w: 3035 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3036 case Mips::BI__builtin_msa_bseli_b: 3037 case Mips::BI__builtin_msa_bmnzi_b: 3038 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3039 // df/n format 3040 // These intrinsics take an unsigned 4 bit immediate. 3041 case Mips::BI__builtin_msa_copy_s_b: 3042 case Mips::BI__builtin_msa_copy_u_b: 3043 case Mips::BI__builtin_msa_insve_b: 3044 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3045 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3046 // These intrinsics take an unsigned 3 bit immediate. 3047 case Mips::BI__builtin_msa_copy_s_h: 3048 case Mips::BI__builtin_msa_copy_u_h: 3049 case Mips::BI__builtin_msa_insve_h: 3050 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3051 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3052 // These intrinsics take an unsigned 2 bit immediate. 3053 case Mips::BI__builtin_msa_copy_s_w: 3054 case Mips::BI__builtin_msa_copy_u_w: 3055 case Mips::BI__builtin_msa_insve_w: 3056 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3057 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3058 // These intrinsics take an unsigned 1 bit immediate. 3059 case Mips::BI__builtin_msa_copy_s_d: 3060 case Mips::BI__builtin_msa_copy_u_d: 3061 case Mips::BI__builtin_msa_insve_d: 3062 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3063 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3064 // Memory offsets and immediate loads. 3065 // These intrinsics take a signed 10 bit immediate. 3066 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3067 case Mips::BI__builtin_msa_ldi_h: 3068 case Mips::BI__builtin_msa_ldi_w: 3069 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3070 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3071 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3072 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3073 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3074 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3075 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3076 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3077 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3078 } 3079 3080 if (!m) 3081 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3082 3083 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3084 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3085 } 3086 3087 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3088 unsigned i = 0, l = 0, u = 0; 3089 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3090 BuiltinID == PPC::BI__builtin_divdeu || 3091 BuiltinID == PPC::BI__builtin_bpermd; 3092 bool IsTarget64Bit = Context.getTargetInfo() 3093 .getTypeWidth(Context 3094 .getTargetInfo() 3095 .getIntPtrType()) == 64; 3096 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3097 BuiltinID == PPC::BI__builtin_divweu || 3098 BuiltinID == PPC::BI__builtin_divde || 3099 BuiltinID == PPC::BI__builtin_divdeu; 3100 3101 if (Is64BitBltin && !IsTarget64Bit) 3102 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3103 << TheCall->getSourceRange(); 3104 3105 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 3106 (BuiltinID == PPC::BI__builtin_bpermd && 3107 !Context.getTargetInfo().hasFeature("bpermd"))) 3108 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3109 << TheCall->getSourceRange(); 3110 3111 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3112 if (!Context.getTargetInfo().hasFeature("vsx")) 3113 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3114 << TheCall->getSourceRange(); 3115 return false; 3116 }; 3117 3118 switch (BuiltinID) { 3119 default: return false; 3120 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3121 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3122 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3123 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3124 case PPC::BI__builtin_tbegin: 3125 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3126 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3127 case PPC::BI__builtin_tabortwc: 3128 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3129 case PPC::BI__builtin_tabortwci: 3130 case PPC::BI__builtin_tabortdci: 3131 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3132 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3133 case PPC::BI__builtin_vsx_xxpermdi: 3134 case PPC::BI__builtin_vsx_xxsldwi: 3135 return SemaBuiltinVSX(TheCall); 3136 case PPC::BI__builtin_unpack_vector_int128: 3137 return SemaVSXCheck(TheCall) || 3138 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3139 case PPC::BI__builtin_pack_vector_int128: 3140 return SemaVSXCheck(TheCall); 3141 } 3142 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3143 } 3144 3145 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3146 CallExpr *TheCall) { 3147 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3148 Expr *Arg = TheCall->getArg(0); 3149 llvm::APSInt AbortCode(32); 3150 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3151 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3152 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3153 << Arg->getSourceRange(); 3154 } 3155 3156 // For intrinsics which take an immediate value as part of the instruction, 3157 // range check them here. 3158 unsigned i = 0, l = 0, u = 0; 3159 switch (BuiltinID) { 3160 default: return false; 3161 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3162 case SystemZ::BI__builtin_s390_verimb: 3163 case SystemZ::BI__builtin_s390_verimh: 3164 case SystemZ::BI__builtin_s390_verimf: 3165 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3166 case SystemZ::BI__builtin_s390_vfaeb: 3167 case SystemZ::BI__builtin_s390_vfaeh: 3168 case SystemZ::BI__builtin_s390_vfaef: 3169 case SystemZ::BI__builtin_s390_vfaebs: 3170 case SystemZ::BI__builtin_s390_vfaehs: 3171 case SystemZ::BI__builtin_s390_vfaefs: 3172 case SystemZ::BI__builtin_s390_vfaezb: 3173 case SystemZ::BI__builtin_s390_vfaezh: 3174 case SystemZ::BI__builtin_s390_vfaezf: 3175 case SystemZ::BI__builtin_s390_vfaezbs: 3176 case SystemZ::BI__builtin_s390_vfaezhs: 3177 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3178 case SystemZ::BI__builtin_s390_vfisb: 3179 case SystemZ::BI__builtin_s390_vfidb: 3180 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3181 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3182 case SystemZ::BI__builtin_s390_vftcisb: 3183 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3184 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3185 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3186 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3187 case SystemZ::BI__builtin_s390_vstrcb: 3188 case SystemZ::BI__builtin_s390_vstrch: 3189 case SystemZ::BI__builtin_s390_vstrcf: 3190 case SystemZ::BI__builtin_s390_vstrczb: 3191 case SystemZ::BI__builtin_s390_vstrczh: 3192 case SystemZ::BI__builtin_s390_vstrczf: 3193 case SystemZ::BI__builtin_s390_vstrcbs: 3194 case SystemZ::BI__builtin_s390_vstrchs: 3195 case SystemZ::BI__builtin_s390_vstrcfs: 3196 case SystemZ::BI__builtin_s390_vstrczbs: 3197 case SystemZ::BI__builtin_s390_vstrczhs: 3198 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3199 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3200 case SystemZ::BI__builtin_s390_vfminsb: 3201 case SystemZ::BI__builtin_s390_vfmaxsb: 3202 case SystemZ::BI__builtin_s390_vfmindb: 3203 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3204 } 3205 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3206 } 3207 3208 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3209 /// This checks that the target supports __builtin_cpu_supports and 3210 /// that the string argument is constant and valid. 3211 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 3212 Expr *Arg = TheCall->getArg(0); 3213 3214 // Check if the argument is a string literal. 3215 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3216 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3217 << Arg->getSourceRange(); 3218 3219 // Check the contents of the string. 3220 StringRef Feature = 3221 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3222 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 3223 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3224 << Arg->getSourceRange(); 3225 return false; 3226 } 3227 3228 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3229 /// This checks that the target supports __builtin_cpu_is and 3230 /// that the string argument is constant and valid. 3231 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 3232 Expr *Arg = TheCall->getArg(0); 3233 3234 // Check if the argument is a string literal. 3235 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3236 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3237 << Arg->getSourceRange(); 3238 3239 // Check the contents of the string. 3240 StringRef Feature = 3241 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3242 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 3243 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3244 << Arg->getSourceRange(); 3245 return false; 3246 } 3247 3248 // Check if the rounding mode is legal. 3249 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3250 // Indicates if this instruction has rounding control or just SAE. 3251 bool HasRC = false; 3252 3253 unsigned ArgNum = 0; 3254 switch (BuiltinID) { 3255 default: 3256 return false; 3257 case X86::BI__builtin_ia32_vcvttsd2si32: 3258 case X86::BI__builtin_ia32_vcvttsd2si64: 3259 case X86::BI__builtin_ia32_vcvttsd2usi32: 3260 case X86::BI__builtin_ia32_vcvttsd2usi64: 3261 case X86::BI__builtin_ia32_vcvttss2si32: 3262 case X86::BI__builtin_ia32_vcvttss2si64: 3263 case X86::BI__builtin_ia32_vcvttss2usi32: 3264 case X86::BI__builtin_ia32_vcvttss2usi64: 3265 ArgNum = 1; 3266 break; 3267 case X86::BI__builtin_ia32_maxpd512: 3268 case X86::BI__builtin_ia32_maxps512: 3269 case X86::BI__builtin_ia32_minpd512: 3270 case X86::BI__builtin_ia32_minps512: 3271 ArgNum = 2; 3272 break; 3273 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3274 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3275 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3276 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3277 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3278 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3279 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3280 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3281 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3282 case X86::BI__builtin_ia32_exp2pd_mask: 3283 case X86::BI__builtin_ia32_exp2ps_mask: 3284 case X86::BI__builtin_ia32_getexppd512_mask: 3285 case X86::BI__builtin_ia32_getexpps512_mask: 3286 case X86::BI__builtin_ia32_rcp28pd_mask: 3287 case X86::BI__builtin_ia32_rcp28ps_mask: 3288 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3289 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3290 case X86::BI__builtin_ia32_vcomisd: 3291 case X86::BI__builtin_ia32_vcomiss: 3292 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3293 ArgNum = 3; 3294 break; 3295 case X86::BI__builtin_ia32_cmppd512_mask: 3296 case X86::BI__builtin_ia32_cmpps512_mask: 3297 case X86::BI__builtin_ia32_cmpsd_mask: 3298 case X86::BI__builtin_ia32_cmpss_mask: 3299 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3300 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3301 case X86::BI__builtin_ia32_getexpss128_round_mask: 3302 case X86::BI__builtin_ia32_maxsd_round_mask: 3303 case X86::BI__builtin_ia32_maxss_round_mask: 3304 case X86::BI__builtin_ia32_minsd_round_mask: 3305 case X86::BI__builtin_ia32_minss_round_mask: 3306 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3307 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3308 case X86::BI__builtin_ia32_reducepd512_mask: 3309 case X86::BI__builtin_ia32_reduceps512_mask: 3310 case X86::BI__builtin_ia32_rndscalepd_mask: 3311 case X86::BI__builtin_ia32_rndscaleps_mask: 3312 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3313 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3314 ArgNum = 4; 3315 break; 3316 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3317 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3318 case X86::BI__builtin_ia32_fixupimmps512_mask: 3319 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3320 case X86::BI__builtin_ia32_fixupimmsd_mask: 3321 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3322 case X86::BI__builtin_ia32_fixupimmss_mask: 3323 case X86::BI__builtin_ia32_fixupimmss_maskz: 3324 case X86::BI__builtin_ia32_rangepd512_mask: 3325 case X86::BI__builtin_ia32_rangeps512_mask: 3326 case X86::BI__builtin_ia32_rangesd128_round_mask: 3327 case X86::BI__builtin_ia32_rangess128_round_mask: 3328 case X86::BI__builtin_ia32_reducesd_mask: 3329 case X86::BI__builtin_ia32_reducess_mask: 3330 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3331 case X86::BI__builtin_ia32_rndscaless_round_mask: 3332 ArgNum = 5; 3333 break; 3334 case X86::BI__builtin_ia32_vcvtsd2si64: 3335 case X86::BI__builtin_ia32_vcvtsd2si32: 3336 case X86::BI__builtin_ia32_vcvtsd2usi32: 3337 case X86::BI__builtin_ia32_vcvtsd2usi64: 3338 case X86::BI__builtin_ia32_vcvtss2si32: 3339 case X86::BI__builtin_ia32_vcvtss2si64: 3340 case X86::BI__builtin_ia32_vcvtss2usi32: 3341 case X86::BI__builtin_ia32_vcvtss2usi64: 3342 case X86::BI__builtin_ia32_sqrtpd512: 3343 case X86::BI__builtin_ia32_sqrtps512: 3344 ArgNum = 1; 3345 HasRC = true; 3346 break; 3347 case X86::BI__builtin_ia32_addpd512: 3348 case X86::BI__builtin_ia32_addps512: 3349 case X86::BI__builtin_ia32_divpd512: 3350 case X86::BI__builtin_ia32_divps512: 3351 case X86::BI__builtin_ia32_mulpd512: 3352 case X86::BI__builtin_ia32_mulps512: 3353 case X86::BI__builtin_ia32_subpd512: 3354 case X86::BI__builtin_ia32_subps512: 3355 case X86::BI__builtin_ia32_cvtsi2sd64: 3356 case X86::BI__builtin_ia32_cvtsi2ss32: 3357 case X86::BI__builtin_ia32_cvtsi2ss64: 3358 case X86::BI__builtin_ia32_cvtusi2sd64: 3359 case X86::BI__builtin_ia32_cvtusi2ss32: 3360 case X86::BI__builtin_ia32_cvtusi2ss64: 3361 ArgNum = 2; 3362 HasRC = true; 3363 break; 3364 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3365 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3366 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3367 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3368 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3369 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3370 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3371 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3372 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3373 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3374 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3375 ArgNum = 3; 3376 HasRC = true; 3377 break; 3378 case X86::BI__builtin_ia32_addss_round_mask: 3379 case X86::BI__builtin_ia32_addsd_round_mask: 3380 case X86::BI__builtin_ia32_divss_round_mask: 3381 case X86::BI__builtin_ia32_divsd_round_mask: 3382 case X86::BI__builtin_ia32_mulss_round_mask: 3383 case X86::BI__builtin_ia32_mulsd_round_mask: 3384 case X86::BI__builtin_ia32_subss_round_mask: 3385 case X86::BI__builtin_ia32_subsd_round_mask: 3386 case X86::BI__builtin_ia32_scalefpd512_mask: 3387 case X86::BI__builtin_ia32_scalefps512_mask: 3388 case X86::BI__builtin_ia32_scalefsd_round_mask: 3389 case X86::BI__builtin_ia32_scalefss_round_mask: 3390 case X86::BI__builtin_ia32_getmantpd512_mask: 3391 case X86::BI__builtin_ia32_getmantps512_mask: 3392 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3393 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3394 case X86::BI__builtin_ia32_sqrtss_round_mask: 3395 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3396 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3397 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3398 case X86::BI__builtin_ia32_vfmaddss3_mask: 3399 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3400 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3401 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3402 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3403 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3404 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3405 case X86::BI__builtin_ia32_vfmaddps512_mask: 3406 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3407 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3408 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3409 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3410 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3411 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3412 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3413 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3414 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3415 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3416 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3417 ArgNum = 4; 3418 HasRC = true; 3419 break; 3420 case X86::BI__builtin_ia32_getmantsd_round_mask: 3421 case X86::BI__builtin_ia32_getmantss_round_mask: 3422 ArgNum = 5; 3423 HasRC = true; 3424 break; 3425 } 3426 3427 llvm::APSInt Result; 3428 3429 // We can't check the value of a dependent argument. 3430 Expr *Arg = TheCall->getArg(ArgNum); 3431 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3432 return false; 3433 3434 // Check constant-ness first. 3435 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3436 return true; 3437 3438 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3439 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3440 // combined with ROUND_NO_EXC. 3441 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3442 Result == 8/*ROUND_NO_EXC*/ || 3443 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3444 return false; 3445 3446 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3447 << Arg->getSourceRange(); 3448 } 3449 3450 // Check if the gather/scatter scale is legal. 3451 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3452 CallExpr *TheCall) { 3453 unsigned ArgNum = 0; 3454 switch (BuiltinID) { 3455 default: 3456 return false; 3457 case X86::BI__builtin_ia32_gatherpfdpd: 3458 case X86::BI__builtin_ia32_gatherpfdps: 3459 case X86::BI__builtin_ia32_gatherpfqpd: 3460 case X86::BI__builtin_ia32_gatherpfqps: 3461 case X86::BI__builtin_ia32_scatterpfdpd: 3462 case X86::BI__builtin_ia32_scatterpfdps: 3463 case X86::BI__builtin_ia32_scatterpfqpd: 3464 case X86::BI__builtin_ia32_scatterpfqps: 3465 ArgNum = 3; 3466 break; 3467 case X86::BI__builtin_ia32_gatherd_pd: 3468 case X86::BI__builtin_ia32_gatherd_pd256: 3469 case X86::BI__builtin_ia32_gatherq_pd: 3470 case X86::BI__builtin_ia32_gatherq_pd256: 3471 case X86::BI__builtin_ia32_gatherd_ps: 3472 case X86::BI__builtin_ia32_gatherd_ps256: 3473 case X86::BI__builtin_ia32_gatherq_ps: 3474 case X86::BI__builtin_ia32_gatherq_ps256: 3475 case X86::BI__builtin_ia32_gatherd_q: 3476 case X86::BI__builtin_ia32_gatherd_q256: 3477 case X86::BI__builtin_ia32_gatherq_q: 3478 case X86::BI__builtin_ia32_gatherq_q256: 3479 case X86::BI__builtin_ia32_gatherd_d: 3480 case X86::BI__builtin_ia32_gatherd_d256: 3481 case X86::BI__builtin_ia32_gatherq_d: 3482 case X86::BI__builtin_ia32_gatherq_d256: 3483 case X86::BI__builtin_ia32_gather3div2df: 3484 case X86::BI__builtin_ia32_gather3div2di: 3485 case X86::BI__builtin_ia32_gather3div4df: 3486 case X86::BI__builtin_ia32_gather3div4di: 3487 case X86::BI__builtin_ia32_gather3div4sf: 3488 case X86::BI__builtin_ia32_gather3div4si: 3489 case X86::BI__builtin_ia32_gather3div8sf: 3490 case X86::BI__builtin_ia32_gather3div8si: 3491 case X86::BI__builtin_ia32_gather3siv2df: 3492 case X86::BI__builtin_ia32_gather3siv2di: 3493 case X86::BI__builtin_ia32_gather3siv4df: 3494 case X86::BI__builtin_ia32_gather3siv4di: 3495 case X86::BI__builtin_ia32_gather3siv4sf: 3496 case X86::BI__builtin_ia32_gather3siv4si: 3497 case X86::BI__builtin_ia32_gather3siv8sf: 3498 case X86::BI__builtin_ia32_gather3siv8si: 3499 case X86::BI__builtin_ia32_gathersiv8df: 3500 case X86::BI__builtin_ia32_gathersiv16sf: 3501 case X86::BI__builtin_ia32_gatherdiv8df: 3502 case X86::BI__builtin_ia32_gatherdiv16sf: 3503 case X86::BI__builtin_ia32_gathersiv8di: 3504 case X86::BI__builtin_ia32_gathersiv16si: 3505 case X86::BI__builtin_ia32_gatherdiv8di: 3506 case X86::BI__builtin_ia32_gatherdiv16si: 3507 case X86::BI__builtin_ia32_scatterdiv2df: 3508 case X86::BI__builtin_ia32_scatterdiv2di: 3509 case X86::BI__builtin_ia32_scatterdiv4df: 3510 case X86::BI__builtin_ia32_scatterdiv4di: 3511 case X86::BI__builtin_ia32_scatterdiv4sf: 3512 case X86::BI__builtin_ia32_scatterdiv4si: 3513 case X86::BI__builtin_ia32_scatterdiv8sf: 3514 case X86::BI__builtin_ia32_scatterdiv8si: 3515 case X86::BI__builtin_ia32_scattersiv2df: 3516 case X86::BI__builtin_ia32_scattersiv2di: 3517 case X86::BI__builtin_ia32_scattersiv4df: 3518 case X86::BI__builtin_ia32_scattersiv4di: 3519 case X86::BI__builtin_ia32_scattersiv4sf: 3520 case X86::BI__builtin_ia32_scattersiv4si: 3521 case X86::BI__builtin_ia32_scattersiv8sf: 3522 case X86::BI__builtin_ia32_scattersiv8si: 3523 case X86::BI__builtin_ia32_scattersiv8df: 3524 case X86::BI__builtin_ia32_scattersiv16sf: 3525 case X86::BI__builtin_ia32_scatterdiv8df: 3526 case X86::BI__builtin_ia32_scatterdiv16sf: 3527 case X86::BI__builtin_ia32_scattersiv8di: 3528 case X86::BI__builtin_ia32_scattersiv16si: 3529 case X86::BI__builtin_ia32_scatterdiv8di: 3530 case X86::BI__builtin_ia32_scatterdiv16si: 3531 ArgNum = 4; 3532 break; 3533 } 3534 3535 llvm::APSInt Result; 3536 3537 // We can't check the value of a dependent argument. 3538 Expr *Arg = TheCall->getArg(ArgNum); 3539 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3540 return false; 3541 3542 // Check constant-ness first. 3543 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3544 return true; 3545 3546 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3547 return false; 3548 3549 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3550 << Arg->getSourceRange(); 3551 } 3552 3553 static bool isX86_32Builtin(unsigned BuiltinID) { 3554 // These builtins only work on x86-32 targets. 3555 switch (BuiltinID) { 3556 case X86::BI__builtin_ia32_readeflags_u32: 3557 case X86::BI__builtin_ia32_writeeflags_u32: 3558 return true; 3559 } 3560 3561 return false; 3562 } 3563 3564 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3565 if (BuiltinID == X86::BI__builtin_cpu_supports) 3566 return SemaBuiltinCpuSupports(*this, TheCall); 3567 3568 if (BuiltinID == X86::BI__builtin_cpu_is) 3569 return SemaBuiltinCpuIs(*this, TheCall); 3570 3571 // Check for 32-bit only builtins on a 64-bit target. 3572 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3573 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3574 return Diag(TheCall->getCallee()->getBeginLoc(), 3575 diag::err_32_bit_builtin_64_bit_tgt); 3576 3577 // If the intrinsic has rounding or SAE make sure its valid. 3578 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3579 return true; 3580 3581 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3582 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3583 return true; 3584 3585 // For intrinsics which take an immediate value as part of the instruction, 3586 // range check them here. 3587 int i = 0, l = 0, u = 0; 3588 switch (BuiltinID) { 3589 default: 3590 return false; 3591 case X86::BI__builtin_ia32_vec_ext_v2si: 3592 case X86::BI__builtin_ia32_vec_ext_v2di: 3593 case X86::BI__builtin_ia32_vextractf128_pd256: 3594 case X86::BI__builtin_ia32_vextractf128_ps256: 3595 case X86::BI__builtin_ia32_vextractf128_si256: 3596 case X86::BI__builtin_ia32_extract128i256: 3597 case X86::BI__builtin_ia32_extractf64x4_mask: 3598 case X86::BI__builtin_ia32_extracti64x4_mask: 3599 case X86::BI__builtin_ia32_extractf32x8_mask: 3600 case X86::BI__builtin_ia32_extracti32x8_mask: 3601 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3602 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3603 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3604 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3605 i = 1; l = 0; u = 1; 3606 break; 3607 case X86::BI__builtin_ia32_vec_set_v2di: 3608 case X86::BI__builtin_ia32_vinsertf128_pd256: 3609 case X86::BI__builtin_ia32_vinsertf128_ps256: 3610 case X86::BI__builtin_ia32_vinsertf128_si256: 3611 case X86::BI__builtin_ia32_insert128i256: 3612 case X86::BI__builtin_ia32_insertf32x8: 3613 case X86::BI__builtin_ia32_inserti32x8: 3614 case X86::BI__builtin_ia32_insertf64x4: 3615 case X86::BI__builtin_ia32_inserti64x4: 3616 case X86::BI__builtin_ia32_insertf64x2_256: 3617 case X86::BI__builtin_ia32_inserti64x2_256: 3618 case X86::BI__builtin_ia32_insertf32x4_256: 3619 case X86::BI__builtin_ia32_inserti32x4_256: 3620 i = 2; l = 0; u = 1; 3621 break; 3622 case X86::BI__builtin_ia32_vpermilpd: 3623 case X86::BI__builtin_ia32_vec_ext_v4hi: 3624 case X86::BI__builtin_ia32_vec_ext_v4si: 3625 case X86::BI__builtin_ia32_vec_ext_v4sf: 3626 case X86::BI__builtin_ia32_vec_ext_v4di: 3627 case X86::BI__builtin_ia32_extractf32x4_mask: 3628 case X86::BI__builtin_ia32_extracti32x4_mask: 3629 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3630 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3631 i = 1; l = 0; u = 3; 3632 break; 3633 case X86::BI_mm_prefetch: 3634 case X86::BI__builtin_ia32_vec_ext_v8hi: 3635 case X86::BI__builtin_ia32_vec_ext_v8si: 3636 i = 1; l = 0; u = 7; 3637 break; 3638 case X86::BI__builtin_ia32_sha1rnds4: 3639 case X86::BI__builtin_ia32_blendpd: 3640 case X86::BI__builtin_ia32_shufpd: 3641 case X86::BI__builtin_ia32_vec_set_v4hi: 3642 case X86::BI__builtin_ia32_vec_set_v4si: 3643 case X86::BI__builtin_ia32_vec_set_v4di: 3644 case X86::BI__builtin_ia32_shuf_f32x4_256: 3645 case X86::BI__builtin_ia32_shuf_f64x2_256: 3646 case X86::BI__builtin_ia32_shuf_i32x4_256: 3647 case X86::BI__builtin_ia32_shuf_i64x2_256: 3648 case X86::BI__builtin_ia32_insertf64x2_512: 3649 case X86::BI__builtin_ia32_inserti64x2_512: 3650 case X86::BI__builtin_ia32_insertf32x4: 3651 case X86::BI__builtin_ia32_inserti32x4: 3652 i = 2; l = 0; u = 3; 3653 break; 3654 case X86::BI__builtin_ia32_vpermil2pd: 3655 case X86::BI__builtin_ia32_vpermil2pd256: 3656 case X86::BI__builtin_ia32_vpermil2ps: 3657 case X86::BI__builtin_ia32_vpermil2ps256: 3658 i = 3; l = 0; u = 3; 3659 break; 3660 case X86::BI__builtin_ia32_cmpb128_mask: 3661 case X86::BI__builtin_ia32_cmpw128_mask: 3662 case X86::BI__builtin_ia32_cmpd128_mask: 3663 case X86::BI__builtin_ia32_cmpq128_mask: 3664 case X86::BI__builtin_ia32_cmpb256_mask: 3665 case X86::BI__builtin_ia32_cmpw256_mask: 3666 case X86::BI__builtin_ia32_cmpd256_mask: 3667 case X86::BI__builtin_ia32_cmpq256_mask: 3668 case X86::BI__builtin_ia32_cmpb512_mask: 3669 case X86::BI__builtin_ia32_cmpw512_mask: 3670 case X86::BI__builtin_ia32_cmpd512_mask: 3671 case X86::BI__builtin_ia32_cmpq512_mask: 3672 case X86::BI__builtin_ia32_ucmpb128_mask: 3673 case X86::BI__builtin_ia32_ucmpw128_mask: 3674 case X86::BI__builtin_ia32_ucmpd128_mask: 3675 case X86::BI__builtin_ia32_ucmpq128_mask: 3676 case X86::BI__builtin_ia32_ucmpb256_mask: 3677 case X86::BI__builtin_ia32_ucmpw256_mask: 3678 case X86::BI__builtin_ia32_ucmpd256_mask: 3679 case X86::BI__builtin_ia32_ucmpq256_mask: 3680 case X86::BI__builtin_ia32_ucmpb512_mask: 3681 case X86::BI__builtin_ia32_ucmpw512_mask: 3682 case X86::BI__builtin_ia32_ucmpd512_mask: 3683 case X86::BI__builtin_ia32_ucmpq512_mask: 3684 case X86::BI__builtin_ia32_vpcomub: 3685 case X86::BI__builtin_ia32_vpcomuw: 3686 case X86::BI__builtin_ia32_vpcomud: 3687 case X86::BI__builtin_ia32_vpcomuq: 3688 case X86::BI__builtin_ia32_vpcomb: 3689 case X86::BI__builtin_ia32_vpcomw: 3690 case X86::BI__builtin_ia32_vpcomd: 3691 case X86::BI__builtin_ia32_vpcomq: 3692 case X86::BI__builtin_ia32_vec_set_v8hi: 3693 case X86::BI__builtin_ia32_vec_set_v8si: 3694 i = 2; l = 0; u = 7; 3695 break; 3696 case X86::BI__builtin_ia32_vpermilpd256: 3697 case X86::BI__builtin_ia32_roundps: 3698 case X86::BI__builtin_ia32_roundpd: 3699 case X86::BI__builtin_ia32_roundps256: 3700 case X86::BI__builtin_ia32_roundpd256: 3701 case X86::BI__builtin_ia32_getmantpd128_mask: 3702 case X86::BI__builtin_ia32_getmantpd256_mask: 3703 case X86::BI__builtin_ia32_getmantps128_mask: 3704 case X86::BI__builtin_ia32_getmantps256_mask: 3705 case X86::BI__builtin_ia32_getmantpd512_mask: 3706 case X86::BI__builtin_ia32_getmantps512_mask: 3707 case X86::BI__builtin_ia32_vec_ext_v16qi: 3708 case X86::BI__builtin_ia32_vec_ext_v16hi: 3709 i = 1; l = 0; u = 15; 3710 break; 3711 case X86::BI__builtin_ia32_pblendd128: 3712 case X86::BI__builtin_ia32_blendps: 3713 case X86::BI__builtin_ia32_blendpd256: 3714 case X86::BI__builtin_ia32_shufpd256: 3715 case X86::BI__builtin_ia32_roundss: 3716 case X86::BI__builtin_ia32_roundsd: 3717 case X86::BI__builtin_ia32_rangepd128_mask: 3718 case X86::BI__builtin_ia32_rangepd256_mask: 3719 case X86::BI__builtin_ia32_rangepd512_mask: 3720 case X86::BI__builtin_ia32_rangeps128_mask: 3721 case X86::BI__builtin_ia32_rangeps256_mask: 3722 case X86::BI__builtin_ia32_rangeps512_mask: 3723 case X86::BI__builtin_ia32_getmantsd_round_mask: 3724 case X86::BI__builtin_ia32_getmantss_round_mask: 3725 case X86::BI__builtin_ia32_vec_set_v16qi: 3726 case X86::BI__builtin_ia32_vec_set_v16hi: 3727 i = 2; l = 0; u = 15; 3728 break; 3729 case X86::BI__builtin_ia32_vec_ext_v32qi: 3730 i = 1; l = 0; u = 31; 3731 break; 3732 case X86::BI__builtin_ia32_cmpps: 3733 case X86::BI__builtin_ia32_cmpss: 3734 case X86::BI__builtin_ia32_cmppd: 3735 case X86::BI__builtin_ia32_cmpsd: 3736 case X86::BI__builtin_ia32_cmpps256: 3737 case X86::BI__builtin_ia32_cmppd256: 3738 case X86::BI__builtin_ia32_cmpps128_mask: 3739 case X86::BI__builtin_ia32_cmppd128_mask: 3740 case X86::BI__builtin_ia32_cmpps256_mask: 3741 case X86::BI__builtin_ia32_cmppd256_mask: 3742 case X86::BI__builtin_ia32_cmpps512_mask: 3743 case X86::BI__builtin_ia32_cmppd512_mask: 3744 case X86::BI__builtin_ia32_cmpsd_mask: 3745 case X86::BI__builtin_ia32_cmpss_mask: 3746 case X86::BI__builtin_ia32_vec_set_v32qi: 3747 i = 2; l = 0; u = 31; 3748 break; 3749 case X86::BI__builtin_ia32_permdf256: 3750 case X86::BI__builtin_ia32_permdi256: 3751 case X86::BI__builtin_ia32_permdf512: 3752 case X86::BI__builtin_ia32_permdi512: 3753 case X86::BI__builtin_ia32_vpermilps: 3754 case X86::BI__builtin_ia32_vpermilps256: 3755 case X86::BI__builtin_ia32_vpermilpd512: 3756 case X86::BI__builtin_ia32_vpermilps512: 3757 case X86::BI__builtin_ia32_pshufd: 3758 case X86::BI__builtin_ia32_pshufd256: 3759 case X86::BI__builtin_ia32_pshufd512: 3760 case X86::BI__builtin_ia32_pshufhw: 3761 case X86::BI__builtin_ia32_pshufhw256: 3762 case X86::BI__builtin_ia32_pshufhw512: 3763 case X86::BI__builtin_ia32_pshuflw: 3764 case X86::BI__builtin_ia32_pshuflw256: 3765 case X86::BI__builtin_ia32_pshuflw512: 3766 case X86::BI__builtin_ia32_vcvtps2ph: 3767 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3768 case X86::BI__builtin_ia32_vcvtps2ph256: 3769 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3770 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3771 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3772 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3773 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3774 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3775 case X86::BI__builtin_ia32_rndscaleps_mask: 3776 case X86::BI__builtin_ia32_rndscalepd_mask: 3777 case X86::BI__builtin_ia32_reducepd128_mask: 3778 case X86::BI__builtin_ia32_reducepd256_mask: 3779 case X86::BI__builtin_ia32_reducepd512_mask: 3780 case X86::BI__builtin_ia32_reduceps128_mask: 3781 case X86::BI__builtin_ia32_reduceps256_mask: 3782 case X86::BI__builtin_ia32_reduceps512_mask: 3783 case X86::BI__builtin_ia32_prold512: 3784 case X86::BI__builtin_ia32_prolq512: 3785 case X86::BI__builtin_ia32_prold128: 3786 case X86::BI__builtin_ia32_prold256: 3787 case X86::BI__builtin_ia32_prolq128: 3788 case X86::BI__builtin_ia32_prolq256: 3789 case X86::BI__builtin_ia32_prord512: 3790 case X86::BI__builtin_ia32_prorq512: 3791 case X86::BI__builtin_ia32_prord128: 3792 case X86::BI__builtin_ia32_prord256: 3793 case X86::BI__builtin_ia32_prorq128: 3794 case X86::BI__builtin_ia32_prorq256: 3795 case X86::BI__builtin_ia32_fpclasspd128_mask: 3796 case X86::BI__builtin_ia32_fpclasspd256_mask: 3797 case X86::BI__builtin_ia32_fpclassps128_mask: 3798 case X86::BI__builtin_ia32_fpclassps256_mask: 3799 case X86::BI__builtin_ia32_fpclassps512_mask: 3800 case X86::BI__builtin_ia32_fpclasspd512_mask: 3801 case X86::BI__builtin_ia32_fpclasssd_mask: 3802 case X86::BI__builtin_ia32_fpclassss_mask: 3803 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3804 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3805 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3806 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3807 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3808 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3809 case X86::BI__builtin_ia32_kshiftliqi: 3810 case X86::BI__builtin_ia32_kshiftlihi: 3811 case X86::BI__builtin_ia32_kshiftlisi: 3812 case X86::BI__builtin_ia32_kshiftlidi: 3813 case X86::BI__builtin_ia32_kshiftriqi: 3814 case X86::BI__builtin_ia32_kshiftrihi: 3815 case X86::BI__builtin_ia32_kshiftrisi: 3816 case X86::BI__builtin_ia32_kshiftridi: 3817 i = 1; l = 0; u = 255; 3818 break; 3819 case X86::BI__builtin_ia32_vperm2f128_pd256: 3820 case X86::BI__builtin_ia32_vperm2f128_ps256: 3821 case X86::BI__builtin_ia32_vperm2f128_si256: 3822 case X86::BI__builtin_ia32_permti256: 3823 case X86::BI__builtin_ia32_pblendw128: 3824 case X86::BI__builtin_ia32_pblendw256: 3825 case X86::BI__builtin_ia32_blendps256: 3826 case X86::BI__builtin_ia32_pblendd256: 3827 case X86::BI__builtin_ia32_palignr128: 3828 case X86::BI__builtin_ia32_palignr256: 3829 case X86::BI__builtin_ia32_palignr512: 3830 case X86::BI__builtin_ia32_alignq512: 3831 case X86::BI__builtin_ia32_alignd512: 3832 case X86::BI__builtin_ia32_alignd128: 3833 case X86::BI__builtin_ia32_alignd256: 3834 case X86::BI__builtin_ia32_alignq128: 3835 case X86::BI__builtin_ia32_alignq256: 3836 case X86::BI__builtin_ia32_vcomisd: 3837 case X86::BI__builtin_ia32_vcomiss: 3838 case X86::BI__builtin_ia32_shuf_f32x4: 3839 case X86::BI__builtin_ia32_shuf_f64x2: 3840 case X86::BI__builtin_ia32_shuf_i32x4: 3841 case X86::BI__builtin_ia32_shuf_i64x2: 3842 case X86::BI__builtin_ia32_shufpd512: 3843 case X86::BI__builtin_ia32_shufps: 3844 case X86::BI__builtin_ia32_shufps256: 3845 case X86::BI__builtin_ia32_shufps512: 3846 case X86::BI__builtin_ia32_dbpsadbw128: 3847 case X86::BI__builtin_ia32_dbpsadbw256: 3848 case X86::BI__builtin_ia32_dbpsadbw512: 3849 case X86::BI__builtin_ia32_vpshldd128: 3850 case X86::BI__builtin_ia32_vpshldd256: 3851 case X86::BI__builtin_ia32_vpshldd512: 3852 case X86::BI__builtin_ia32_vpshldq128: 3853 case X86::BI__builtin_ia32_vpshldq256: 3854 case X86::BI__builtin_ia32_vpshldq512: 3855 case X86::BI__builtin_ia32_vpshldw128: 3856 case X86::BI__builtin_ia32_vpshldw256: 3857 case X86::BI__builtin_ia32_vpshldw512: 3858 case X86::BI__builtin_ia32_vpshrdd128: 3859 case X86::BI__builtin_ia32_vpshrdd256: 3860 case X86::BI__builtin_ia32_vpshrdd512: 3861 case X86::BI__builtin_ia32_vpshrdq128: 3862 case X86::BI__builtin_ia32_vpshrdq256: 3863 case X86::BI__builtin_ia32_vpshrdq512: 3864 case X86::BI__builtin_ia32_vpshrdw128: 3865 case X86::BI__builtin_ia32_vpshrdw256: 3866 case X86::BI__builtin_ia32_vpshrdw512: 3867 i = 2; l = 0; u = 255; 3868 break; 3869 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3870 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3871 case X86::BI__builtin_ia32_fixupimmps512_mask: 3872 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3873 case X86::BI__builtin_ia32_fixupimmsd_mask: 3874 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3875 case X86::BI__builtin_ia32_fixupimmss_mask: 3876 case X86::BI__builtin_ia32_fixupimmss_maskz: 3877 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3878 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3879 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3880 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3881 case X86::BI__builtin_ia32_fixupimmps128_mask: 3882 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3883 case X86::BI__builtin_ia32_fixupimmps256_mask: 3884 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3885 case X86::BI__builtin_ia32_pternlogd512_mask: 3886 case X86::BI__builtin_ia32_pternlogd512_maskz: 3887 case X86::BI__builtin_ia32_pternlogq512_mask: 3888 case X86::BI__builtin_ia32_pternlogq512_maskz: 3889 case X86::BI__builtin_ia32_pternlogd128_mask: 3890 case X86::BI__builtin_ia32_pternlogd128_maskz: 3891 case X86::BI__builtin_ia32_pternlogd256_mask: 3892 case X86::BI__builtin_ia32_pternlogd256_maskz: 3893 case X86::BI__builtin_ia32_pternlogq128_mask: 3894 case X86::BI__builtin_ia32_pternlogq128_maskz: 3895 case X86::BI__builtin_ia32_pternlogq256_mask: 3896 case X86::BI__builtin_ia32_pternlogq256_maskz: 3897 i = 3; l = 0; u = 255; 3898 break; 3899 case X86::BI__builtin_ia32_gatherpfdpd: 3900 case X86::BI__builtin_ia32_gatherpfdps: 3901 case X86::BI__builtin_ia32_gatherpfqpd: 3902 case X86::BI__builtin_ia32_gatherpfqps: 3903 case X86::BI__builtin_ia32_scatterpfdpd: 3904 case X86::BI__builtin_ia32_scatterpfdps: 3905 case X86::BI__builtin_ia32_scatterpfqpd: 3906 case X86::BI__builtin_ia32_scatterpfqps: 3907 i = 4; l = 2; u = 3; 3908 break; 3909 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3910 case X86::BI__builtin_ia32_rndscaless_round_mask: 3911 i = 4; l = 0; u = 255; 3912 break; 3913 } 3914 3915 // Note that we don't force a hard error on the range check here, allowing 3916 // template-generated or macro-generated dead code to potentially have out-of- 3917 // range values. These need to code generate, but don't need to necessarily 3918 // make any sense. We use a warning that defaults to an error. 3919 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 3920 } 3921 3922 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 3923 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 3924 /// Returns true when the format fits the function and the FormatStringInfo has 3925 /// been populated. 3926 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 3927 FormatStringInfo *FSI) { 3928 FSI->HasVAListArg = Format->getFirstArg() == 0; 3929 FSI->FormatIdx = Format->getFormatIdx() - 1; 3930 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 3931 3932 // The way the format attribute works in GCC, the implicit this argument 3933 // of member functions is counted. However, it doesn't appear in our own 3934 // lists, so decrement format_idx in that case. 3935 if (IsCXXMember) { 3936 if(FSI->FormatIdx == 0) 3937 return false; 3938 --FSI->FormatIdx; 3939 if (FSI->FirstDataArg != 0) 3940 --FSI->FirstDataArg; 3941 } 3942 return true; 3943 } 3944 3945 /// Checks if a the given expression evaluates to null. 3946 /// 3947 /// Returns true if the value evaluates to null. 3948 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 3949 // If the expression has non-null type, it doesn't evaluate to null. 3950 if (auto nullability 3951 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 3952 if (*nullability == NullabilityKind::NonNull) 3953 return false; 3954 } 3955 3956 // As a special case, transparent unions initialized with zero are 3957 // considered null for the purposes of the nonnull attribute. 3958 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 3959 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3960 if (const CompoundLiteralExpr *CLE = 3961 dyn_cast<CompoundLiteralExpr>(Expr)) 3962 if (const InitListExpr *ILE = 3963 dyn_cast<InitListExpr>(CLE->getInitializer())) 3964 Expr = ILE->getInit(0); 3965 } 3966 3967 bool Result; 3968 return (!Expr->isValueDependent() && 3969 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 3970 !Result); 3971 } 3972 3973 static void CheckNonNullArgument(Sema &S, 3974 const Expr *ArgExpr, 3975 SourceLocation CallSiteLoc) { 3976 if (CheckNonNullExpr(S, ArgExpr)) 3977 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 3978 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 3979 } 3980 3981 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 3982 FormatStringInfo FSI; 3983 if ((GetFormatStringType(Format) == FST_NSString) && 3984 getFormatStringInfo(Format, false, &FSI)) { 3985 Idx = FSI.FormatIdx; 3986 return true; 3987 } 3988 return false; 3989 } 3990 3991 /// Diagnose use of %s directive in an NSString which is being passed 3992 /// as formatting string to formatting method. 3993 static void 3994 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 3995 const NamedDecl *FDecl, 3996 Expr **Args, 3997 unsigned NumArgs) { 3998 unsigned Idx = 0; 3999 bool Format = false; 4000 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4001 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4002 Idx = 2; 4003 Format = true; 4004 } 4005 else 4006 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4007 if (S.GetFormatNSStringIdx(I, Idx)) { 4008 Format = true; 4009 break; 4010 } 4011 } 4012 if (!Format || NumArgs <= Idx) 4013 return; 4014 const Expr *FormatExpr = Args[Idx]; 4015 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4016 FormatExpr = CSCE->getSubExpr(); 4017 const StringLiteral *FormatString; 4018 if (const ObjCStringLiteral *OSL = 4019 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4020 FormatString = OSL->getString(); 4021 else 4022 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4023 if (!FormatString) 4024 return; 4025 if (S.FormatStringHasSArg(FormatString)) { 4026 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4027 << "%s" << 1 << 1; 4028 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4029 << FDecl->getDeclName(); 4030 } 4031 } 4032 4033 /// Determine whether the given type has a non-null nullability annotation. 4034 static bool isNonNullType(ASTContext &ctx, QualType type) { 4035 if (auto nullability = type->getNullability(ctx)) 4036 return *nullability == NullabilityKind::NonNull; 4037 4038 return false; 4039 } 4040 4041 static void CheckNonNullArguments(Sema &S, 4042 const NamedDecl *FDecl, 4043 const FunctionProtoType *Proto, 4044 ArrayRef<const Expr *> Args, 4045 SourceLocation CallSiteLoc) { 4046 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4047 4048 // Check the attributes attached to the method/function itself. 4049 llvm::SmallBitVector NonNullArgs; 4050 if (FDecl) { 4051 // Handle the nonnull attribute on the function/method declaration itself. 4052 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4053 if (!NonNull->args_size()) { 4054 // Easy case: all pointer arguments are nonnull. 4055 for (const auto *Arg : Args) 4056 if (S.isValidPointerAttrType(Arg->getType())) 4057 CheckNonNullArgument(S, Arg, CallSiteLoc); 4058 return; 4059 } 4060 4061 for (const ParamIdx &Idx : NonNull->args()) { 4062 unsigned IdxAST = Idx.getASTIndex(); 4063 if (IdxAST >= Args.size()) 4064 continue; 4065 if (NonNullArgs.empty()) 4066 NonNullArgs.resize(Args.size()); 4067 NonNullArgs.set(IdxAST); 4068 } 4069 } 4070 } 4071 4072 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4073 // Handle the nonnull attribute on the parameters of the 4074 // function/method. 4075 ArrayRef<ParmVarDecl*> parms; 4076 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4077 parms = FD->parameters(); 4078 else 4079 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4080 4081 unsigned ParamIndex = 0; 4082 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4083 I != E; ++I, ++ParamIndex) { 4084 const ParmVarDecl *PVD = *I; 4085 if (PVD->hasAttr<NonNullAttr>() || 4086 isNonNullType(S.Context, PVD->getType())) { 4087 if (NonNullArgs.empty()) 4088 NonNullArgs.resize(Args.size()); 4089 4090 NonNullArgs.set(ParamIndex); 4091 } 4092 } 4093 } else { 4094 // If we have a non-function, non-method declaration but no 4095 // function prototype, try to dig out the function prototype. 4096 if (!Proto) { 4097 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4098 QualType type = VD->getType().getNonReferenceType(); 4099 if (auto pointerType = type->getAs<PointerType>()) 4100 type = pointerType->getPointeeType(); 4101 else if (auto blockType = type->getAs<BlockPointerType>()) 4102 type = blockType->getPointeeType(); 4103 // FIXME: data member pointers? 4104 4105 // Dig out the function prototype, if there is one. 4106 Proto = type->getAs<FunctionProtoType>(); 4107 } 4108 } 4109 4110 // Fill in non-null argument information from the nullability 4111 // information on the parameter types (if we have them). 4112 if (Proto) { 4113 unsigned Index = 0; 4114 for (auto paramType : Proto->getParamTypes()) { 4115 if (isNonNullType(S.Context, paramType)) { 4116 if (NonNullArgs.empty()) 4117 NonNullArgs.resize(Args.size()); 4118 4119 NonNullArgs.set(Index); 4120 } 4121 4122 ++Index; 4123 } 4124 } 4125 } 4126 4127 // Check for non-null arguments. 4128 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4129 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4130 if (NonNullArgs[ArgIndex]) 4131 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4132 } 4133 } 4134 4135 /// Handles the checks for format strings, non-POD arguments to vararg 4136 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4137 /// attributes. 4138 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4139 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4140 bool IsMemberFunction, SourceLocation Loc, 4141 SourceRange Range, VariadicCallType CallType) { 4142 // FIXME: We should check as much as we can in the template definition. 4143 if (CurContext->isDependentContext()) 4144 return; 4145 4146 // Printf and scanf checking. 4147 llvm::SmallBitVector CheckedVarArgs; 4148 if (FDecl) { 4149 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4150 // Only create vector if there are format attributes. 4151 CheckedVarArgs.resize(Args.size()); 4152 4153 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4154 CheckedVarArgs); 4155 } 4156 } 4157 4158 // Refuse POD arguments that weren't caught by the format string 4159 // checks above. 4160 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4161 if (CallType != VariadicDoesNotApply && 4162 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4163 unsigned NumParams = Proto ? Proto->getNumParams() 4164 : FDecl && isa<FunctionDecl>(FDecl) 4165 ? cast<FunctionDecl>(FDecl)->getNumParams() 4166 : FDecl && isa<ObjCMethodDecl>(FDecl) 4167 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4168 : 0; 4169 4170 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4171 // Args[ArgIdx] can be null in malformed code. 4172 if (const Expr *Arg = Args[ArgIdx]) { 4173 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4174 checkVariadicArgument(Arg, CallType); 4175 } 4176 } 4177 } 4178 4179 if (FDecl || Proto) { 4180 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4181 4182 // Type safety checking. 4183 if (FDecl) { 4184 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4185 CheckArgumentWithTypeTag(I, Args, Loc); 4186 } 4187 } 4188 4189 if (FD) 4190 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4191 } 4192 4193 /// CheckConstructorCall - Check a constructor call for correctness and safety 4194 /// properties not enforced by the C type system. 4195 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4196 ArrayRef<const Expr *> Args, 4197 const FunctionProtoType *Proto, 4198 SourceLocation Loc) { 4199 VariadicCallType CallType = 4200 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4201 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4202 Loc, SourceRange(), CallType); 4203 } 4204 4205 /// CheckFunctionCall - Check a direct function call for various correctness 4206 /// and safety properties not strictly enforced by the C type system. 4207 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4208 const FunctionProtoType *Proto) { 4209 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4210 isa<CXXMethodDecl>(FDecl); 4211 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4212 IsMemberOperatorCall; 4213 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4214 TheCall->getCallee()); 4215 Expr** Args = TheCall->getArgs(); 4216 unsigned NumArgs = TheCall->getNumArgs(); 4217 4218 Expr *ImplicitThis = nullptr; 4219 if (IsMemberOperatorCall) { 4220 // If this is a call to a member operator, hide the first argument 4221 // from checkCall. 4222 // FIXME: Our choice of AST representation here is less than ideal. 4223 ImplicitThis = Args[0]; 4224 ++Args; 4225 --NumArgs; 4226 } else if (IsMemberFunction) 4227 ImplicitThis = 4228 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4229 4230 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4231 IsMemberFunction, TheCall->getRParenLoc(), 4232 TheCall->getCallee()->getSourceRange(), CallType); 4233 4234 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4235 // None of the checks below are needed for functions that don't have 4236 // simple names (e.g., C++ conversion functions). 4237 if (!FnInfo) 4238 return false; 4239 4240 CheckAbsoluteValueFunction(TheCall, FDecl); 4241 CheckMaxUnsignedZero(TheCall, FDecl); 4242 4243 if (getLangOpts().ObjC) 4244 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4245 4246 unsigned CMId = FDecl->getMemoryFunctionKind(); 4247 if (CMId == 0) 4248 return false; 4249 4250 // Handle memory setting and copying functions. 4251 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4252 CheckStrlcpycatArguments(TheCall, FnInfo); 4253 else if (CMId == Builtin::BIstrncat) 4254 CheckStrncatArguments(TheCall, FnInfo); 4255 else 4256 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4257 4258 return false; 4259 } 4260 4261 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4262 ArrayRef<const Expr *> Args) { 4263 VariadicCallType CallType = 4264 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4265 4266 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4267 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4268 CallType); 4269 4270 return false; 4271 } 4272 4273 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4274 const FunctionProtoType *Proto) { 4275 QualType Ty; 4276 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4277 Ty = V->getType().getNonReferenceType(); 4278 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4279 Ty = F->getType().getNonReferenceType(); 4280 else 4281 return false; 4282 4283 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4284 !Ty->isFunctionProtoType()) 4285 return false; 4286 4287 VariadicCallType CallType; 4288 if (!Proto || !Proto->isVariadic()) { 4289 CallType = VariadicDoesNotApply; 4290 } else if (Ty->isBlockPointerType()) { 4291 CallType = VariadicBlock; 4292 } else { // Ty->isFunctionPointerType() 4293 CallType = VariadicFunction; 4294 } 4295 4296 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4297 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4298 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4299 TheCall->getCallee()->getSourceRange(), CallType); 4300 4301 return false; 4302 } 4303 4304 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4305 /// such as function pointers returned from functions. 4306 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4307 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4308 TheCall->getCallee()); 4309 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4310 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4311 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4312 TheCall->getCallee()->getSourceRange(), CallType); 4313 4314 return false; 4315 } 4316 4317 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4318 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4319 return false; 4320 4321 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4322 switch (Op) { 4323 case AtomicExpr::AO__c11_atomic_init: 4324 case AtomicExpr::AO__opencl_atomic_init: 4325 llvm_unreachable("There is no ordering argument for an init"); 4326 4327 case AtomicExpr::AO__c11_atomic_load: 4328 case AtomicExpr::AO__opencl_atomic_load: 4329 case AtomicExpr::AO__atomic_load_n: 4330 case AtomicExpr::AO__atomic_load: 4331 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4332 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4333 4334 case AtomicExpr::AO__c11_atomic_store: 4335 case AtomicExpr::AO__opencl_atomic_store: 4336 case AtomicExpr::AO__atomic_store: 4337 case AtomicExpr::AO__atomic_store_n: 4338 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4339 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4340 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4341 4342 default: 4343 return true; 4344 } 4345 } 4346 4347 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4348 AtomicExpr::AtomicOp Op) { 4349 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4350 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4351 4352 // All the non-OpenCL operations take one of the following forms. 4353 // The OpenCL operations take the __c11 forms with one extra argument for 4354 // synchronization scope. 4355 enum { 4356 // C __c11_atomic_init(A *, C) 4357 Init, 4358 4359 // C __c11_atomic_load(A *, int) 4360 Load, 4361 4362 // void __atomic_load(A *, CP, int) 4363 LoadCopy, 4364 4365 // void __atomic_store(A *, CP, int) 4366 Copy, 4367 4368 // C __c11_atomic_add(A *, M, int) 4369 Arithmetic, 4370 4371 // C __atomic_exchange_n(A *, CP, int) 4372 Xchg, 4373 4374 // void __atomic_exchange(A *, C *, CP, int) 4375 GNUXchg, 4376 4377 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4378 C11CmpXchg, 4379 4380 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4381 GNUCmpXchg 4382 } Form = Init; 4383 4384 const unsigned NumForm = GNUCmpXchg + 1; 4385 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4386 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4387 // where: 4388 // C is an appropriate type, 4389 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4390 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4391 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4392 // the int parameters are for orderings. 4393 4394 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4395 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4396 "need to update code for modified forms"); 4397 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4398 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 4399 AtomicExpr::AO__atomic_load, 4400 "need to update code for modified C11 atomics"); 4401 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4402 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4403 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4404 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 4405 IsOpenCL; 4406 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4407 Op == AtomicExpr::AO__atomic_store_n || 4408 Op == AtomicExpr::AO__atomic_exchange_n || 4409 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4410 bool IsAddSub = false; 4411 bool IsMinMax = false; 4412 4413 switch (Op) { 4414 case AtomicExpr::AO__c11_atomic_init: 4415 case AtomicExpr::AO__opencl_atomic_init: 4416 Form = Init; 4417 break; 4418 4419 case AtomicExpr::AO__c11_atomic_load: 4420 case AtomicExpr::AO__opencl_atomic_load: 4421 case AtomicExpr::AO__atomic_load_n: 4422 Form = Load; 4423 break; 4424 4425 case AtomicExpr::AO__atomic_load: 4426 Form = LoadCopy; 4427 break; 4428 4429 case AtomicExpr::AO__c11_atomic_store: 4430 case AtomicExpr::AO__opencl_atomic_store: 4431 case AtomicExpr::AO__atomic_store: 4432 case AtomicExpr::AO__atomic_store_n: 4433 Form = Copy; 4434 break; 4435 4436 case AtomicExpr::AO__c11_atomic_fetch_add: 4437 case AtomicExpr::AO__c11_atomic_fetch_sub: 4438 case AtomicExpr::AO__opencl_atomic_fetch_add: 4439 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4440 case AtomicExpr::AO__opencl_atomic_fetch_min: 4441 case AtomicExpr::AO__opencl_atomic_fetch_max: 4442 case AtomicExpr::AO__atomic_fetch_add: 4443 case AtomicExpr::AO__atomic_fetch_sub: 4444 case AtomicExpr::AO__atomic_add_fetch: 4445 case AtomicExpr::AO__atomic_sub_fetch: 4446 IsAddSub = true; 4447 LLVM_FALLTHROUGH; 4448 case AtomicExpr::AO__c11_atomic_fetch_and: 4449 case AtomicExpr::AO__c11_atomic_fetch_or: 4450 case AtomicExpr::AO__c11_atomic_fetch_xor: 4451 case AtomicExpr::AO__opencl_atomic_fetch_and: 4452 case AtomicExpr::AO__opencl_atomic_fetch_or: 4453 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4454 case AtomicExpr::AO__atomic_fetch_and: 4455 case AtomicExpr::AO__atomic_fetch_or: 4456 case AtomicExpr::AO__atomic_fetch_xor: 4457 case AtomicExpr::AO__atomic_fetch_nand: 4458 case AtomicExpr::AO__atomic_and_fetch: 4459 case AtomicExpr::AO__atomic_or_fetch: 4460 case AtomicExpr::AO__atomic_xor_fetch: 4461 case AtomicExpr::AO__atomic_nand_fetch: 4462 Form = Arithmetic; 4463 break; 4464 4465 case AtomicExpr::AO__atomic_fetch_min: 4466 case AtomicExpr::AO__atomic_fetch_max: 4467 IsMinMax = true; 4468 Form = Arithmetic; 4469 break; 4470 4471 case AtomicExpr::AO__c11_atomic_exchange: 4472 case AtomicExpr::AO__opencl_atomic_exchange: 4473 case AtomicExpr::AO__atomic_exchange_n: 4474 Form = Xchg; 4475 break; 4476 4477 case AtomicExpr::AO__atomic_exchange: 4478 Form = GNUXchg; 4479 break; 4480 4481 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4482 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4483 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4484 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4485 Form = C11CmpXchg; 4486 break; 4487 4488 case AtomicExpr::AO__atomic_compare_exchange: 4489 case AtomicExpr::AO__atomic_compare_exchange_n: 4490 Form = GNUCmpXchg; 4491 break; 4492 } 4493 4494 unsigned AdjustedNumArgs = NumArgs[Form]; 4495 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4496 ++AdjustedNumArgs; 4497 // Check we have the right number of arguments. 4498 if (TheCall->getNumArgs() < AdjustedNumArgs) { 4499 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 4500 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4501 << TheCall->getCallee()->getSourceRange(); 4502 return ExprError(); 4503 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 4504 Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(), 4505 diag::err_typecheck_call_too_many_args) 4506 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4507 << TheCall->getCallee()->getSourceRange(); 4508 return ExprError(); 4509 } 4510 4511 // Inspect the first argument of the atomic operation. 4512 Expr *Ptr = TheCall->getArg(0); 4513 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4514 if (ConvertedPtr.isInvalid()) 4515 return ExprError(); 4516 4517 Ptr = ConvertedPtr.get(); 4518 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4519 if (!pointerType) { 4520 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4521 << Ptr->getType() << Ptr->getSourceRange(); 4522 return ExprError(); 4523 } 4524 4525 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4526 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4527 QualType ValType = AtomTy; // 'C' 4528 if (IsC11) { 4529 if (!AtomTy->isAtomicType()) { 4530 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic) 4531 << Ptr->getType() << Ptr->getSourceRange(); 4532 return ExprError(); 4533 } 4534 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4535 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4536 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic) 4537 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4538 << Ptr->getSourceRange(); 4539 return ExprError(); 4540 } 4541 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 4542 } else if (Form != Load && Form != LoadCopy) { 4543 if (ValType.isConstQualified()) { 4544 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer) 4545 << Ptr->getType() << Ptr->getSourceRange(); 4546 return ExprError(); 4547 } 4548 } 4549 4550 // For an arithmetic operation, the implied arithmetic must be well-formed. 4551 if (Form == Arithmetic) { 4552 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4553 if (IsAddSub && !ValType->isIntegerType() 4554 && !ValType->isPointerType()) { 4555 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4556 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4557 return ExprError(); 4558 } 4559 if (IsMinMax) { 4560 const BuiltinType *BT = ValType->getAs<BuiltinType>(); 4561 if (!BT || (BT->getKind() != BuiltinType::Int && 4562 BT->getKind() != BuiltinType::UInt)) { 4563 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr); 4564 return ExprError(); 4565 } 4566 } 4567 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) { 4568 Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int) 4569 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4570 return ExprError(); 4571 } 4572 if (IsC11 && ValType->isPointerType() && 4573 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4574 diag::err_incomplete_type)) { 4575 return ExprError(); 4576 } 4577 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4578 // For __atomic_*_n operations, the value type must be a scalar integral or 4579 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4580 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4581 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4582 return ExprError(); 4583 } 4584 4585 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4586 !AtomTy->isScalarType()) { 4587 // For GNU atomics, require a trivially-copyable type. This is not part of 4588 // the GNU atomics specification, but we enforce it for sanity. 4589 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy) 4590 << Ptr->getType() << Ptr->getSourceRange(); 4591 return ExprError(); 4592 } 4593 4594 switch (ValType.getObjCLifetime()) { 4595 case Qualifiers::OCL_None: 4596 case Qualifiers::OCL_ExplicitNone: 4597 // okay 4598 break; 4599 4600 case Qualifiers::OCL_Weak: 4601 case Qualifiers::OCL_Strong: 4602 case Qualifiers::OCL_Autoreleasing: 4603 // FIXME: Can this happen? By this point, ValType should be known 4604 // to be trivially copyable. 4605 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4606 << ValType << Ptr->getSourceRange(); 4607 return ExprError(); 4608 } 4609 4610 // All atomic operations have an overload which takes a pointer to a volatile 4611 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4612 // into the result or the other operands. Similarly atomic_load takes a 4613 // pointer to a const 'A'. 4614 ValType.removeLocalVolatile(); 4615 ValType.removeLocalConst(); 4616 QualType ResultType = ValType; 4617 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4618 Form == Init) 4619 ResultType = Context.VoidTy; 4620 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4621 ResultType = Context.BoolTy; 4622 4623 // The type of a parameter passed 'by value'. In the GNU atomics, such 4624 // arguments are actually passed as pointers. 4625 QualType ByValType = ValType; // 'CP' 4626 bool IsPassedByAddress = false; 4627 if (!IsC11 && !IsN) { 4628 ByValType = Ptr->getType(); 4629 IsPassedByAddress = true; 4630 } 4631 4632 // The first argument's non-CV pointer type is used to deduce the type of 4633 // subsequent arguments, except for: 4634 // - weak flag (always converted to bool) 4635 // - memory order (always converted to int) 4636 // - scope (always converted to int) 4637 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 4638 QualType Ty; 4639 if (i < NumVals[Form] + 1) { 4640 switch (i) { 4641 case 0: 4642 // The first argument is always a pointer. It has a fixed type. 4643 // It is always dereferenced, a nullptr is undefined. 4644 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4645 // Nothing else to do: we already know all we want about this pointer. 4646 continue; 4647 case 1: 4648 // The second argument is the non-atomic operand. For arithmetic, this 4649 // is always passed by value, and for a compare_exchange it is always 4650 // passed by address. For the rest, GNU uses by-address and C11 uses 4651 // by-value. 4652 assert(Form != Load); 4653 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4654 Ty = ValType; 4655 else if (Form == Copy || Form == Xchg) { 4656 if (IsPassedByAddress) 4657 // The value pointer is always dereferenced, a nullptr is undefined. 4658 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4659 Ty = ByValType; 4660 } else if (Form == Arithmetic) 4661 Ty = Context.getPointerDiffType(); 4662 else { 4663 Expr *ValArg = TheCall->getArg(i); 4664 // The value pointer is always dereferenced, a nullptr is undefined. 4665 CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc()); 4666 LangAS AS = LangAS::Default; 4667 // Keep address space of non-atomic pointer type. 4668 if (const PointerType *PtrTy = 4669 ValArg->getType()->getAs<PointerType>()) { 4670 AS = PtrTy->getPointeeType().getAddressSpace(); 4671 } 4672 Ty = Context.getPointerType( 4673 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4674 } 4675 break; 4676 case 2: 4677 // The third argument to compare_exchange / GNU exchange is the desired 4678 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4679 if (IsPassedByAddress) 4680 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4681 Ty = ByValType; 4682 break; 4683 case 3: 4684 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4685 Ty = Context.BoolTy; 4686 break; 4687 } 4688 } else { 4689 // The order(s) and scope are always converted to int. 4690 Ty = Context.IntTy; 4691 } 4692 4693 InitializedEntity Entity = 4694 InitializedEntity::InitializeParameter(Context, Ty, false); 4695 ExprResult Arg = TheCall->getArg(i); 4696 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4697 if (Arg.isInvalid()) 4698 return true; 4699 TheCall->setArg(i, Arg.get()); 4700 } 4701 4702 // Permute the arguments into a 'consistent' order. 4703 SmallVector<Expr*, 5> SubExprs; 4704 SubExprs.push_back(Ptr); 4705 switch (Form) { 4706 case Init: 4707 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4708 SubExprs.push_back(TheCall->getArg(1)); // Val1 4709 break; 4710 case Load: 4711 SubExprs.push_back(TheCall->getArg(1)); // Order 4712 break; 4713 case LoadCopy: 4714 case Copy: 4715 case Arithmetic: 4716 case Xchg: 4717 SubExprs.push_back(TheCall->getArg(2)); // Order 4718 SubExprs.push_back(TheCall->getArg(1)); // Val1 4719 break; 4720 case GNUXchg: 4721 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4722 SubExprs.push_back(TheCall->getArg(3)); // Order 4723 SubExprs.push_back(TheCall->getArg(1)); // Val1 4724 SubExprs.push_back(TheCall->getArg(2)); // Val2 4725 break; 4726 case C11CmpXchg: 4727 SubExprs.push_back(TheCall->getArg(3)); // Order 4728 SubExprs.push_back(TheCall->getArg(1)); // Val1 4729 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 4730 SubExprs.push_back(TheCall->getArg(2)); // Val2 4731 break; 4732 case GNUCmpXchg: 4733 SubExprs.push_back(TheCall->getArg(4)); // Order 4734 SubExprs.push_back(TheCall->getArg(1)); // Val1 4735 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 4736 SubExprs.push_back(TheCall->getArg(2)); // Val2 4737 SubExprs.push_back(TheCall->getArg(3)); // Weak 4738 break; 4739 } 4740 4741 if (SubExprs.size() >= 2 && Form != Init) { 4742 llvm::APSInt Result(32); 4743 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4744 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4745 Diag(SubExprs[1]->getBeginLoc(), 4746 diag::warn_atomic_op_has_invalid_memory_order) 4747 << SubExprs[1]->getSourceRange(); 4748 } 4749 4750 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4751 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 4752 llvm::APSInt Result(32); 4753 if (Scope->isIntegerConstantExpr(Result, Context) && 4754 !ScopeModel->isValid(Result.getZExtValue())) { 4755 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4756 << Scope->getSourceRange(); 4757 } 4758 SubExprs.push_back(Scope); 4759 } 4760 4761 AtomicExpr *AE = 4762 new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs, 4763 ResultType, Op, TheCall->getRParenLoc()); 4764 4765 if ((Op == AtomicExpr::AO__c11_atomic_load || 4766 Op == AtomicExpr::AO__c11_atomic_store || 4767 Op == AtomicExpr::AO__opencl_atomic_load || 4768 Op == AtomicExpr::AO__opencl_atomic_store ) && 4769 Context.AtomicUsesUnsupportedLibcall(AE)) 4770 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4771 << ((Op == AtomicExpr::AO__c11_atomic_load || 4772 Op == AtomicExpr::AO__opencl_atomic_load) 4773 ? 0 4774 : 1); 4775 4776 return AE; 4777 } 4778 4779 /// checkBuiltinArgument - Given a call to a builtin function, perform 4780 /// normal type-checking on the given argument, updating the call in 4781 /// place. This is useful when a builtin function requires custom 4782 /// type-checking for some of its arguments but not necessarily all of 4783 /// them. 4784 /// 4785 /// Returns true on error. 4786 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4787 FunctionDecl *Fn = E->getDirectCallee(); 4788 assert(Fn && "builtin call without direct callee!"); 4789 4790 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4791 InitializedEntity Entity = 4792 InitializedEntity::InitializeParameter(S.Context, Param); 4793 4794 ExprResult Arg = E->getArg(0); 4795 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4796 if (Arg.isInvalid()) 4797 return true; 4798 4799 E->setArg(ArgIndex, Arg.get()); 4800 return false; 4801 } 4802 4803 /// We have a call to a function like __sync_fetch_and_add, which is an 4804 /// overloaded function based on the pointer type of its first argument. 4805 /// The main ActOnCallExpr routines have already promoted the types of 4806 /// arguments because all of these calls are prototyped as void(...). 4807 /// 4808 /// This function goes through and does final semantic checking for these 4809 /// builtins, as well as generating any warnings. 4810 ExprResult 4811 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4812 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4813 Expr *Callee = TheCall->getCallee(); 4814 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4815 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4816 4817 // Ensure that we have at least one argument to do type inference from. 4818 if (TheCall->getNumArgs() < 1) { 4819 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4820 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4821 return ExprError(); 4822 } 4823 4824 // Inspect the first argument of the atomic builtin. This should always be 4825 // a pointer type, whose element is an integral scalar or pointer type. 4826 // Because it is a pointer type, we don't have to worry about any implicit 4827 // casts here. 4828 // FIXME: We don't allow floating point scalars as input. 4829 Expr *FirstArg = TheCall->getArg(0); 4830 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4831 if (FirstArgResult.isInvalid()) 4832 return ExprError(); 4833 FirstArg = FirstArgResult.get(); 4834 TheCall->setArg(0, FirstArg); 4835 4836 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4837 if (!pointerType) { 4838 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4839 << FirstArg->getType() << FirstArg->getSourceRange(); 4840 return ExprError(); 4841 } 4842 4843 QualType ValType = pointerType->getPointeeType(); 4844 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4845 !ValType->isBlockPointerType()) { 4846 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4847 << FirstArg->getType() << FirstArg->getSourceRange(); 4848 return ExprError(); 4849 } 4850 4851 if (ValType.isConstQualified()) { 4852 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4853 << FirstArg->getType() << FirstArg->getSourceRange(); 4854 return ExprError(); 4855 } 4856 4857 switch (ValType.getObjCLifetime()) { 4858 case Qualifiers::OCL_None: 4859 case Qualifiers::OCL_ExplicitNone: 4860 // okay 4861 break; 4862 4863 case Qualifiers::OCL_Weak: 4864 case Qualifiers::OCL_Strong: 4865 case Qualifiers::OCL_Autoreleasing: 4866 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4867 << ValType << FirstArg->getSourceRange(); 4868 return ExprError(); 4869 } 4870 4871 // Strip any qualifiers off ValType. 4872 ValType = ValType.getUnqualifiedType(); 4873 4874 // The majority of builtins return a value, but a few have special return 4875 // types, so allow them to override appropriately below. 4876 QualType ResultType = ValType; 4877 4878 // We need to figure out which concrete builtin this maps onto. For example, 4879 // __sync_fetch_and_add with a 2 byte object turns into 4880 // __sync_fetch_and_add_2. 4881 #define BUILTIN_ROW(x) \ 4882 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4883 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4884 4885 static const unsigned BuiltinIndices[][5] = { 4886 BUILTIN_ROW(__sync_fetch_and_add), 4887 BUILTIN_ROW(__sync_fetch_and_sub), 4888 BUILTIN_ROW(__sync_fetch_and_or), 4889 BUILTIN_ROW(__sync_fetch_and_and), 4890 BUILTIN_ROW(__sync_fetch_and_xor), 4891 BUILTIN_ROW(__sync_fetch_and_nand), 4892 4893 BUILTIN_ROW(__sync_add_and_fetch), 4894 BUILTIN_ROW(__sync_sub_and_fetch), 4895 BUILTIN_ROW(__sync_and_and_fetch), 4896 BUILTIN_ROW(__sync_or_and_fetch), 4897 BUILTIN_ROW(__sync_xor_and_fetch), 4898 BUILTIN_ROW(__sync_nand_and_fetch), 4899 4900 BUILTIN_ROW(__sync_val_compare_and_swap), 4901 BUILTIN_ROW(__sync_bool_compare_and_swap), 4902 BUILTIN_ROW(__sync_lock_test_and_set), 4903 BUILTIN_ROW(__sync_lock_release), 4904 BUILTIN_ROW(__sync_swap) 4905 }; 4906 #undef BUILTIN_ROW 4907 4908 // Determine the index of the size. 4909 unsigned SizeIndex; 4910 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 4911 case 1: SizeIndex = 0; break; 4912 case 2: SizeIndex = 1; break; 4913 case 4: SizeIndex = 2; break; 4914 case 8: SizeIndex = 3; break; 4915 case 16: SizeIndex = 4; break; 4916 default: 4917 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 4918 << FirstArg->getType() << FirstArg->getSourceRange(); 4919 return ExprError(); 4920 } 4921 4922 // Each of these builtins has one pointer argument, followed by some number of 4923 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 4924 // that we ignore. Find out which row of BuiltinIndices to read from as well 4925 // as the number of fixed args. 4926 unsigned BuiltinID = FDecl->getBuiltinID(); 4927 unsigned BuiltinIndex, NumFixed = 1; 4928 bool WarnAboutSemanticsChange = false; 4929 switch (BuiltinID) { 4930 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 4931 case Builtin::BI__sync_fetch_and_add: 4932 case Builtin::BI__sync_fetch_and_add_1: 4933 case Builtin::BI__sync_fetch_and_add_2: 4934 case Builtin::BI__sync_fetch_and_add_4: 4935 case Builtin::BI__sync_fetch_and_add_8: 4936 case Builtin::BI__sync_fetch_and_add_16: 4937 BuiltinIndex = 0; 4938 break; 4939 4940 case Builtin::BI__sync_fetch_and_sub: 4941 case Builtin::BI__sync_fetch_and_sub_1: 4942 case Builtin::BI__sync_fetch_and_sub_2: 4943 case Builtin::BI__sync_fetch_and_sub_4: 4944 case Builtin::BI__sync_fetch_and_sub_8: 4945 case Builtin::BI__sync_fetch_and_sub_16: 4946 BuiltinIndex = 1; 4947 break; 4948 4949 case Builtin::BI__sync_fetch_and_or: 4950 case Builtin::BI__sync_fetch_and_or_1: 4951 case Builtin::BI__sync_fetch_and_or_2: 4952 case Builtin::BI__sync_fetch_and_or_4: 4953 case Builtin::BI__sync_fetch_and_or_8: 4954 case Builtin::BI__sync_fetch_and_or_16: 4955 BuiltinIndex = 2; 4956 break; 4957 4958 case Builtin::BI__sync_fetch_and_and: 4959 case Builtin::BI__sync_fetch_and_and_1: 4960 case Builtin::BI__sync_fetch_and_and_2: 4961 case Builtin::BI__sync_fetch_and_and_4: 4962 case Builtin::BI__sync_fetch_and_and_8: 4963 case Builtin::BI__sync_fetch_and_and_16: 4964 BuiltinIndex = 3; 4965 break; 4966 4967 case Builtin::BI__sync_fetch_and_xor: 4968 case Builtin::BI__sync_fetch_and_xor_1: 4969 case Builtin::BI__sync_fetch_and_xor_2: 4970 case Builtin::BI__sync_fetch_and_xor_4: 4971 case Builtin::BI__sync_fetch_and_xor_8: 4972 case Builtin::BI__sync_fetch_and_xor_16: 4973 BuiltinIndex = 4; 4974 break; 4975 4976 case Builtin::BI__sync_fetch_and_nand: 4977 case Builtin::BI__sync_fetch_and_nand_1: 4978 case Builtin::BI__sync_fetch_and_nand_2: 4979 case Builtin::BI__sync_fetch_and_nand_4: 4980 case Builtin::BI__sync_fetch_and_nand_8: 4981 case Builtin::BI__sync_fetch_and_nand_16: 4982 BuiltinIndex = 5; 4983 WarnAboutSemanticsChange = true; 4984 break; 4985 4986 case Builtin::BI__sync_add_and_fetch: 4987 case Builtin::BI__sync_add_and_fetch_1: 4988 case Builtin::BI__sync_add_and_fetch_2: 4989 case Builtin::BI__sync_add_and_fetch_4: 4990 case Builtin::BI__sync_add_and_fetch_8: 4991 case Builtin::BI__sync_add_and_fetch_16: 4992 BuiltinIndex = 6; 4993 break; 4994 4995 case Builtin::BI__sync_sub_and_fetch: 4996 case Builtin::BI__sync_sub_and_fetch_1: 4997 case Builtin::BI__sync_sub_and_fetch_2: 4998 case Builtin::BI__sync_sub_and_fetch_4: 4999 case Builtin::BI__sync_sub_and_fetch_8: 5000 case Builtin::BI__sync_sub_and_fetch_16: 5001 BuiltinIndex = 7; 5002 break; 5003 5004 case Builtin::BI__sync_and_and_fetch: 5005 case Builtin::BI__sync_and_and_fetch_1: 5006 case Builtin::BI__sync_and_and_fetch_2: 5007 case Builtin::BI__sync_and_and_fetch_4: 5008 case Builtin::BI__sync_and_and_fetch_8: 5009 case Builtin::BI__sync_and_and_fetch_16: 5010 BuiltinIndex = 8; 5011 break; 5012 5013 case Builtin::BI__sync_or_and_fetch: 5014 case Builtin::BI__sync_or_and_fetch_1: 5015 case Builtin::BI__sync_or_and_fetch_2: 5016 case Builtin::BI__sync_or_and_fetch_4: 5017 case Builtin::BI__sync_or_and_fetch_8: 5018 case Builtin::BI__sync_or_and_fetch_16: 5019 BuiltinIndex = 9; 5020 break; 5021 5022 case Builtin::BI__sync_xor_and_fetch: 5023 case Builtin::BI__sync_xor_and_fetch_1: 5024 case Builtin::BI__sync_xor_and_fetch_2: 5025 case Builtin::BI__sync_xor_and_fetch_4: 5026 case Builtin::BI__sync_xor_and_fetch_8: 5027 case Builtin::BI__sync_xor_and_fetch_16: 5028 BuiltinIndex = 10; 5029 break; 5030 5031 case Builtin::BI__sync_nand_and_fetch: 5032 case Builtin::BI__sync_nand_and_fetch_1: 5033 case Builtin::BI__sync_nand_and_fetch_2: 5034 case Builtin::BI__sync_nand_and_fetch_4: 5035 case Builtin::BI__sync_nand_and_fetch_8: 5036 case Builtin::BI__sync_nand_and_fetch_16: 5037 BuiltinIndex = 11; 5038 WarnAboutSemanticsChange = true; 5039 break; 5040 5041 case Builtin::BI__sync_val_compare_and_swap: 5042 case Builtin::BI__sync_val_compare_and_swap_1: 5043 case Builtin::BI__sync_val_compare_and_swap_2: 5044 case Builtin::BI__sync_val_compare_and_swap_4: 5045 case Builtin::BI__sync_val_compare_and_swap_8: 5046 case Builtin::BI__sync_val_compare_and_swap_16: 5047 BuiltinIndex = 12; 5048 NumFixed = 2; 5049 break; 5050 5051 case Builtin::BI__sync_bool_compare_and_swap: 5052 case Builtin::BI__sync_bool_compare_and_swap_1: 5053 case Builtin::BI__sync_bool_compare_and_swap_2: 5054 case Builtin::BI__sync_bool_compare_and_swap_4: 5055 case Builtin::BI__sync_bool_compare_and_swap_8: 5056 case Builtin::BI__sync_bool_compare_and_swap_16: 5057 BuiltinIndex = 13; 5058 NumFixed = 2; 5059 ResultType = Context.BoolTy; 5060 break; 5061 5062 case Builtin::BI__sync_lock_test_and_set: 5063 case Builtin::BI__sync_lock_test_and_set_1: 5064 case Builtin::BI__sync_lock_test_and_set_2: 5065 case Builtin::BI__sync_lock_test_and_set_4: 5066 case Builtin::BI__sync_lock_test_and_set_8: 5067 case Builtin::BI__sync_lock_test_and_set_16: 5068 BuiltinIndex = 14; 5069 break; 5070 5071 case Builtin::BI__sync_lock_release: 5072 case Builtin::BI__sync_lock_release_1: 5073 case Builtin::BI__sync_lock_release_2: 5074 case Builtin::BI__sync_lock_release_4: 5075 case Builtin::BI__sync_lock_release_8: 5076 case Builtin::BI__sync_lock_release_16: 5077 BuiltinIndex = 15; 5078 NumFixed = 0; 5079 ResultType = Context.VoidTy; 5080 break; 5081 5082 case Builtin::BI__sync_swap: 5083 case Builtin::BI__sync_swap_1: 5084 case Builtin::BI__sync_swap_2: 5085 case Builtin::BI__sync_swap_4: 5086 case Builtin::BI__sync_swap_8: 5087 case Builtin::BI__sync_swap_16: 5088 BuiltinIndex = 16; 5089 break; 5090 } 5091 5092 // Now that we know how many fixed arguments we expect, first check that we 5093 // have at least that many. 5094 if (TheCall->getNumArgs() < 1+NumFixed) { 5095 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5096 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5097 << Callee->getSourceRange(); 5098 return ExprError(); 5099 } 5100 5101 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5102 << Callee->getSourceRange(); 5103 5104 if (WarnAboutSemanticsChange) { 5105 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5106 << Callee->getSourceRange(); 5107 } 5108 5109 // Get the decl for the concrete builtin from this, we can tell what the 5110 // concrete integer type we should convert to is. 5111 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5112 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5113 FunctionDecl *NewBuiltinDecl; 5114 if (NewBuiltinID == BuiltinID) 5115 NewBuiltinDecl = FDecl; 5116 else { 5117 // Perform builtin lookup to avoid redeclaring it. 5118 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5119 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5120 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5121 assert(Res.getFoundDecl()); 5122 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5123 if (!NewBuiltinDecl) 5124 return ExprError(); 5125 } 5126 5127 // The first argument --- the pointer --- has a fixed type; we 5128 // deduce the types of the rest of the arguments accordingly. Walk 5129 // the remaining arguments, converting them to the deduced value type. 5130 for (unsigned i = 0; i != NumFixed; ++i) { 5131 ExprResult Arg = TheCall->getArg(i+1); 5132 5133 // GCC does an implicit conversion to the pointer or integer ValType. This 5134 // can fail in some cases (1i -> int**), check for this error case now. 5135 // Initialize the argument. 5136 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5137 ValType, /*consume*/ false); 5138 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5139 if (Arg.isInvalid()) 5140 return ExprError(); 5141 5142 // Okay, we have something that *can* be converted to the right type. Check 5143 // to see if there is a potentially weird extension going on here. This can 5144 // happen when you do an atomic operation on something like an char* and 5145 // pass in 42. The 42 gets converted to char. This is even more strange 5146 // for things like 45.123 -> char, etc. 5147 // FIXME: Do this check. 5148 TheCall->setArg(i+1, Arg.get()); 5149 } 5150 5151 // Create a new DeclRefExpr to refer to the new decl. 5152 DeclRefExpr* NewDRE = DeclRefExpr::Create( 5153 Context, 5154 DRE->getQualifierLoc(), 5155 SourceLocation(), 5156 NewBuiltinDecl, 5157 /*enclosing*/ false, 5158 DRE->getLocation(), 5159 Context.BuiltinFnTy, 5160 DRE->getValueKind()); 5161 5162 // Set the callee in the CallExpr. 5163 // FIXME: This loses syntactic information. 5164 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5165 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5166 CK_BuiltinFnToFnPtr); 5167 TheCall->setCallee(PromotedCall.get()); 5168 5169 // Change the result type of the call to match the original value type. This 5170 // is arbitrary, but the codegen for these builtins ins design to handle it 5171 // gracefully. 5172 TheCall->setType(ResultType); 5173 5174 return TheCallResult; 5175 } 5176 5177 /// SemaBuiltinNontemporalOverloaded - We have a call to 5178 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5179 /// overloaded function based on the pointer type of its last argument. 5180 /// 5181 /// This function goes through and does final semantic checking for these 5182 /// builtins. 5183 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5184 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5185 DeclRefExpr *DRE = 5186 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5187 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5188 unsigned BuiltinID = FDecl->getBuiltinID(); 5189 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5190 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5191 "Unexpected nontemporal load/store builtin!"); 5192 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5193 unsigned numArgs = isStore ? 2 : 1; 5194 5195 // Ensure that we have the proper number of arguments. 5196 if (checkArgCount(*this, TheCall, numArgs)) 5197 return ExprError(); 5198 5199 // Inspect the last argument of the nontemporal builtin. This should always 5200 // be a pointer type, from which we imply the type of the memory access. 5201 // Because it is a pointer type, we don't have to worry about any implicit 5202 // casts here. 5203 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5204 ExprResult PointerArgResult = 5205 DefaultFunctionArrayLvalueConversion(PointerArg); 5206 5207 if (PointerArgResult.isInvalid()) 5208 return ExprError(); 5209 PointerArg = PointerArgResult.get(); 5210 TheCall->setArg(numArgs - 1, PointerArg); 5211 5212 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5213 if (!pointerType) { 5214 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5215 << PointerArg->getType() << PointerArg->getSourceRange(); 5216 return ExprError(); 5217 } 5218 5219 QualType ValType = pointerType->getPointeeType(); 5220 5221 // Strip any qualifiers off ValType. 5222 ValType = ValType.getUnqualifiedType(); 5223 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5224 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5225 !ValType->isVectorType()) { 5226 Diag(DRE->getBeginLoc(), 5227 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5228 << PointerArg->getType() << PointerArg->getSourceRange(); 5229 return ExprError(); 5230 } 5231 5232 if (!isStore) { 5233 TheCall->setType(ValType); 5234 return TheCallResult; 5235 } 5236 5237 ExprResult ValArg = TheCall->getArg(0); 5238 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5239 Context, ValType, /*consume*/ false); 5240 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5241 if (ValArg.isInvalid()) 5242 return ExprError(); 5243 5244 TheCall->setArg(0, ValArg.get()); 5245 TheCall->setType(Context.VoidTy); 5246 return TheCallResult; 5247 } 5248 5249 /// CheckObjCString - Checks that the argument to the builtin 5250 /// CFString constructor is correct 5251 /// Note: It might also make sense to do the UTF-16 conversion here (would 5252 /// simplify the backend). 5253 bool Sema::CheckObjCString(Expr *Arg) { 5254 Arg = Arg->IgnoreParenCasts(); 5255 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5256 5257 if (!Literal || !Literal->isAscii()) { 5258 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5259 << Arg->getSourceRange(); 5260 return true; 5261 } 5262 5263 if (Literal->containsNonAsciiOrNull()) { 5264 StringRef String = Literal->getString(); 5265 unsigned NumBytes = String.size(); 5266 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5267 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5268 llvm::UTF16 *ToPtr = &ToBuf[0]; 5269 5270 llvm::ConversionResult Result = 5271 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5272 ToPtr + NumBytes, llvm::strictConversion); 5273 // Check for conversion failure. 5274 if (Result != llvm::conversionOK) 5275 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5276 << Arg->getSourceRange(); 5277 } 5278 return false; 5279 } 5280 5281 /// CheckObjCString - Checks that the format string argument to the os_log() 5282 /// and os_trace() functions is correct, and converts it to const char *. 5283 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5284 Arg = Arg->IgnoreParenCasts(); 5285 auto *Literal = dyn_cast<StringLiteral>(Arg); 5286 if (!Literal) { 5287 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5288 Literal = ObjcLiteral->getString(); 5289 } 5290 } 5291 5292 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5293 return ExprError( 5294 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5295 << Arg->getSourceRange()); 5296 } 5297 5298 ExprResult Result(Literal); 5299 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5300 InitializedEntity Entity = 5301 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5302 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5303 return Result; 5304 } 5305 5306 /// Check that the user is calling the appropriate va_start builtin for the 5307 /// target and calling convention. 5308 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5309 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5310 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5311 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 5312 bool IsWindows = TT.isOSWindows(); 5313 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5314 if (IsX64 || IsAArch64) { 5315 CallingConv CC = CC_C; 5316 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5317 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 5318 if (IsMSVAStart) { 5319 // Don't allow this in System V ABI functions. 5320 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5321 return S.Diag(Fn->getBeginLoc(), 5322 diag::err_ms_va_start_used_in_sysv_function); 5323 } else { 5324 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5325 // On x64 Windows, don't allow this in System V ABI functions. 5326 // (Yes, that means there's no corresponding way to support variadic 5327 // System V ABI functions on Windows.) 5328 if ((IsWindows && CC == CC_X86_64SysV) || 5329 (!IsWindows && CC == CC_Win64)) 5330 return S.Diag(Fn->getBeginLoc(), 5331 diag::err_va_start_used_in_wrong_abi_function) 5332 << !IsWindows; 5333 } 5334 return false; 5335 } 5336 5337 if (IsMSVAStart) 5338 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5339 return false; 5340 } 5341 5342 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5343 ParmVarDecl **LastParam = nullptr) { 5344 // Determine whether the current function, block, or obj-c method is variadic 5345 // and get its parameter list. 5346 bool IsVariadic = false; 5347 ArrayRef<ParmVarDecl *> Params; 5348 DeclContext *Caller = S.CurContext; 5349 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5350 IsVariadic = Block->isVariadic(); 5351 Params = Block->parameters(); 5352 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5353 IsVariadic = FD->isVariadic(); 5354 Params = FD->parameters(); 5355 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5356 IsVariadic = MD->isVariadic(); 5357 // FIXME: This isn't correct for methods (results in bogus warning). 5358 Params = MD->parameters(); 5359 } else if (isa<CapturedDecl>(Caller)) { 5360 // We don't support va_start in a CapturedDecl. 5361 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5362 return true; 5363 } else { 5364 // This must be some other declcontext that parses exprs. 5365 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5366 return true; 5367 } 5368 5369 if (!IsVariadic) { 5370 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5371 return true; 5372 } 5373 5374 if (LastParam) 5375 *LastParam = Params.empty() ? nullptr : Params.back(); 5376 5377 return false; 5378 } 5379 5380 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5381 /// for validity. Emit an error and return true on failure; return false 5382 /// on success. 5383 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5384 Expr *Fn = TheCall->getCallee(); 5385 5386 if (checkVAStartABI(*this, BuiltinID, Fn)) 5387 return true; 5388 5389 if (TheCall->getNumArgs() > 2) { 5390 Diag(TheCall->getArg(2)->getBeginLoc(), 5391 diag::err_typecheck_call_too_many_args) 5392 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5393 << Fn->getSourceRange() 5394 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5395 (*(TheCall->arg_end() - 1))->getEndLoc()); 5396 return true; 5397 } 5398 5399 if (TheCall->getNumArgs() < 2) { 5400 return Diag(TheCall->getEndLoc(), 5401 diag::err_typecheck_call_too_few_args_at_least) 5402 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5403 } 5404 5405 // Type-check the first argument normally. 5406 if (checkBuiltinArgument(*this, TheCall, 0)) 5407 return true; 5408 5409 // Check that the current function is variadic, and get its last parameter. 5410 ParmVarDecl *LastParam; 5411 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5412 return true; 5413 5414 // Verify that the second argument to the builtin is the last argument of the 5415 // current function or method. 5416 bool SecondArgIsLastNamedArgument = false; 5417 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5418 5419 // These are valid if SecondArgIsLastNamedArgument is false after the next 5420 // block. 5421 QualType Type; 5422 SourceLocation ParamLoc; 5423 bool IsCRegister = false; 5424 5425 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5426 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5427 SecondArgIsLastNamedArgument = PV == LastParam; 5428 5429 Type = PV->getType(); 5430 ParamLoc = PV->getLocation(); 5431 IsCRegister = 5432 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5433 } 5434 } 5435 5436 if (!SecondArgIsLastNamedArgument) 5437 Diag(TheCall->getArg(1)->getBeginLoc(), 5438 diag::warn_second_arg_of_va_start_not_last_named_param); 5439 else if (IsCRegister || Type->isReferenceType() || 5440 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5441 // Promotable integers are UB, but enumerations need a bit of 5442 // extra checking to see what their promotable type actually is. 5443 if (!Type->isPromotableIntegerType()) 5444 return false; 5445 if (!Type->isEnumeralType()) 5446 return true; 5447 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 5448 return !(ED && 5449 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5450 }()) { 5451 unsigned Reason = 0; 5452 if (Type->isReferenceType()) Reason = 1; 5453 else if (IsCRegister) Reason = 2; 5454 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5455 Diag(ParamLoc, diag::note_parameter_type) << Type; 5456 } 5457 5458 TheCall->setType(Context.VoidTy); 5459 return false; 5460 } 5461 5462 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5463 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5464 // const char *named_addr); 5465 5466 Expr *Func = Call->getCallee(); 5467 5468 if (Call->getNumArgs() < 3) 5469 return Diag(Call->getEndLoc(), 5470 diag::err_typecheck_call_too_few_args_at_least) 5471 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5472 5473 // Type-check the first argument normally. 5474 if (checkBuiltinArgument(*this, Call, 0)) 5475 return true; 5476 5477 // Check that the current function is variadic. 5478 if (checkVAStartIsInVariadicFunction(*this, Func)) 5479 return true; 5480 5481 // __va_start on Windows does not validate the parameter qualifiers 5482 5483 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5484 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5485 5486 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5487 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5488 5489 const QualType &ConstCharPtrTy = 5490 Context.getPointerType(Context.CharTy.withConst()); 5491 if (!Arg1Ty->isPointerType() || 5492 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5493 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5494 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5495 << 0 /* qualifier difference */ 5496 << 3 /* parameter mismatch */ 5497 << 2 << Arg1->getType() << ConstCharPtrTy; 5498 5499 const QualType SizeTy = Context.getSizeType(); 5500 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5501 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5502 << Arg2->getType() << SizeTy << 1 /* different class */ 5503 << 0 /* qualifier difference */ 5504 << 3 /* parameter mismatch */ 5505 << 3 << Arg2->getType() << SizeTy; 5506 5507 return false; 5508 } 5509 5510 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5511 /// friends. This is declared to take (...), so we have to check everything. 5512 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5513 if (TheCall->getNumArgs() < 2) 5514 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5515 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5516 if (TheCall->getNumArgs() > 2) 5517 return Diag(TheCall->getArg(2)->getBeginLoc(), 5518 diag::err_typecheck_call_too_many_args) 5519 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5520 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5521 (*(TheCall->arg_end() - 1))->getEndLoc()); 5522 5523 ExprResult OrigArg0 = TheCall->getArg(0); 5524 ExprResult OrigArg1 = TheCall->getArg(1); 5525 5526 // Do standard promotions between the two arguments, returning their common 5527 // type. 5528 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 5529 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5530 return true; 5531 5532 // Make sure any conversions are pushed back into the call; this is 5533 // type safe since unordered compare builtins are declared as "_Bool 5534 // foo(...)". 5535 TheCall->setArg(0, OrigArg0.get()); 5536 TheCall->setArg(1, OrigArg1.get()); 5537 5538 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5539 return false; 5540 5541 // If the common type isn't a real floating type, then the arguments were 5542 // invalid for this operation. 5543 if (Res.isNull() || !Res->isRealFloatingType()) 5544 return Diag(OrigArg0.get()->getBeginLoc(), 5545 diag::err_typecheck_call_invalid_ordered_compare) 5546 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5547 << SourceRange(OrigArg0.get()->getBeginLoc(), 5548 OrigArg1.get()->getEndLoc()); 5549 5550 return false; 5551 } 5552 5553 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5554 /// __builtin_isnan and friends. This is declared to take (...), so we have 5555 /// to check everything. We expect the last argument to be a floating point 5556 /// value. 5557 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5558 if (TheCall->getNumArgs() < NumArgs) 5559 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5560 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5561 if (TheCall->getNumArgs() > NumArgs) 5562 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5563 diag::err_typecheck_call_too_many_args) 5564 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5565 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5566 (*(TheCall->arg_end() - 1))->getEndLoc()); 5567 5568 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5569 5570 if (OrigArg->isTypeDependent()) 5571 return false; 5572 5573 // This operation requires a non-_Complex floating-point number. 5574 if (!OrigArg->getType()->isRealFloatingType()) 5575 return Diag(OrigArg->getBeginLoc(), 5576 diag::err_typecheck_call_invalid_unary_fp) 5577 << OrigArg->getType() << OrigArg->getSourceRange(); 5578 5579 // If this is an implicit conversion from float -> float, double, or 5580 // long double, remove it. 5581 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 5582 // Only remove standard FloatCasts, leaving other casts inplace 5583 if (Cast->getCastKind() == CK_FloatingCast) { 5584 Expr *CastArg = Cast->getSubExpr(); 5585 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 5586 assert( 5587 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 5588 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || 5589 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && 5590 "promotion from float to either float, double, or long double is " 5591 "the only expected cast here"); 5592 Cast->setSubExpr(nullptr); 5593 TheCall->setArg(NumArgs-1, CastArg); 5594 } 5595 } 5596 } 5597 5598 return false; 5599 } 5600 5601 // Customized Sema Checking for VSX builtins that have the following signature: 5602 // vector [...] builtinName(vector [...], vector [...], const int); 5603 // Which takes the same type of vectors (any legal vector type) for the first 5604 // two arguments and takes compile time constant for the third argument. 5605 // Example builtins are : 5606 // vector double vec_xxpermdi(vector double, vector double, int); 5607 // vector short vec_xxsldwi(vector short, vector short, int); 5608 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5609 unsigned ExpectedNumArgs = 3; 5610 if (TheCall->getNumArgs() < ExpectedNumArgs) 5611 return Diag(TheCall->getEndLoc(), 5612 diag::err_typecheck_call_too_few_args_at_least) 5613 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5614 << TheCall->getSourceRange(); 5615 5616 if (TheCall->getNumArgs() > ExpectedNumArgs) 5617 return Diag(TheCall->getEndLoc(), 5618 diag::err_typecheck_call_too_many_args_at_most) 5619 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5620 << TheCall->getSourceRange(); 5621 5622 // Check the third argument is a compile time constant 5623 llvm::APSInt Value; 5624 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5625 return Diag(TheCall->getBeginLoc(), 5626 diag::err_vsx_builtin_nonconstant_argument) 5627 << 3 /* argument index */ << TheCall->getDirectCallee() 5628 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5629 TheCall->getArg(2)->getEndLoc()); 5630 5631 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5632 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5633 5634 // Check the type of argument 1 and argument 2 are vectors. 5635 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5636 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5637 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5638 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5639 << TheCall->getDirectCallee() 5640 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5641 TheCall->getArg(1)->getEndLoc()); 5642 } 5643 5644 // Check the first two arguments are the same type. 5645 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5646 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5647 << TheCall->getDirectCallee() 5648 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5649 TheCall->getArg(1)->getEndLoc()); 5650 } 5651 5652 // When default clang type checking is turned off and the customized type 5653 // checking is used, the returning type of the function must be explicitly 5654 // set. Otherwise it is _Bool by default. 5655 TheCall->setType(Arg1Ty); 5656 5657 return false; 5658 } 5659 5660 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5661 // This is declared to take (...), so we have to check everything. 5662 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5663 if (TheCall->getNumArgs() < 2) 5664 return ExprError(Diag(TheCall->getEndLoc(), 5665 diag::err_typecheck_call_too_few_args_at_least) 5666 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5667 << TheCall->getSourceRange()); 5668 5669 // Determine which of the following types of shufflevector we're checking: 5670 // 1) unary, vector mask: (lhs, mask) 5671 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5672 QualType resType = TheCall->getArg(0)->getType(); 5673 unsigned numElements = 0; 5674 5675 if (!TheCall->getArg(0)->isTypeDependent() && 5676 !TheCall->getArg(1)->isTypeDependent()) { 5677 QualType LHSType = TheCall->getArg(0)->getType(); 5678 QualType RHSType = TheCall->getArg(1)->getType(); 5679 5680 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5681 return ExprError( 5682 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5683 << TheCall->getDirectCallee() 5684 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5685 TheCall->getArg(1)->getEndLoc())); 5686 5687 numElements = LHSType->getAs<VectorType>()->getNumElements(); 5688 unsigned numResElements = TheCall->getNumArgs() - 2; 5689 5690 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5691 // with mask. If so, verify that RHS is an integer vector type with the 5692 // same number of elts as lhs. 5693 if (TheCall->getNumArgs() == 2) { 5694 if (!RHSType->hasIntegerRepresentation() || 5695 RHSType->getAs<VectorType>()->getNumElements() != numElements) 5696 return ExprError(Diag(TheCall->getBeginLoc(), 5697 diag::err_vec_builtin_incompatible_vector) 5698 << TheCall->getDirectCallee() 5699 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5700 TheCall->getArg(1)->getEndLoc())); 5701 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5702 return ExprError(Diag(TheCall->getBeginLoc(), 5703 diag::err_vec_builtin_incompatible_vector) 5704 << TheCall->getDirectCallee() 5705 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5706 TheCall->getArg(1)->getEndLoc())); 5707 } else if (numElements != numResElements) { 5708 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 5709 resType = Context.getVectorType(eltType, numResElements, 5710 VectorType::GenericVector); 5711 } 5712 } 5713 5714 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5715 if (TheCall->getArg(i)->isTypeDependent() || 5716 TheCall->getArg(i)->isValueDependent()) 5717 continue; 5718 5719 llvm::APSInt Result(32); 5720 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5721 return ExprError(Diag(TheCall->getBeginLoc(), 5722 diag::err_shufflevector_nonconstant_argument) 5723 << TheCall->getArg(i)->getSourceRange()); 5724 5725 // Allow -1 which will be translated to undef in the IR. 5726 if (Result.isSigned() && Result.isAllOnesValue()) 5727 continue; 5728 5729 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5730 return ExprError(Diag(TheCall->getBeginLoc(), 5731 diag::err_shufflevector_argument_too_large) 5732 << TheCall->getArg(i)->getSourceRange()); 5733 } 5734 5735 SmallVector<Expr*, 32> exprs; 5736 5737 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5738 exprs.push_back(TheCall->getArg(i)); 5739 TheCall->setArg(i, nullptr); 5740 } 5741 5742 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5743 TheCall->getCallee()->getBeginLoc(), 5744 TheCall->getRParenLoc()); 5745 } 5746 5747 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5748 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5749 SourceLocation BuiltinLoc, 5750 SourceLocation RParenLoc) { 5751 ExprValueKind VK = VK_RValue; 5752 ExprObjectKind OK = OK_Ordinary; 5753 QualType DstTy = TInfo->getType(); 5754 QualType SrcTy = E->getType(); 5755 5756 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5757 return ExprError(Diag(BuiltinLoc, 5758 diag::err_convertvector_non_vector) 5759 << E->getSourceRange()); 5760 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5761 return ExprError(Diag(BuiltinLoc, 5762 diag::err_convertvector_non_vector_type)); 5763 5764 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5765 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 5766 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 5767 if (SrcElts != DstElts) 5768 return ExprError(Diag(BuiltinLoc, 5769 diag::err_convertvector_incompatible_vector) 5770 << E->getSourceRange()); 5771 } 5772 5773 return new (Context) 5774 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5775 } 5776 5777 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5778 // This is declared to take (const void*, ...) and can take two 5779 // optional constant int args. 5780 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5781 unsigned NumArgs = TheCall->getNumArgs(); 5782 5783 if (NumArgs > 3) 5784 return Diag(TheCall->getEndLoc(), 5785 diag::err_typecheck_call_too_many_args_at_most) 5786 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5787 5788 // Argument 0 is checked for us and the remaining arguments must be 5789 // constant integers. 5790 for (unsigned i = 1; i != NumArgs; ++i) 5791 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5792 return true; 5793 5794 return false; 5795 } 5796 5797 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5798 // __assume does not evaluate its arguments, and should warn if its argument 5799 // has side effects. 5800 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5801 Expr *Arg = TheCall->getArg(0); 5802 if (Arg->isInstantiationDependent()) return false; 5803 5804 if (Arg->HasSideEffects(Context)) 5805 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5806 << Arg->getSourceRange() 5807 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5808 5809 return false; 5810 } 5811 5812 /// Handle __builtin_alloca_with_align. This is declared 5813 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5814 /// than 8. 5815 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5816 // The alignment must be a constant integer. 5817 Expr *Arg = TheCall->getArg(1); 5818 5819 // We can't check the value of a dependent argument. 5820 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5821 if (const auto *UE = 5822 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5823 if (UE->getKind() == UETT_AlignOf || 5824 UE->getKind() == UETT_PreferredAlignOf) 5825 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5826 << Arg->getSourceRange(); 5827 5828 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5829 5830 if (!Result.isPowerOf2()) 5831 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5832 << Arg->getSourceRange(); 5833 5834 if (Result < Context.getCharWidth()) 5835 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5836 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5837 5838 if (Result > std::numeric_limits<int32_t>::max()) 5839 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5840 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5841 } 5842 5843 return false; 5844 } 5845 5846 /// Handle __builtin_assume_aligned. This is declared 5847 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5848 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5849 unsigned NumArgs = TheCall->getNumArgs(); 5850 5851 if (NumArgs > 3) 5852 return Diag(TheCall->getEndLoc(), 5853 diag::err_typecheck_call_too_many_args_at_most) 5854 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5855 5856 // The alignment must be a constant integer. 5857 Expr *Arg = TheCall->getArg(1); 5858 5859 // We can't check the value of a dependent argument. 5860 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5861 llvm::APSInt Result; 5862 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5863 return true; 5864 5865 if (!Result.isPowerOf2()) 5866 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5867 << Arg->getSourceRange(); 5868 } 5869 5870 if (NumArgs > 2) { 5871 ExprResult Arg(TheCall->getArg(2)); 5872 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5873 Context.getSizeType(), false); 5874 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5875 if (Arg.isInvalid()) return true; 5876 TheCall->setArg(2, Arg.get()); 5877 } 5878 5879 return false; 5880 } 5881 5882 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5883 unsigned BuiltinID = 5884 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5885 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5886 5887 unsigned NumArgs = TheCall->getNumArgs(); 5888 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5889 if (NumArgs < NumRequiredArgs) { 5890 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5891 << 0 /* function call */ << NumRequiredArgs << NumArgs 5892 << TheCall->getSourceRange(); 5893 } 5894 if (NumArgs >= NumRequiredArgs + 0x100) { 5895 return Diag(TheCall->getEndLoc(), 5896 diag::err_typecheck_call_too_many_args_at_most) 5897 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5898 << TheCall->getSourceRange(); 5899 } 5900 unsigned i = 0; 5901 5902 // For formatting call, check buffer arg. 5903 if (!IsSizeCall) { 5904 ExprResult Arg(TheCall->getArg(i)); 5905 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5906 Context, Context.VoidPtrTy, false); 5907 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5908 if (Arg.isInvalid()) 5909 return true; 5910 TheCall->setArg(i, Arg.get()); 5911 i++; 5912 } 5913 5914 // Check string literal arg. 5915 unsigned FormatIdx = i; 5916 { 5917 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 5918 if (Arg.isInvalid()) 5919 return true; 5920 TheCall->setArg(i, Arg.get()); 5921 i++; 5922 } 5923 5924 // Make sure variadic args are scalar. 5925 unsigned FirstDataArg = i; 5926 while (i < NumArgs) { 5927 ExprResult Arg = DefaultVariadicArgumentPromotion( 5928 TheCall->getArg(i), VariadicFunction, nullptr); 5929 if (Arg.isInvalid()) 5930 return true; 5931 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 5932 if (ArgSize.getQuantity() >= 0x100) { 5933 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 5934 << i << (int)ArgSize.getQuantity() << 0xff 5935 << TheCall->getSourceRange(); 5936 } 5937 TheCall->setArg(i, Arg.get()); 5938 i++; 5939 } 5940 5941 // Check formatting specifiers. NOTE: We're only doing this for the non-size 5942 // call to avoid duplicate diagnostics. 5943 if (!IsSizeCall) { 5944 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 5945 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 5946 bool Success = CheckFormatArguments( 5947 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 5948 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 5949 CheckedVarArgs); 5950 if (!Success) 5951 return true; 5952 } 5953 5954 if (IsSizeCall) { 5955 TheCall->setType(Context.getSizeType()); 5956 } else { 5957 TheCall->setType(Context.VoidPtrTy); 5958 } 5959 return false; 5960 } 5961 5962 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 5963 /// TheCall is a constant expression. 5964 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 5965 llvm::APSInt &Result) { 5966 Expr *Arg = TheCall->getArg(ArgNum); 5967 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5968 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5969 5970 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 5971 5972 if (!Arg->isIntegerConstantExpr(Result, Context)) 5973 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 5974 << FDecl->getDeclName() << Arg->getSourceRange(); 5975 5976 return false; 5977 } 5978 5979 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 5980 /// TheCall is a constant expression in the range [Low, High]. 5981 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 5982 int Low, int High, bool RangeIsError) { 5983 llvm::APSInt Result; 5984 5985 // We can't check the value of a dependent argument. 5986 Expr *Arg = TheCall->getArg(ArgNum); 5987 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5988 return false; 5989 5990 // Check constant-ness first. 5991 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5992 return true; 5993 5994 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 5995 if (RangeIsError) 5996 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 5997 << Result.toString(10) << Low << High << Arg->getSourceRange(); 5998 else 5999 // Defer the warning until we know if the code will be emitted so that 6000 // dead code can ignore this. 6001 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6002 PDiag(diag::warn_argument_invalid_range) 6003 << Result.toString(10) << Low << High 6004 << Arg->getSourceRange()); 6005 } 6006 6007 return false; 6008 } 6009 6010 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6011 /// TheCall is a constant expression is a multiple of Num.. 6012 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6013 unsigned Num) { 6014 llvm::APSInt Result; 6015 6016 // We can't check the value of a dependent argument. 6017 Expr *Arg = TheCall->getArg(ArgNum); 6018 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6019 return false; 6020 6021 // Check constant-ness first. 6022 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6023 return true; 6024 6025 if (Result.getSExtValue() % Num != 0) 6026 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6027 << Num << Arg->getSourceRange(); 6028 6029 return false; 6030 } 6031 6032 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6033 /// TheCall is an ARM/AArch64 special register string literal. 6034 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6035 int ArgNum, unsigned ExpectedFieldNum, 6036 bool AllowName) { 6037 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6038 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6039 BuiltinID == ARM::BI__builtin_arm_rsr || 6040 BuiltinID == ARM::BI__builtin_arm_rsrp || 6041 BuiltinID == ARM::BI__builtin_arm_wsr || 6042 BuiltinID == ARM::BI__builtin_arm_wsrp; 6043 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6044 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6045 BuiltinID == AArch64::BI__builtin_arm_rsr || 6046 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6047 BuiltinID == AArch64::BI__builtin_arm_wsr || 6048 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6049 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6050 6051 // We can't check the value of a dependent argument. 6052 Expr *Arg = TheCall->getArg(ArgNum); 6053 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6054 return false; 6055 6056 // Check if the argument is a string literal. 6057 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6058 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6059 << Arg->getSourceRange(); 6060 6061 // Check the type of special register given. 6062 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6063 SmallVector<StringRef, 6> Fields; 6064 Reg.split(Fields, ":"); 6065 6066 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6067 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6068 << Arg->getSourceRange(); 6069 6070 // If the string is the name of a register then we cannot check that it is 6071 // valid here but if the string is of one the forms described in ACLE then we 6072 // can check that the supplied fields are integers and within the valid 6073 // ranges. 6074 if (Fields.size() > 1) { 6075 bool FiveFields = Fields.size() == 5; 6076 6077 bool ValidString = true; 6078 if (IsARMBuiltin) { 6079 ValidString &= Fields[0].startswith_lower("cp") || 6080 Fields[0].startswith_lower("p"); 6081 if (ValidString) 6082 Fields[0] = 6083 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6084 6085 ValidString &= Fields[2].startswith_lower("c"); 6086 if (ValidString) 6087 Fields[2] = Fields[2].drop_front(1); 6088 6089 if (FiveFields) { 6090 ValidString &= Fields[3].startswith_lower("c"); 6091 if (ValidString) 6092 Fields[3] = Fields[3].drop_front(1); 6093 } 6094 } 6095 6096 SmallVector<int, 5> Ranges; 6097 if (FiveFields) 6098 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6099 else 6100 Ranges.append({15, 7, 15}); 6101 6102 for (unsigned i=0; i<Fields.size(); ++i) { 6103 int IntField; 6104 ValidString &= !Fields[i].getAsInteger(10, IntField); 6105 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6106 } 6107 6108 if (!ValidString) 6109 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6110 << Arg->getSourceRange(); 6111 } else if (IsAArch64Builtin && Fields.size() == 1) { 6112 // If the register name is one of those that appear in the condition below 6113 // and the special register builtin being used is one of the write builtins, 6114 // then we require that the argument provided for writing to the register 6115 // is an integer constant expression. This is because it will be lowered to 6116 // an MSR (immediate) instruction, so we need to know the immediate at 6117 // compile time. 6118 if (TheCall->getNumArgs() != 2) 6119 return false; 6120 6121 std::string RegLower = Reg.lower(); 6122 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6123 RegLower != "pan" && RegLower != "uao") 6124 return false; 6125 6126 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6127 } 6128 6129 return false; 6130 } 6131 6132 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6133 /// This checks that the target supports __builtin_longjmp and 6134 /// that val is a constant 1. 6135 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6136 if (!Context.getTargetInfo().hasSjLjLowering()) 6137 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6138 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6139 6140 Expr *Arg = TheCall->getArg(1); 6141 llvm::APSInt Result; 6142 6143 // TODO: This is less than ideal. Overload this to take a value. 6144 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6145 return true; 6146 6147 if (Result != 1) 6148 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6149 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6150 6151 return false; 6152 } 6153 6154 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6155 /// This checks that the target supports __builtin_setjmp. 6156 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6157 if (!Context.getTargetInfo().hasSjLjLowering()) 6158 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6159 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6160 return false; 6161 } 6162 6163 namespace { 6164 6165 class UncoveredArgHandler { 6166 enum { Unknown = -1, AllCovered = -2 }; 6167 6168 signed FirstUncoveredArg = Unknown; 6169 SmallVector<const Expr *, 4> DiagnosticExprs; 6170 6171 public: 6172 UncoveredArgHandler() = default; 6173 6174 bool hasUncoveredArg() const { 6175 return (FirstUncoveredArg >= 0); 6176 } 6177 6178 unsigned getUncoveredArg() const { 6179 assert(hasUncoveredArg() && "no uncovered argument"); 6180 return FirstUncoveredArg; 6181 } 6182 6183 void setAllCovered() { 6184 // A string has been found with all arguments covered, so clear out 6185 // the diagnostics. 6186 DiagnosticExprs.clear(); 6187 FirstUncoveredArg = AllCovered; 6188 } 6189 6190 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6191 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6192 6193 // Don't update if a previous string covers all arguments. 6194 if (FirstUncoveredArg == AllCovered) 6195 return; 6196 6197 // UncoveredArgHandler tracks the highest uncovered argument index 6198 // and with it all the strings that match this index. 6199 if (NewFirstUncoveredArg == FirstUncoveredArg) 6200 DiagnosticExprs.push_back(StrExpr); 6201 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6202 DiagnosticExprs.clear(); 6203 DiagnosticExprs.push_back(StrExpr); 6204 FirstUncoveredArg = NewFirstUncoveredArg; 6205 } 6206 } 6207 6208 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6209 }; 6210 6211 enum StringLiteralCheckType { 6212 SLCT_NotALiteral, 6213 SLCT_UncheckedLiteral, 6214 SLCT_CheckedLiteral 6215 }; 6216 6217 } // namespace 6218 6219 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6220 BinaryOperatorKind BinOpKind, 6221 bool AddendIsRight) { 6222 unsigned BitWidth = Offset.getBitWidth(); 6223 unsigned AddendBitWidth = Addend.getBitWidth(); 6224 // There might be negative interim results. 6225 if (Addend.isUnsigned()) { 6226 Addend = Addend.zext(++AddendBitWidth); 6227 Addend.setIsSigned(true); 6228 } 6229 // Adjust the bit width of the APSInts. 6230 if (AddendBitWidth > BitWidth) { 6231 Offset = Offset.sext(AddendBitWidth); 6232 BitWidth = AddendBitWidth; 6233 } else if (BitWidth > AddendBitWidth) { 6234 Addend = Addend.sext(BitWidth); 6235 } 6236 6237 bool Ov = false; 6238 llvm::APSInt ResOffset = Offset; 6239 if (BinOpKind == BO_Add) 6240 ResOffset = Offset.sadd_ov(Addend, Ov); 6241 else { 6242 assert(AddendIsRight && BinOpKind == BO_Sub && 6243 "operator must be add or sub with addend on the right"); 6244 ResOffset = Offset.ssub_ov(Addend, Ov); 6245 } 6246 6247 // We add an offset to a pointer here so we should support an offset as big as 6248 // possible. 6249 if (Ov) { 6250 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6251 "index (intermediate) result too big"); 6252 Offset = Offset.sext(2 * BitWidth); 6253 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6254 return; 6255 } 6256 6257 Offset = ResOffset; 6258 } 6259 6260 namespace { 6261 6262 // This is a wrapper class around StringLiteral to support offsetted string 6263 // literals as format strings. It takes the offset into account when returning 6264 // the string and its length or the source locations to display notes correctly. 6265 class FormatStringLiteral { 6266 const StringLiteral *FExpr; 6267 int64_t Offset; 6268 6269 public: 6270 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6271 : FExpr(fexpr), Offset(Offset) {} 6272 6273 StringRef getString() const { 6274 return FExpr->getString().drop_front(Offset); 6275 } 6276 6277 unsigned getByteLength() const { 6278 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6279 } 6280 6281 unsigned getLength() const { return FExpr->getLength() - Offset; } 6282 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6283 6284 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6285 6286 QualType getType() const { return FExpr->getType(); } 6287 6288 bool isAscii() const { return FExpr->isAscii(); } 6289 bool isWide() const { return FExpr->isWide(); } 6290 bool isUTF8() const { return FExpr->isUTF8(); } 6291 bool isUTF16() const { return FExpr->isUTF16(); } 6292 bool isUTF32() const { return FExpr->isUTF32(); } 6293 bool isPascal() const { return FExpr->isPascal(); } 6294 6295 SourceLocation getLocationOfByte( 6296 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6297 const TargetInfo &Target, unsigned *StartToken = nullptr, 6298 unsigned *StartTokenByteOffset = nullptr) const { 6299 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6300 StartToken, StartTokenByteOffset); 6301 } 6302 6303 SourceLocation getBeginLoc() const LLVM_READONLY { 6304 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6305 } 6306 6307 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6308 }; 6309 6310 } // namespace 6311 6312 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6313 const Expr *OrigFormatExpr, 6314 ArrayRef<const Expr *> Args, 6315 bool HasVAListArg, unsigned format_idx, 6316 unsigned firstDataArg, 6317 Sema::FormatStringType Type, 6318 bool inFunctionCall, 6319 Sema::VariadicCallType CallType, 6320 llvm::SmallBitVector &CheckedVarArgs, 6321 UncoveredArgHandler &UncoveredArg); 6322 6323 // Determine if an expression is a string literal or constant string. 6324 // If this function returns false on the arguments to a function expecting a 6325 // format string, we will usually need to emit a warning. 6326 // True string literals are then checked by CheckFormatString. 6327 static StringLiteralCheckType 6328 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6329 bool HasVAListArg, unsigned format_idx, 6330 unsigned firstDataArg, Sema::FormatStringType Type, 6331 Sema::VariadicCallType CallType, bool InFunctionCall, 6332 llvm::SmallBitVector &CheckedVarArgs, 6333 UncoveredArgHandler &UncoveredArg, 6334 llvm::APSInt Offset) { 6335 tryAgain: 6336 assert(Offset.isSigned() && "invalid offset"); 6337 6338 if (E->isTypeDependent() || E->isValueDependent()) 6339 return SLCT_NotALiteral; 6340 6341 E = E->IgnoreParenCasts(); 6342 6343 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6344 // Technically -Wformat-nonliteral does not warn about this case. 6345 // The behavior of printf and friends in this case is implementation 6346 // dependent. Ideally if the format string cannot be null then 6347 // it should have a 'nonnull' attribute in the function prototype. 6348 return SLCT_UncheckedLiteral; 6349 6350 switch (E->getStmtClass()) { 6351 case Stmt::BinaryConditionalOperatorClass: 6352 case Stmt::ConditionalOperatorClass: { 6353 // The expression is a literal if both sub-expressions were, and it was 6354 // completely checked only if both sub-expressions were checked. 6355 const AbstractConditionalOperator *C = 6356 cast<AbstractConditionalOperator>(E); 6357 6358 // Determine whether it is necessary to check both sub-expressions, for 6359 // example, because the condition expression is a constant that can be 6360 // evaluated at compile time. 6361 bool CheckLeft = true, CheckRight = true; 6362 6363 bool Cond; 6364 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 6365 if (Cond) 6366 CheckRight = false; 6367 else 6368 CheckLeft = false; 6369 } 6370 6371 // We need to maintain the offsets for the right and the left hand side 6372 // separately to check if every possible indexed expression is a valid 6373 // string literal. They might have different offsets for different string 6374 // literals in the end. 6375 StringLiteralCheckType Left; 6376 if (!CheckLeft) 6377 Left = SLCT_UncheckedLiteral; 6378 else { 6379 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6380 HasVAListArg, format_idx, firstDataArg, 6381 Type, CallType, InFunctionCall, 6382 CheckedVarArgs, UncoveredArg, Offset); 6383 if (Left == SLCT_NotALiteral || !CheckRight) { 6384 return Left; 6385 } 6386 } 6387 6388 StringLiteralCheckType Right = 6389 checkFormatStringExpr(S, C->getFalseExpr(), Args, 6390 HasVAListArg, format_idx, firstDataArg, 6391 Type, CallType, InFunctionCall, CheckedVarArgs, 6392 UncoveredArg, Offset); 6393 6394 return (CheckLeft && Left < Right) ? Left : Right; 6395 } 6396 6397 case Stmt::ImplicitCastExprClass: 6398 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6399 goto tryAgain; 6400 6401 case Stmt::OpaqueValueExprClass: 6402 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6403 E = src; 6404 goto tryAgain; 6405 } 6406 return SLCT_NotALiteral; 6407 6408 case Stmt::PredefinedExprClass: 6409 // While __func__, etc., are technically not string literals, they 6410 // cannot contain format specifiers and thus are not a security 6411 // liability. 6412 return SLCT_UncheckedLiteral; 6413 6414 case Stmt::DeclRefExprClass: { 6415 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6416 6417 // As an exception, do not flag errors for variables binding to 6418 // const string literals. 6419 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6420 bool isConstant = false; 6421 QualType T = DR->getType(); 6422 6423 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6424 isConstant = AT->getElementType().isConstant(S.Context); 6425 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6426 isConstant = T.isConstant(S.Context) && 6427 PT->getPointeeType().isConstant(S.Context); 6428 } else if (T->isObjCObjectPointerType()) { 6429 // In ObjC, there is usually no "const ObjectPointer" type, 6430 // so don't check if the pointee type is constant. 6431 isConstant = T.isConstant(S.Context); 6432 } 6433 6434 if (isConstant) { 6435 if (const Expr *Init = VD->getAnyInitializer()) { 6436 // Look through initializers like const char c[] = { "foo" } 6437 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6438 if (InitList->isStringLiteralInit()) 6439 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6440 } 6441 return checkFormatStringExpr(S, Init, Args, 6442 HasVAListArg, format_idx, 6443 firstDataArg, Type, CallType, 6444 /*InFunctionCall*/ false, CheckedVarArgs, 6445 UncoveredArg, Offset); 6446 } 6447 } 6448 6449 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6450 // special check to see if the format string is a function parameter 6451 // of the function calling the printf function. If the function 6452 // has an attribute indicating it is a printf-like function, then we 6453 // should suppress warnings concerning non-literals being used in a call 6454 // to a vprintf function. For example: 6455 // 6456 // void 6457 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6458 // va_list ap; 6459 // va_start(ap, fmt); 6460 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6461 // ... 6462 // } 6463 if (HasVAListArg) { 6464 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6465 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6466 int PVIndex = PV->getFunctionScopeIndex() + 1; 6467 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6468 // adjust for implicit parameter 6469 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6470 if (MD->isInstance()) 6471 ++PVIndex; 6472 // We also check if the formats are compatible. 6473 // We can't pass a 'scanf' string to a 'printf' function. 6474 if (PVIndex == PVFormat->getFormatIdx() && 6475 Type == S.GetFormatStringType(PVFormat)) 6476 return SLCT_UncheckedLiteral; 6477 } 6478 } 6479 } 6480 } 6481 } 6482 6483 return SLCT_NotALiteral; 6484 } 6485 6486 case Stmt::CallExprClass: 6487 case Stmt::CXXMemberCallExprClass: { 6488 const CallExpr *CE = cast<CallExpr>(E); 6489 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6490 bool IsFirst = true; 6491 StringLiteralCheckType CommonResult; 6492 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6493 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6494 StringLiteralCheckType Result = checkFormatStringExpr( 6495 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6496 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6497 if (IsFirst) { 6498 CommonResult = Result; 6499 IsFirst = false; 6500 } 6501 } 6502 if (!IsFirst) 6503 return CommonResult; 6504 6505 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6506 unsigned BuiltinID = FD->getBuiltinID(); 6507 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6508 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6509 const Expr *Arg = CE->getArg(0); 6510 return checkFormatStringExpr(S, Arg, Args, 6511 HasVAListArg, format_idx, 6512 firstDataArg, Type, CallType, 6513 InFunctionCall, CheckedVarArgs, 6514 UncoveredArg, Offset); 6515 } 6516 } 6517 } 6518 6519 return SLCT_NotALiteral; 6520 } 6521 case Stmt::ObjCMessageExprClass: { 6522 const auto *ME = cast<ObjCMessageExpr>(E); 6523 if (const auto *ND = ME->getMethodDecl()) { 6524 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 6525 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6526 return checkFormatStringExpr( 6527 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6528 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6529 } 6530 } 6531 6532 return SLCT_NotALiteral; 6533 } 6534 case Stmt::ObjCStringLiteralClass: 6535 case Stmt::StringLiteralClass: { 6536 const StringLiteral *StrE = nullptr; 6537 6538 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6539 StrE = ObjCFExpr->getString(); 6540 else 6541 StrE = cast<StringLiteral>(E); 6542 6543 if (StrE) { 6544 if (Offset.isNegative() || Offset > StrE->getLength()) { 6545 // TODO: It would be better to have an explicit warning for out of 6546 // bounds literals. 6547 return SLCT_NotALiteral; 6548 } 6549 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6550 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6551 firstDataArg, Type, InFunctionCall, CallType, 6552 CheckedVarArgs, UncoveredArg); 6553 return SLCT_CheckedLiteral; 6554 } 6555 6556 return SLCT_NotALiteral; 6557 } 6558 case Stmt::BinaryOperatorClass: { 6559 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6560 6561 // A string literal + an int offset is still a string literal. 6562 if (BinOp->isAdditiveOp()) { 6563 Expr::EvalResult LResult, RResult; 6564 6565 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 6566 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 6567 6568 if (LIsInt != RIsInt) { 6569 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6570 6571 if (LIsInt) { 6572 if (BinOpKind == BO_Add) { 6573 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 6574 E = BinOp->getRHS(); 6575 goto tryAgain; 6576 } 6577 } else { 6578 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 6579 E = BinOp->getLHS(); 6580 goto tryAgain; 6581 } 6582 } 6583 } 6584 6585 return SLCT_NotALiteral; 6586 } 6587 case Stmt::UnaryOperatorClass: { 6588 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6589 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6590 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6591 Expr::EvalResult IndexResult; 6592 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 6593 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 6594 /*RHS is int*/ true); 6595 E = ASE->getBase(); 6596 goto tryAgain; 6597 } 6598 } 6599 6600 return SLCT_NotALiteral; 6601 } 6602 6603 default: 6604 return SLCT_NotALiteral; 6605 } 6606 } 6607 6608 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6609 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6610 .Case("scanf", FST_Scanf) 6611 .Cases("printf", "printf0", FST_Printf) 6612 .Cases("NSString", "CFString", FST_NSString) 6613 .Case("strftime", FST_Strftime) 6614 .Case("strfmon", FST_Strfmon) 6615 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6616 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6617 .Case("os_trace", FST_OSLog) 6618 .Case("os_log", FST_OSLog) 6619 .Default(FST_Unknown); 6620 } 6621 6622 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6623 /// functions) for correct use of format strings. 6624 /// Returns true if a format string has been fully checked. 6625 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6626 ArrayRef<const Expr *> Args, 6627 bool IsCXXMember, 6628 VariadicCallType CallType, 6629 SourceLocation Loc, SourceRange Range, 6630 llvm::SmallBitVector &CheckedVarArgs) { 6631 FormatStringInfo FSI; 6632 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6633 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6634 FSI.FirstDataArg, GetFormatStringType(Format), 6635 CallType, Loc, Range, CheckedVarArgs); 6636 return false; 6637 } 6638 6639 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6640 bool HasVAListArg, unsigned format_idx, 6641 unsigned firstDataArg, FormatStringType Type, 6642 VariadicCallType CallType, 6643 SourceLocation Loc, SourceRange Range, 6644 llvm::SmallBitVector &CheckedVarArgs) { 6645 // CHECK: printf/scanf-like function is called with no format string. 6646 if (format_idx >= Args.size()) { 6647 Diag(Loc, diag::warn_missing_format_string) << Range; 6648 return false; 6649 } 6650 6651 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6652 6653 // CHECK: format string is not a string literal. 6654 // 6655 // Dynamically generated format strings are difficult to 6656 // automatically vet at compile time. Requiring that format strings 6657 // are string literals: (1) permits the checking of format strings by 6658 // the compiler and thereby (2) can practically remove the source of 6659 // many format string exploits. 6660 6661 // Format string can be either ObjC string (e.g. @"%d") or 6662 // C string (e.g. "%d") 6663 // ObjC string uses the same format specifiers as C string, so we can use 6664 // the same format string checking logic for both ObjC and C strings. 6665 UncoveredArgHandler UncoveredArg; 6666 StringLiteralCheckType CT = 6667 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 6668 format_idx, firstDataArg, Type, CallType, 6669 /*IsFunctionCall*/ true, CheckedVarArgs, 6670 UncoveredArg, 6671 /*no string offset*/ llvm::APSInt(64, false) = 0); 6672 6673 // Generate a diagnostic where an uncovered argument is detected. 6674 if (UncoveredArg.hasUncoveredArg()) { 6675 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 6676 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 6677 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 6678 } 6679 6680 if (CT != SLCT_NotALiteral) 6681 // Literal format string found, check done! 6682 return CT == SLCT_CheckedLiteral; 6683 6684 // Strftime is particular as it always uses a single 'time' argument, 6685 // so it is safe to pass a non-literal string. 6686 if (Type == FST_Strftime) 6687 return false; 6688 6689 // Do not emit diag when the string param is a macro expansion and the 6690 // format is either NSString or CFString. This is a hack to prevent 6691 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 6692 // which are usually used in place of NS and CF string literals. 6693 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 6694 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 6695 return false; 6696 6697 // If there are no arguments specified, warn with -Wformat-security, otherwise 6698 // warn only with -Wformat-nonliteral. 6699 if (Args.size() == firstDataArg) { 6700 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 6701 << OrigFormatExpr->getSourceRange(); 6702 switch (Type) { 6703 default: 6704 break; 6705 case FST_Kprintf: 6706 case FST_FreeBSDKPrintf: 6707 case FST_Printf: 6708 Diag(FormatLoc, diag::note_format_security_fixit) 6709 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 6710 break; 6711 case FST_NSString: 6712 Diag(FormatLoc, diag::note_format_security_fixit) 6713 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 6714 break; 6715 } 6716 } else { 6717 Diag(FormatLoc, diag::warn_format_nonliteral) 6718 << OrigFormatExpr->getSourceRange(); 6719 } 6720 return false; 6721 } 6722 6723 namespace { 6724 6725 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 6726 protected: 6727 Sema &S; 6728 const FormatStringLiteral *FExpr; 6729 const Expr *OrigFormatExpr; 6730 const Sema::FormatStringType FSType; 6731 const unsigned FirstDataArg; 6732 const unsigned NumDataArgs; 6733 const char *Beg; // Start of format string. 6734 const bool HasVAListArg; 6735 ArrayRef<const Expr *> Args; 6736 unsigned FormatIdx; 6737 llvm::SmallBitVector CoveredArgs; 6738 bool usesPositionalArgs = false; 6739 bool atFirstArg = true; 6740 bool inFunctionCall; 6741 Sema::VariadicCallType CallType; 6742 llvm::SmallBitVector &CheckedVarArgs; 6743 UncoveredArgHandler &UncoveredArg; 6744 6745 public: 6746 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 6747 const Expr *origFormatExpr, 6748 const Sema::FormatStringType type, unsigned firstDataArg, 6749 unsigned numDataArgs, const char *beg, bool hasVAListArg, 6750 ArrayRef<const Expr *> Args, unsigned formatIdx, 6751 bool inFunctionCall, Sema::VariadicCallType callType, 6752 llvm::SmallBitVector &CheckedVarArgs, 6753 UncoveredArgHandler &UncoveredArg) 6754 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 6755 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 6756 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 6757 inFunctionCall(inFunctionCall), CallType(callType), 6758 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 6759 CoveredArgs.resize(numDataArgs); 6760 CoveredArgs.reset(); 6761 } 6762 6763 void DoneProcessing(); 6764 6765 void HandleIncompleteSpecifier(const char *startSpecifier, 6766 unsigned specifierLen) override; 6767 6768 void HandleInvalidLengthModifier( 6769 const analyze_format_string::FormatSpecifier &FS, 6770 const analyze_format_string::ConversionSpecifier &CS, 6771 const char *startSpecifier, unsigned specifierLen, 6772 unsigned DiagID); 6773 6774 void HandleNonStandardLengthModifier( 6775 const analyze_format_string::FormatSpecifier &FS, 6776 const char *startSpecifier, unsigned specifierLen); 6777 6778 void HandleNonStandardConversionSpecifier( 6779 const analyze_format_string::ConversionSpecifier &CS, 6780 const char *startSpecifier, unsigned specifierLen); 6781 6782 void HandlePosition(const char *startPos, unsigned posLen) override; 6783 6784 void HandleInvalidPosition(const char *startSpecifier, 6785 unsigned specifierLen, 6786 analyze_format_string::PositionContext p) override; 6787 6788 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 6789 6790 void HandleNullChar(const char *nullCharacter) override; 6791 6792 template <typename Range> 6793 static void 6794 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 6795 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 6796 bool IsStringLocation, Range StringRange, 6797 ArrayRef<FixItHint> Fixit = None); 6798 6799 protected: 6800 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 6801 const char *startSpec, 6802 unsigned specifierLen, 6803 const char *csStart, unsigned csLen); 6804 6805 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 6806 const char *startSpec, 6807 unsigned specifierLen); 6808 6809 SourceRange getFormatStringRange(); 6810 CharSourceRange getSpecifierRange(const char *startSpecifier, 6811 unsigned specifierLen); 6812 SourceLocation getLocationOfByte(const char *x); 6813 6814 const Expr *getDataArg(unsigned i) const; 6815 6816 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 6817 const analyze_format_string::ConversionSpecifier &CS, 6818 const char *startSpecifier, unsigned specifierLen, 6819 unsigned argIndex); 6820 6821 template <typename Range> 6822 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 6823 bool IsStringLocation, Range StringRange, 6824 ArrayRef<FixItHint> Fixit = None); 6825 }; 6826 6827 } // namespace 6828 6829 SourceRange CheckFormatHandler::getFormatStringRange() { 6830 return OrigFormatExpr->getSourceRange(); 6831 } 6832 6833 CharSourceRange CheckFormatHandler:: 6834 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 6835 SourceLocation Start = getLocationOfByte(startSpecifier); 6836 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 6837 6838 // Advance the end SourceLocation by one due to half-open ranges. 6839 End = End.getLocWithOffset(1); 6840 6841 return CharSourceRange::getCharRange(Start, End); 6842 } 6843 6844 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 6845 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 6846 S.getLangOpts(), S.Context.getTargetInfo()); 6847 } 6848 6849 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 6850 unsigned specifierLen){ 6851 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 6852 getLocationOfByte(startSpecifier), 6853 /*IsStringLocation*/true, 6854 getSpecifierRange(startSpecifier, specifierLen)); 6855 } 6856 6857 void CheckFormatHandler::HandleInvalidLengthModifier( 6858 const analyze_format_string::FormatSpecifier &FS, 6859 const analyze_format_string::ConversionSpecifier &CS, 6860 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 6861 using namespace analyze_format_string; 6862 6863 const LengthModifier &LM = FS.getLengthModifier(); 6864 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6865 6866 // See if we know how to fix this length modifier. 6867 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6868 if (FixedLM) { 6869 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6870 getLocationOfByte(LM.getStart()), 6871 /*IsStringLocation*/true, 6872 getSpecifierRange(startSpecifier, specifierLen)); 6873 6874 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6875 << FixedLM->toString() 6876 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6877 6878 } else { 6879 FixItHint Hint; 6880 if (DiagID == diag::warn_format_nonsensical_length) 6881 Hint = FixItHint::CreateRemoval(LMRange); 6882 6883 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6884 getLocationOfByte(LM.getStart()), 6885 /*IsStringLocation*/true, 6886 getSpecifierRange(startSpecifier, specifierLen), 6887 Hint); 6888 } 6889 } 6890 6891 void CheckFormatHandler::HandleNonStandardLengthModifier( 6892 const analyze_format_string::FormatSpecifier &FS, 6893 const char *startSpecifier, unsigned specifierLen) { 6894 using namespace analyze_format_string; 6895 6896 const LengthModifier &LM = FS.getLengthModifier(); 6897 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6898 6899 // See if we know how to fix this length modifier. 6900 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6901 if (FixedLM) { 6902 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6903 << LM.toString() << 0, 6904 getLocationOfByte(LM.getStart()), 6905 /*IsStringLocation*/true, 6906 getSpecifierRange(startSpecifier, specifierLen)); 6907 6908 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6909 << FixedLM->toString() 6910 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6911 6912 } else { 6913 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6914 << LM.toString() << 0, 6915 getLocationOfByte(LM.getStart()), 6916 /*IsStringLocation*/true, 6917 getSpecifierRange(startSpecifier, specifierLen)); 6918 } 6919 } 6920 6921 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 6922 const analyze_format_string::ConversionSpecifier &CS, 6923 const char *startSpecifier, unsigned specifierLen) { 6924 using namespace analyze_format_string; 6925 6926 // See if we know how to fix this conversion specifier. 6927 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 6928 if (FixedCS) { 6929 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6930 << CS.toString() << /*conversion specifier*/1, 6931 getLocationOfByte(CS.getStart()), 6932 /*IsStringLocation*/true, 6933 getSpecifierRange(startSpecifier, specifierLen)); 6934 6935 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 6936 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 6937 << FixedCS->toString() 6938 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 6939 } else { 6940 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6941 << CS.toString() << /*conversion specifier*/1, 6942 getLocationOfByte(CS.getStart()), 6943 /*IsStringLocation*/true, 6944 getSpecifierRange(startSpecifier, specifierLen)); 6945 } 6946 } 6947 6948 void CheckFormatHandler::HandlePosition(const char *startPos, 6949 unsigned posLen) { 6950 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 6951 getLocationOfByte(startPos), 6952 /*IsStringLocation*/true, 6953 getSpecifierRange(startPos, posLen)); 6954 } 6955 6956 void 6957 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 6958 analyze_format_string::PositionContext p) { 6959 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 6960 << (unsigned) p, 6961 getLocationOfByte(startPos), /*IsStringLocation*/true, 6962 getSpecifierRange(startPos, posLen)); 6963 } 6964 6965 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 6966 unsigned posLen) { 6967 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 6968 getLocationOfByte(startPos), 6969 /*IsStringLocation*/true, 6970 getSpecifierRange(startPos, posLen)); 6971 } 6972 6973 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 6974 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 6975 // The presence of a null character is likely an error. 6976 EmitFormatDiagnostic( 6977 S.PDiag(diag::warn_printf_format_string_contains_null_char), 6978 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 6979 getFormatStringRange()); 6980 } 6981 } 6982 6983 // Note that this may return NULL if there was an error parsing or building 6984 // one of the argument expressions. 6985 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 6986 return Args[FirstDataArg + i]; 6987 } 6988 6989 void CheckFormatHandler::DoneProcessing() { 6990 // Does the number of data arguments exceed the number of 6991 // format conversions in the format string? 6992 if (!HasVAListArg) { 6993 // Find any arguments that weren't covered. 6994 CoveredArgs.flip(); 6995 signed notCoveredArg = CoveredArgs.find_first(); 6996 if (notCoveredArg >= 0) { 6997 assert((unsigned)notCoveredArg < NumDataArgs); 6998 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 6999 } else { 7000 UncoveredArg.setAllCovered(); 7001 } 7002 } 7003 } 7004 7005 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7006 const Expr *ArgExpr) { 7007 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7008 "Invalid state"); 7009 7010 if (!ArgExpr) 7011 return; 7012 7013 SourceLocation Loc = ArgExpr->getBeginLoc(); 7014 7015 if (S.getSourceManager().isInSystemMacro(Loc)) 7016 return; 7017 7018 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7019 for (auto E : DiagnosticExprs) 7020 PDiag << E->getSourceRange(); 7021 7022 CheckFormatHandler::EmitFormatDiagnostic( 7023 S, IsFunctionCall, DiagnosticExprs[0], 7024 PDiag, Loc, /*IsStringLocation*/false, 7025 DiagnosticExprs[0]->getSourceRange()); 7026 } 7027 7028 bool 7029 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7030 SourceLocation Loc, 7031 const char *startSpec, 7032 unsigned specifierLen, 7033 const char *csStart, 7034 unsigned csLen) { 7035 bool keepGoing = true; 7036 if (argIndex < NumDataArgs) { 7037 // Consider the argument coverered, even though the specifier doesn't 7038 // make sense. 7039 CoveredArgs.set(argIndex); 7040 } 7041 else { 7042 // If argIndex exceeds the number of data arguments we 7043 // don't issue a warning because that is just a cascade of warnings (and 7044 // they may have intended '%%' anyway). We don't want to continue processing 7045 // the format string after this point, however, as we will like just get 7046 // gibberish when trying to match arguments. 7047 keepGoing = false; 7048 } 7049 7050 StringRef Specifier(csStart, csLen); 7051 7052 // If the specifier in non-printable, it could be the first byte of a UTF-8 7053 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7054 // hex value. 7055 std::string CodePointStr; 7056 if (!llvm::sys::locale::isPrint(*csStart)) { 7057 llvm::UTF32 CodePoint; 7058 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7059 const llvm::UTF8 *E = 7060 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7061 llvm::ConversionResult Result = 7062 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7063 7064 if (Result != llvm::conversionOK) { 7065 unsigned char FirstChar = *csStart; 7066 CodePoint = (llvm::UTF32)FirstChar; 7067 } 7068 7069 llvm::raw_string_ostream OS(CodePointStr); 7070 if (CodePoint < 256) 7071 OS << "\\x" << llvm::format("%02x", CodePoint); 7072 else if (CodePoint <= 0xFFFF) 7073 OS << "\\u" << llvm::format("%04x", CodePoint); 7074 else 7075 OS << "\\U" << llvm::format("%08x", CodePoint); 7076 OS.flush(); 7077 Specifier = CodePointStr; 7078 } 7079 7080 EmitFormatDiagnostic( 7081 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7082 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7083 7084 return keepGoing; 7085 } 7086 7087 void 7088 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7089 const char *startSpec, 7090 unsigned specifierLen) { 7091 EmitFormatDiagnostic( 7092 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7093 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7094 } 7095 7096 bool 7097 CheckFormatHandler::CheckNumArgs( 7098 const analyze_format_string::FormatSpecifier &FS, 7099 const analyze_format_string::ConversionSpecifier &CS, 7100 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7101 7102 if (argIndex >= NumDataArgs) { 7103 PartialDiagnostic PDiag = FS.usesPositionalArg() 7104 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7105 << (argIndex+1) << NumDataArgs) 7106 : S.PDiag(diag::warn_printf_insufficient_data_args); 7107 EmitFormatDiagnostic( 7108 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7109 getSpecifierRange(startSpecifier, specifierLen)); 7110 7111 // Since more arguments than conversion tokens are given, by extension 7112 // all arguments are covered, so mark this as so. 7113 UncoveredArg.setAllCovered(); 7114 return false; 7115 } 7116 return true; 7117 } 7118 7119 template<typename Range> 7120 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7121 SourceLocation Loc, 7122 bool IsStringLocation, 7123 Range StringRange, 7124 ArrayRef<FixItHint> FixIt) { 7125 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7126 Loc, IsStringLocation, StringRange, FixIt); 7127 } 7128 7129 /// If the format string is not within the function call, emit a note 7130 /// so that the function call and string are in diagnostic messages. 7131 /// 7132 /// \param InFunctionCall if true, the format string is within the function 7133 /// call and only one diagnostic message will be produced. Otherwise, an 7134 /// extra note will be emitted pointing to location of the format string. 7135 /// 7136 /// \param ArgumentExpr the expression that is passed as the format string 7137 /// argument in the function call. Used for getting locations when two 7138 /// diagnostics are emitted. 7139 /// 7140 /// \param PDiag the callee should already have provided any strings for the 7141 /// diagnostic message. This function only adds locations and fixits 7142 /// to diagnostics. 7143 /// 7144 /// \param Loc primary location for diagnostic. If two diagnostics are 7145 /// required, one will be at Loc and a new SourceLocation will be created for 7146 /// the other one. 7147 /// 7148 /// \param IsStringLocation if true, Loc points to the format string should be 7149 /// used for the note. Otherwise, Loc points to the argument list and will 7150 /// be used with PDiag. 7151 /// 7152 /// \param StringRange some or all of the string to highlight. This is 7153 /// templated so it can accept either a CharSourceRange or a SourceRange. 7154 /// 7155 /// \param FixIt optional fix it hint for the format string. 7156 template <typename Range> 7157 void CheckFormatHandler::EmitFormatDiagnostic( 7158 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7159 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7160 Range StringRange, ArrayRef<FixItHint> FixIt) { 7161 if (InFunctionCall) { 7162 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7163 D << StringRange; 7164 D << FixIt; 7165 } else { 7166 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7167 << ArgumentExpr->getSourceRange(); 7168 7169 const Sema::SemaDiagnosticBuilder &Note = 7170 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7171 diag::note_format_string_defined); 7172 7173 Note << StringRange; 7174 Note << FixIt; 7175 } 7176 } 7177 7178 //===--- CHECK: Printf format string checking ------------------------------===// 7179 7180 namespace { 7181 7182 class CheckPrintfHandler : public CheckFormatHandler { 7183 public: 7184 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7185 const Expr *origFormatExpr, 7186 const Sema::FormatStringType type, unsigned firstDataArg, 7187 unsigned numDataArgs, bool isObjC, const char *beg, 7188 bool hasVAListArg, ArrayRef<const Expr *> Args, 7189 unsigned formatIdx, bool inFunctionCall, 7190 Sema::VariadicCallType CallType, 7191 llvm::SmallBitVector &CheckedVarArgs, 7192 UncoveredArgHandler &UncoveredArg) 7193 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7194 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7195 inFunctionCall, CallType, CheckedVarArgs, 7196 UncoveredArg) {} 7197 7198 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7199 7200 /// Returns true if '%@' specifiers are allowed in the format string. 7201 bool allowsObjCArg() const { 7202 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7203 FSType == Sema::FST_OSTrace; 7204 } 7205 7206 bool HandleInvalidPrintfConversionSpecifier( 7207 const analyze_printf::PrintfSpecifier &FS, 7208 const char *startSpecifier, 7209 unsigned specifierLen) override; 7210 7211 void handleInvalidMaskType(StringRef MaskType) override; 7212 7213 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7214 const char *startSpecifier, 7215 unsigned specifierLen) override; 7216 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7217 const char *StartSpecifier, 7218 unsigned SpecifierLen, 7219 const Expr *E); 7220 7221 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7222 const char *startSpecifier, unsigned specifierLen); 7223 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7224 const analyze_printf::OptionalAmount &Amt, 7225 unsigned type, 7226 const char *startSpecifier, unsigned specifierLen); 7227 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7228 const analyze_printf::OptionalFlag &flag, 7229 const char *startSpecifier, unsigned specifierLen); 7230 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7231 const analyze_printf::OptionalFlag &ignoredFlag, 7232 const analyze_printf::OptionalFlag &flag, 7233 const char *startSpecifier, unsigned specifierLen); 7234 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7235 const Expr *E); 7236 7237 void HandleEmptyObjCModifierFlag(const char *startFlag, 7238 unsigned flagLen) override; 7239 7240 void HandleInvalidObjCModifierFlag(const char *startFlag, 7241 unsigned flagLen) override; 7242 7243 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7244 const char *flagsEnd, 7245 const char *conversionPosition) 7246 override; 7247 }; 7248 7249 } // namespace 7250 7251 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7252 const analyze_printf::PrintfSpecifier &FS, 7253 const char *startSpecifier, 7254 unsigned specifierLen) { 7255 const analyze_printf::PrintfConversionSpecifier &CS = 7256 FS.getConversionSpecifier(); 7257 7258 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7259 getLocationOfByte(CS.getStart()), 7260 startSpecifier, specifierLen, 7261 CS.getStart(), CS.getLength()); 7262 } 7263 7264 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7265 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7266 } 7267 7268 bool CheckPrintfHandler::HandleAmount( 7269 const analyze_format_string::OptionalAmount &Amt, 7270 unsigned k, const char *startSpecifier, 7271 unsigned specifierLen) { 7272 if (Amt.hasDataArgument()) { 7273 if (!HasVAListArg) { 7274 unsigned argIndex = Amt.getArgIndex(); 7275 if (argIndex >= NumDataArgs) { 7276 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7277 << k, 7278 getLocationOfByte(Amt.getStart()), 7279 /*IsStringLocation*/true, 7280 getSpecifierRange(startSpecifier, specifierLen)); 7281 // Don't do any more checking. We will just emit 7282 // spurious errors. 7283 return false; 7284 } 7285 7286 // Type check the data argument. It should be an 'int'. 7287 // Although not in conformance with C99, we also allow the argument to be 7288 // an 'unsigned int' as that is a reasonably safe case. GCC also 7289 // doesn't emit a warning for that case. 7290 CoveredArgs.set(argIndex); 7291 const Expr *Arg = getDataArg(argIndex); 7292 if (!Arg) 7293 return false; 7294 7295 QualType T = Arg->getType(); 7296 7297 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7298 assert(AT.isValid()); 7299 7300 if (!AT.matchesType(S.Context, T)) { 7301 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7302 << k << AT.getRepresentativeTypeName(S.Context) 7303 << T << Arg->getSourceRange(), 7304 getLocationOfByte(Amt.getStart()), 7305 /*IsStringLocation*/true, 7306 getSpecifierRange(startSpecifier, specifierLen)); 7307 // Don't do any more checking. We will just emit 7308 // spurious errors. 7309 return false; 7310 } 7311 } 7312 } 7313 return true; 7314 } 7315 7316 void CheckPrintfHandler::HandleInvalidAmount( 7317 const analyze_printf::PrintfSpecifier &FS, 7318 const analyze_printf::OptionalAmount &Amt, 7319 unsigned type, 7320 const char *startSpecifier, 7321 unsigned specifierLen) { 7322 const analyze_printf::PrintfConversionSpecifier &CS = 7323 FS.getConversionSpecifier(); 7324 7325 FixItHint fixit = 7326 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7327 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7328 Amt.getConstantLength())) 7329 : FixItHint(); 7330 7331 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7332 << type << CS.toString(), 7333 getLocationOfByte(Amt.getStart()), 7334 /*IsStringLocation*/true, 7335 getSpecifierRange(startSpecifier, specifierLen), 7336 fixit); 7337 } 7338 7339 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7340 const analyze_printf::OptionalFlag &flag, 7341 const char *startSpecifier, 7342 unsigned specifierLen) { 7343 // Warn about pointless flag with a fixit removal. 7344 const analyze_printf::PrintfConversionSpecifier &CS = 7345 FS.getConversionSpecifier(); 7346 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7347 << flag.toString() << CS.toString(), 7348 getLocationOfByte(flag.getPosition()), 7349 /*IsStringLocation*/true, 7350 getSpecifierRange(startSpecifier, specifierLen), 7351 FixItHint::CreateRemoval( 7352 getSpecifierRange(flag.getPosition(), 1))); 7353 } 7354 7355 void CheckPrintfHandler::HandleIgnoredFlag( 7356 const analyze_printf::PrintfSpecifier &FS, 7357 const analyze_printf::OptionalFlag &ignoredFlag, 7358 const analyze_printf::OptionalFlag &flag, 7359 const char *startSpecifier, 7360 unsigned specifierLen) { 7361 // Warn about ignored flag with a fixit removal. 7362 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7363 << ignoredFlag.toString() << flag.toString(), 7364 getLocationOfByte(ignoredFlag.getPosition()), 7365 /*IsStringLocation*/true, 7366 getSpecifierRange(startSpecifier, specifierLen), 7367 FixItHint::CreateRemoval( 7368 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7369 } 7370 7371 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7372 unsigned flagLen) { 7373 // Warn about an empty flag. 7374 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7375 getLocationOfByte(startFlag), 7376 /*IsStringLocation*/true, 7377 getSpecifierRange(startFlag, flagLen)); 7378 } 7379 7380 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7381 unsigned flagLen) { 7382 // Warn about an invalid flag. 7383 auto Range = getSpecifierRange(startFlag, flagLen); 7384 StringRef flag(startFlag, flagLen); 7385 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7386 getLocationOfByte(startFlag), 7387 /*IsStringLocation*/true, 7388 Range, FixItHint::CreateRemoval(Range)); 7389 } 7390 7391 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7392 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7393 // Warn about using '[...]' without a '@' conversion. 7394 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7395 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7396 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7397 getLocationOfByte(conversionPosition), 7398 /*IsStringLocation*/true, 7399 Range, FixItHint::CreateRemoval(Range)); 7400 } 7401 7402 // Determines if the specified is a C++ class or struct containing 7403 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7404 // "c_str()"). 7405 template<typename MemberKind> 7406 static llvm::SmallPtrSet<MemberKind*, 1> 7407 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7408 const RecordType *RT = Ty->getAs<RecordType>(); 7409 llvm::SmallPtrSet<MemberKind*, 1> Results; 7410 7411 if (!RT) 7412 return Results; 7413 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7414 if (!RD || !RD->getDefinition()) 7415 return Results; 7416 7417 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7418 Sema::LookupMemberName); 7419 R.suppressDiagnostics(); 7420 7421 // We just need to include all members of the right kind turned up by the 7422 // filter, at this point. 7423 if (S.LookupQualifiedName(R, RT->getDecl())) 7424 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7425 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7426 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7427 Results.insert(FK); 7428 } 7429 return Results; 7430 } 7431 7432 /// Check if we could call '.c_str()' on an object. 7433 /// 7434 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7435 /// allow the call, or if it would be ambiguous). 7436 bool Sema::hasCStrMethod(const Expr *E) { 7437 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7438 7439 MethodSet Results = 7440 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7441 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7442 MI != ME; ++MI) 7443 if ((*MI)->getMinRequiredArguments() == 0) 7444 return true; 7445 return false; 7446 } 7447 7448 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7449 // better diagnostic if so. AT is assumed to be valid. 7450 // Returns true when a c_str() conversion method is found. 7451 bool CheckPrintfHandler::checkForCStrMembers( 7452 const analyze_printf::ArgType &AT, const Expr *E) { 7453 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7454 7455 MethodSet Results = 7456 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7457 7458 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7459 MI != ME; ++MI) { 7460 const CXXMethodDecl *Method = *MI; 7461 if (Method->getMinRequiredArguments() == 0 && 7462 AT.matchesType(S.Context, Method->getReturnType())) { 7463 // FIXME: Suggest parens if the expression needs them. 7464 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7465 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7466 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7467 return true; 7468 } 7469 } 7470 7471 return false; 7472 } 7473 7474 bool 7475 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7476 &FS, 7477 const char *startSpecifier, 7478 unsigned specifierLen) { 7479 using namespace analyze_format_string; 7480 using namespace analyze_printf; 7481 7482 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7483 7484 if (FS.consumesDataArgument()) { 7485 if (atFirstArg) { 7486 atFirstArg = false; 7487 usesPositionalArgs = FS.usesPositionalArg(); 7488 } 7489 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7490 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7491 startSpecifier, specifierLen); 7492 return false; 7493 } 7494 } 7495 7496 // First check if the field width, precision, and conversion specifier 7497 // have matching data arguments. 7498 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7499 startSpecifier, specifierLen)) { 7500 return false; 7501 } 7502 7503 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7504 startSpecifier, specifierLen)) { 7505 return false; 7506 } 7507 7508 if (!CS.consumesDataArgument()) { 7509 // FIXME: Technically specifying a precision or field width here 7510 // makes no sense. Worth issuing a warning at some point. 7511 return true; 7512 } 7513 7514 // Consume the argument. 7515 unsigned argIndex = FS.getArgIndex(); 7516 if (argIndex < NumDataArgs) { 7517 // The check to see if the argIndex is valid will come later. 7518 // We set the bit here because we may exit early from this 7519 // function if we encounter some other error. 7520 CoveredArgs.set(argIndex); 7521 } 7522 7523 // FreeBSD kernel extensions. 7524 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7525 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7526 // We need at least two arguments. 7527 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7528 return false; 7529 7530 // Claim the second argument. 7531 CoveredArgs.set(argIndex + 1); 7532 7533 // Type check the first argument (int for %b, pointer for %D) 7534 const Expr *Ex = getDataArg(argIndex); 7535 const analyze_printf::ArgType &AT = 7536 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7537 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7538 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7539 EmitFormatDiagnostic( 7540 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7541 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7542 << false << Ex->getSourceRange(), 7543 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7544 getSpecifierRange(startSpecifier, specifierLen)); 7545 7546 // Type check the second argument (char * for both %b and %D) 7547 Ex = getDataArg(argIndex + 1); 7548 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7549 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7550 EmitFormatDiagnostic( 7551 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7552 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7553 << false << Ex->getSourceRange(), 7554 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7555 getSpecifierRange(startSpecifier, specifierLen)); 7556 7557 return true; 7558 } 7559 7560 // Check for using an Objective-C specific conversion specifier 7561 // in a non-ObjC literal. 7562 if (!allowsObjCArg() && CS.isObjCArg()) { 7563 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7564 specifierLen); 7565 } 7566 7567 // %P can only be used with os_log. 7568 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7569 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7570 specifierLen); 7571 } 7572 7573 // %n is not allowed with os_log. 7574 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7575 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7576 getLocationOfByte(CS.getStart()), 7577 /*IsStringLocation*/ false, 7578 getSpecifierRange(startSpecifier, specifierLen)); 7579 7580 return true; 7581 } 7582 7583 // Only scalars are allowed for os_trace. 7584 if (FSType == Sema::FST_OSTrace && 7585 (CS.getKind() == ConversionSpecifier::PArg || 7586 CS.getKind() == ConversionSpecifier::sArg || 7587 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7588 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7589 specifierLen); 7590 } 7591 7592 // Check for use of public/private annotation outside of os_log(). 7593 if (FSType != Sema::FST_OSLog) { 7594 if (FS.isPublic().isSet()) { 7595 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7596 << "public", 7597 getLocationOfByte(FS.isPublic().getPosition()), 7598 /*IsStringLocation*/ false, 7599 getSpecifierRange(startSpecifier, specifierLen)); 7600 } 7601 if (FS.isPrivate().isSet()) { 7602 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7603 << "private", 7604 getLocationOfByte(FS.isPrivate().getPosition()), 7605 /*IsStringLocation*/ false, 7606 getSpecifierRange(startSpecifier, specifierLen)); 7607 } 7608 } 7609 7610 // Check for invalid use of field width 7611 if (!FS.hasValidFieldWidth()) { 7612 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7613 startSpecifier, specifierLen); 7614 } 7615 7616 // Check for invalid use of precision 7617 if (!FS.hasValidPrecision()) { 7618 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7619 startSpecifier, specifierLen); 7620 } 7621 7622 // Precision is mandatory for %P specifier. 7623 if (CS.getKind() == ConversionSpecifier::PArg && 7624 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7625 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7626 getLocationOfByte(startSpecifier), 7627 /*IsStringLocation*/ false, 7628 getSpecifierRange(startSpecifier, specifierLen)); 7629 } 7630 7631 // Check each flag does not conflict with any other component. 7632 if (!FS.hasValidThousandsGroupingPrefix()) 7633 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7634 if (!FS.hasValidLeadingZeros()) 7635 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7636 if (!FS.hasValidPlusPrefix()) 7637 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7638 if (!FS.hasValidSpacePrefix()) 7639 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7640 if (!FS.hasValidAlternativeForm()) 7641 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7642 if (!FS.hasValidLeftJustified()) 7643 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7644 7645 // Check that flags are not ignored by another flag 7646 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7647 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7648 startSpecifier, specifierLen); 7649 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7650 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7651 startSpecifier, specifierLen); 7652 7653 // Check the length modifier is valid with the given conversion specifier. 7654 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 7655 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7656 diag::warn_format_nonsensical_length); 7657 else if (!FS.hasStandardLengthModifier()) 7658 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7659 else if (!FS.hasStandardLengthConversionCombination()) 7660 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7661 diag::warn_format_non_standard_conversion_spec); 7662 7663 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7664 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7665 7666 // The remaining checks depend on the data arguments. 7667 if (HasVAListArg) 7668 return true; 7669 7670 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7671 return false; 7672 7673 const Expr *Arg = getDataArg(argIndex); 7674 if (!Arg) 7675 return true; 7676 7677 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 7678 } 7679 7680 static bool requiresParensToAddCast(const Expr *E) { 7681 // FIXME: We should have a general way to reason about operator 7682 // precedence and whether parens are actually needed here. 7683 // Take care of a few common cases where they aren't. 7684 const Expr *Inside = E->IgnoreImpCasts(); 7685 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 7686 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 7687 7688 switch (Inside->getStmtClass()) { 7689 case Stmt::ArraySubscriptExprClass: 7690 case Stmt::CallExprClass: 7691 case Stmt::CharacterLiteralClass: 7692 case Stmt::CXXBoolLiteralExprClass: 7693 case Stmt::DeclRefExprClass: 7694 case Stmt::FloatingLiteralClass: 7695 case Stmt::IntegerLiteralClass: 7696 case Stmt::MemberExprClass: 7697 case Stmt::ObjCArrayLiteralClass: 7698 case Stmt::ObjCBoolLiteralExprClass: 7699 case Stmt::ObjCBoxedExprClass: 7700 case Stmt::ObjCDictionaryLiteralClass: 7701 case Stmt::ObjCEncodeExprClass: 7702 case Stmt::ObjCIvarRefExprClass: 7703 case Stmt::ObjCMessageExprClass: 7704 case Stmt::ObjCPropertyRefExprClass: 7705 case Stmt::ObjCStringLiteralClass: 7706 case Stmt::ObjCSubscriptRefExprClass: 7707 case Stmt::ParenExprClass: 7708 case Stmt::StringLiteralClass: 7709 case Stmt::UnaryOperatorClass: 7710 return false; 7711 default: 7712 return true; 7713 } 7714 } 7715 7716 static std::pair<QualType, StringRef> 7717 shouldNotPrintDirectly(const ASTContext &Context, 7718 QualType IntendedTy, 7719 const Expr *E) { 7720 // Use a 'while' to peel off layers of typedefs. 7721 QualType TyTy = IntendedTy; 7722 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 7723 StringRef Name = UserTy->getDecl()->getName(); 7724 QualType CastTy = llvm::StringSwitch<QualType>(Name) 7725 .Case("CFIndex", Context.getNSIntegerType()) 7726 .Case("NSInteger", Context.getNSIntegerType()) 7727 .Case("NSUInteger", Context.getNSUIntegerType()) 7728 .Case("SInt32", Context.IntTy) 7729 .Case("UInt32", Context.UnsignedIntTy) 7730 .Default(QualType()); 7731 7732 if (!CastTy.isNull()) 7733 return std::make_pair(CastTy, Name); 7734 7735 TyTy = UserTy->desugar(); 7736 } 7737 7738 // Strip parens if necessary. 7739 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 7740 return shouldNotPrintDirectly(Context, 7741 PE->getSubExpr()->getType(), 7742 PE->getSubExpr()); 7743 7744 // If this is a conditional expression, then its result type is constructed 7745 // via usual arithmetic conversions and thus there might be no necessary 7746 // typedef sugar there. Recurse to operands to check for NSInteger & 7747 // Co. usage condition. 7748 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7749 QualType TrueTy, FalseTy; 7750 StringRef TrueName, FalseName; 7751 7752 std::tie(TrueTy, TrueName) = 7753 shouldNotPrintDirectly(Context, 7754 CO->getTrueExpr()->getType(), 7755 CO->getTrueExpr()); 7756 std::tie(FalseTy, FalseName) = 7757 shouldNotPrintDirectly(Context, 7758 CO->getFalseExpr()->getType(), 7759 CO->getFalseExpr()); 7760 7761 if (TrueTy == FalseTy) 7762 return std::make_pair(TrueTy, TrueName); 7763 else if (TrueTy.isNull()) 7764 return std::make_pair(FalseTy, FalseName); 7765 else if (FalseTy.isNull()) 7766 return std::make_pair(TrueTy, TrueName); 7767 } 7768 7769 return std::make_pair(QualType(), StringRef()); 7770 } 7771 7772 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 7773 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 7774 /// type do not count. 7775 static bool 7776 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 7777 QualType From = ICE->getSubExpr()->getType(); 7778 QualType To = ICE->getType(); 7779 // It's an integer promotion if the destination type is the promoted 7780 // source type. 7781 if (ICE->getCastKind() == CK_IntegralCast && 7782 From->isPromotableIntegerType() && 7783 S.Context.getPromotedIntegerType(From) == To) 7784 return true; 7785 // Look through vector types, since we do default argument promotion for 7786 // those in OpenCL. 7787 if (const auto *VecTy = From->getAs<ExtVectorType>()) 7788 From = VecTy->getElementType(); 7789 if (const auto *VecTy = To->getAs<ExtVectorType>()) 7790 To = VecTy->getElementType(); 7791 // It's a floating promotion if the source type is a lower rank. 7792 return ICE->getCastKind() == CK_FloatingCast && 7793 S.Context.getFloatingTypeOrder(From, To) < 0; 7794 } 7795 7796 bool 7797 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7798 const char *StartSpecifier, 7799 unsigned SpecifierLen, 7800 const Expr *E) { 7801 using namespace analyze_format_string; 7802 using namespace analyze_printf; 7803 7804 // Now type check the data expression that matches the 7805 // format specifier. 7806 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 7807 if (!AT.isValid()) 7808 return true; 7809 7810 QualType ExprTy = E->getType(); 7811 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 7812 ExprTy = TET->getUnderlyingExpr()->getType(); 7813 } 7814 7815 const analyze_printf::ArgType::MatchKind Match = 7816 AT.matchesType(S.Context, ExprTy); 7817 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic; 7818 if (Match == analyze_printf::ArgType::Match) 7819 return true; 7820 7821 // Look through argument promotions for our error message's reported type. 7822 // This includes the integral and floating promotions, but excludes array 7823 // and function pointer decay (seeing that an argument intended to be a 7824 // string has type 'char [6]' is probably more confusing than 'char *') and 7825 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 7826 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7827 if (isArithmeticArgumentPromotion(S, ICE)) { 7828 E = ICE->getSubExpr(); 7829 ExprTy = E->getType(); 7830 7831 // Check if we didn't match because of an implicit cast from a 'char' 7832 // or 'short' to an 'int'. This is done because printf is a varargs 7833 // function. 7834 if (ICE->getType() == S.Context.IntTy || 7835 ICE->getType() == S.Context.UnsignedIntTy) { 7836 // All further checking is done on the subexpression. 7837 if (AT.matchesType(S.Context, ExprTy)) 7838 return true; 7839 } 7840 } 7841 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 7842 // Special case for 'a', which has type 'int' in C. 7843 // Note, however, that we do /not/ want to treat multibyte constants like 7844 // 'MooV' as characters! This form is deprecated but still exists. 7845 if (ExprTy == S.Context.IntTy) 7846 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 7847 ExprTy = S.Context.CharTy; 7848 } 7849 7850 // Look through enums to their underlying type. 7851 bool IsEnum = false; 7852 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 7853 ExprTy = EnumTy->getDecl()->getIntegerType(); 7854 IsEnum = true; 7855 } 7856 7857 // %C in an Objective-C context prints a unichar, not a wchar_t. 7858 // If the argument is an integer of some kind, believe the %C and suggest 7859 // a cast instead of changing the conversion specifier. 7860 QualType IntendedTy = ExprTy; 7861 if (isObjCContext() && 7862 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 7863 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 7864 !ExprTy->isCharType()) { 7865 // 'unichar' is defined as a typedef of unsigned short, but we should 7866 // prefer using the typedef if it is visible. 7867 IntendedTy = S.Context.UnsignedShortTy; 7868 7869 // While we are here, check if the value is an IntegerLiteral that happens 7870 // to be within the valid range. 7871 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 7872 const llvm::APInt &V = IL->getValue(); 7873 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 7874 return true; 7875 } 7876 7877 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 7878 Sema::LookupOrdinaryName); 7879 if (S.LookupName(Result, S.getCurScope())) { 7880 NamedDecl *ND = Result.getFoundDecl(); 7881 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 7882 if (TD->getUnderlyingType() == IntendedTy) 7883 IntendedTy = S.Context.getTypedefType(TD); 7884 } 7885 } 7886 } 7887 7888 // Special-case some of Darwin's platform-independence types by suggesting 7889 // casts to primitive types that are known to be large enough. 7890 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 7891 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 7892 QualType CastTy; 7893 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 7894 if (!CastTy.isNull()) { 7895 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 7896 // (long in ASTContext). Only complain to pedants. 7897 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 7898 (AT.isSizeT() || AT.isPtrdiffT()) && 7899 AT.matchesType(S.Context, CastTy)) 7900 Pedantic = true; 7901 IntendedTy = CastTy; 7902 ShouldNotPrintDirectly = true; 7903 } 7904 } 7905 7906 // We may be able to offer a FixItHint if it is a supported type. 7907 PrintfSpecifier fixedFS = FS; 7908 bool Success = 7909 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 7910 7911 if (Success) { 7912 // Get the fix string from the fixed format specifier 7913 SmallString<16> buf; 7914 llvm::raw_svector_ostream os(buf); 7915 fixedFS.toString(os); 7916 7917 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 7918 7919 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 7920 unsigned Diag = 7921 Pedantic 7922 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 7923 : diag::warn_format_conversion_argument_type_mismatch; 7924 // In this case, the specifier is wrong and should be changed to match 7925 // the argument. 7926 EmitFormatDiagnostic(S.PDiag(Diag) 7927 << AT.getRepresentativeTypeName(S.Context) 7928 << IntendedTy << IsEnum << E->getSourceRange(), 7929 E->getBeginLoc(), 7930 /*IsStringLocation*/ false, SpecRange, 7931 FixItHint::CreateReplacement(SpecRange, os.str())); 7932 } else { 7933 // The canonical type for formatting this value is different from the 7934 // actual type of the expression. (This occurs, for example, with Darwin's 7935 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 7936 // should be printed as 'long' for 64-bit compatibility.) 7937 // Rather than emitting a normal format/argument mismatch, we want to 7938 // add a cast to the recommended type (and correct the format string 7939 // if necessary). 7940 SmallString<16> CastBuf; 7941 llvm::raw_svector_ostream CastFix(CastBuf); 7942 CastFix << "("; 7943 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 7944 CastFix << ")"; 7945 7946 SmallVector<FixItHint,4> Hints; 7947 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 7948 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 7949 7950 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 7951 // If there's already a cast present, just replace it. 7952 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 7953 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 7954 7955 } else if (!requiresParensToAddCast(E)) { 7956 // If the expression has high enough precedence, 7957 // just write the C-style cast. 7958 Hints.push_back( 7959 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 7960 } else { 7961 // Otherwise, add parens around the expression as well as the cast. 7962 CastFix << "("; 7963 Hints.push_back( 7964 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 7965 7966 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 7967 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 7968 } 7969 7970 if (ShouldNotPrintDirectly) { 7971 // The expression has a type that should not be printed directly. 7972 // We extract the name from the typedef because we don't want to show 7973 // the underlying type in the diagnostic. 7974 StringRef Name; 7975 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 7976 Name = TypedefTy->getDecl()->getName(); 7977 else 7978 Name = CastTyName; 7979 unsigned Diag = Pedantic 7980 ? diag::warn_format_argument_needs_cast_pedantic 7981 : diag::warn_format_argument_needs_cast; 7982 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 7983 << E->getSourceRange(), 7984 E->getBeginLoc(), /*IsStringLocation=*/false, 7985 SpecRange, Hints); 7986 } else { 7987 // In this case, the expression could be printed using a different 7988 // specifier, but we've decided that the specifier is probably correct 7989 // and we should cast instead. Just use the normal warning message. 7990 EmitFormatDiagnostic( 7991 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7992 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 7993 << E->getSourceRange(), 7994 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 7995 } 7996 } 7997 } else { 7998 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 7999 SpecifierLen); 8000 // Since the warning for passing non-POD types to variadic functions 8001 // was deferred until now, we emit a warning for non-POD 8002 // arguments here. 8003 switch (S.isValidVarArgType(ExprTy)) { 8004 case Sema::VAK_Valid: 8005 case Sema::VAK_ValidInCXX11: { 8006 unsigned Diag = 8007 Pedantic 8008 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8009 : diag::warn_format_conversion_argument_type_mismatch; 8010 8011 EmitFormatDiagnostic( 8012 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8013 << IsEnum << CSR << E->getSourceRange(), 8014 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8015 break; 8016 } 8017 case Sema::VAK_Undefined: 8018 case Sema::VAK_MSVCUndefined: 8019 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8020 << S.getLangOpts().CPlusPlus11 << ExprTy 8021 << CallType 8022 << AT.getRepresentativeTypeName(S.Context) << CSR 8023 << E->getSourceRange(), 8024 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8025 checkForCStrMembers(AT, E); 8026 break; 8027 8028 case Sema::VAK_Invalid: 8029 if (ExprTy->isObjCObjectType()) 8030 EmitFormatDiagnostic( 8031 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8032 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8033 << AT.getRepresentativeTypeName(S.Context) << CSR 8034 << E->getSourceRange(), 8035 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8036 else 8037 // FIXME: If this is an initializer list, suggest removing the braces 8038 // or inserting a cast to the target type. 8039 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8040 << isa<InitListExpr>(E) << ExprTy << CallType 8041 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8042 break; 8043 } 8044 8045 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8046 "format string specifier index out of range"); 8047 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8048 } 8049 8050 return true; 8051 } 8052 8053 //===--- CHECK: Scanf format string checking ------------------------------===// 8054 8055 namespace { 8056 8057 class CheckScanfHandler : public CheckFormatHandler { 8058 public: 8059 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8060 const Expr *origFormatExpr, Sema::FormatStringType type, 8061 unsigned firstDataArg, unsigned numDataArgs, 8062 const char *beg, bool hasVAListArg, 8063 ArrayRef<const Expr *> Args, unsigned formatIdx, 8064 bool inFunctionCall, Sema::VariadicCallType CallType, 8065 llvm::SmallBitVector &CheckedVarArgs, 8066 UncoveredArgHandler &UncoveredArg) 8067 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8068 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8069 inFunctionCall, CallType, CheckedVarArgs, 8070 UncoveredArg) {} 8071 8072 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8073 const char *startSpecifier, 8074 unsigned specifierLen) override; 8075 8076 bool HandleInvalidScanfConversionSpecifier( 8077 const analyze_scanf::ScanfSpecifier &FS, 8078 const char *startSpecifier, 8079 unsigned specifierLen) override; 8080 8081 void HandleIncompleteScanList(const char *start, const char *end) override; 8082 }; 8083 8084 } // namespace 8085 8086 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8087 const char *end) { 8088 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8089 getLocationOfByte(end), /*IsStringLocation*/true, 8090 getSpecifierRange(start, end - start)); 8091 } 8092 8093 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8094 const analyze_scanf::ScanfSpecifier &FS, 8095 const char *startSpecifier, 8096 unsigned specifierLen) { 8097 const analyze_scanf::ScanfConversionSpecifier &CS = 8098 FS.getConversionSpecifier(); 8099 8100 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8101 getLocationOfByte(CS.getStart()), 8102 startSpecifier, specifierLen, 8103 CS.getStart(), CS.getLength()); 8104 } 8105 8106 bool CheckScanfHandler::HandleScanfSpecifier( 8107 const analyze_scanf::ScanfSpecifier &FS, 8108 const char *startSpecifier, 8109 unsigned specifierLen) { 8110 using namespace analyze_scanf; 8111 using namespace analyze_format_string; 8112 8113 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8114 8115 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8116 // be used to decide if we are using positional arguments consistently. 8117 if (FS.consumesDataArgument()) { 8118 if (atFirstArg) { 8119 atFirstArg = false; 8120 usesPositionalArgs = FS.usesPositionalArg(); 8121 } 8122 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8123 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8124 startSpecifier, specifierLen); 8125 return false; 8126 } 8127 } 8128 8129 // Check if the field with is non-zero. 8130 const OptionalAmount &Amt = FS.getFieldWidth(); 8131 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8132 if (Amt.getConstantAmount() == 0) { 8133 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8134 Amt.getConstantLength()); 8135 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8136 getLocationOfByte(Amt.getStart()), 8137 /*IsStringLocation*/true, R, 8138 FixItHint::CreateRemoval(R)); 8139 } 8140 } 8141 8142 if (!FS.consumesDataArgument()) { 8143 // FIXME: Technically specifying a precision or field width here 8144 // makes no sense. Worth issuing a warning at some point. 8145 return true; 8146 } 8147 8148 // Consume the argument. 8149 unsigned argIndex = FS.getArgIndex(); 8150 if (argIndex < NumDataArgs) { 8151 // The check to see if the argIndex is valid will come later. 8152 // We set the bit here because we may exit early from this 8153 // function if we encounter some other error. 8154 CoveredArgs.set(argIndex); 8155 } 8156 8157 // Check the length modifier is valid with the given conversion specifier. 8158 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 8159 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8160 diag::warn_format_nonsensical_length); 8161 else if (!FS.hasStandardLengthModifier()) 8162 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8163 else if (!FS.hasStandardLengthConversionCombination()) 8164 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8165 diag::warn_format_non_standard_conversion_spec); 8166 8167 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8168 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8169 8170 // The remaining checks depend on the data arguments. 8171 if (HasVAListArg) 8172 return true; 8173 8174 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8175 return false; 8176 8177 // Check that the argument type matches the format specifier. 8178 const Expr *Ex = getDataArg(argIndex); 8179 if (!Ex) 8180 return true; 8181 8182 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8183 8184 if (!AT.isValid()) { 8185 return true; 8186 } 8187 8188 analyze_format_string::ArgType::MatchKind Match = 8189 AT.matchesType(S.Context, Ex->getType()); 8190 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8191 if (Match == analyze_format_string::ArgType::Match) 8192 return true; 8193 8194 ScanfSpecifier fixedFS = FS; 8195 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8196 S.getLangOpts(), S.Context); 8197 8198 unsigned Diag = 8199 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8200 : diag::warn_format_conversion_argument_type_mismatch; 8201 8202 if (Success) { 8203 // Get the fix string from the fixed format specifier. 8204 SmallString<128> buf; 8205 llvm::raw_svector_ostream os(buf); 8206 fixedFS.toString(os); 8207 8208 EmitFormatDiagnostic( 8209 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8210 << Ex->getType() << false << Ex->getSourceRange(), 8211 Ex->getBeginLoc(), 8212 /*IsStringLocation*/ false, 8213 getSpecifierRange(startSpecifier, specifierLen), 8214 FixItHint::CreateReplacement( 8215 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8216 } else { 8217 EmitFormatDiagnostic(S.PDiag(Diag) 8218 << AT.getRepresentativeTypeName(S.Context) 8219 << Ex->getType() << false << Ex->getSourceRange(), 8220 Ex->getBeginLoc(), 8221 /*IsStringLocation*/ false, 8222 getSpecifierRange(startSpecifier, specifierLen)); 8223 } 8224 8225 return true; 8226 } 8227 8228 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8229 const Expr *OrigFormatExpr, 8230 ArrayRef<const Expr *> Args, 8231 bool HasVAListArg, unsigned format_idx, 8232 unsigned firstDataArg, 8233 Sema::FormatStringType Type, 8234 bool inFunctionCall, 8235 Sema::VariadicCallType CallType, 8236 llvm::SmallBitVector &CheckedVarArgs, 8237 UncoveredArgHandler &UncoveredArg) { 8238 // CHECK: is the format string a wide literal? 8239 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8240 CheckFormatHandler::EmitFormatDiagnostic( 8241 S, inFunctionCall, Args[format_idx], 8242 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8243 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8244 return; 8245 } 8246 8247 // Str - The format string. NOTE: this is NOT null-terminated! 8248 StringRef StrRef = FExpr->getString(); 8249 const char *Str = StrRef.data(); 8250 // Account for cases where the string literal is truncated in a declaration. 8251 const ConstantArrayType *T = 8252 S.Context.getAsConstantArrayType(FExpr->getType()); 8253 assert(T && "String literal not of constant array type!"); 8254 size_t TypeSize = T->getSize().getZExtValue(); 8255 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8256 const unsigned numDataArgs = Args.size() - firstDataArg; 8257 8258 // Emit a warning if the string literal is truncated and does not contain an 8259 // embedded null character. 8260 if (TypeSize <= StrRef.size() && 8261 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8262 CheckFormatHandler::EmitFormatDiagnostic( 8263 S, inFunctionCall, Args[format_idx], 8264 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8265 FExpr->getBeginLoc(), 8266 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8267 return; 8268 } 8269 8270 // CHECK: empty format string? 8271 if (StrLen == 0 && numDataArgs > 0) { 8272 CheckFormatHandler::EmitFormatDiagnostic( 8273 S, inFunctionCall, Args[format_idx], 8274 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8275 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8276 return; 8277 } 8278 8279 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8280 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8281 Type == Sema::FST_OSTrace) { 8282 CheckPrintfHandler H( 8283 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8284 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8285 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8286 CheckedVarArgs, UncoveredArg); 8287 8288 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8289 S.getLangOpts(), 8290 S.Context.getTargetInfo(), 8291 Type == Sema::FST_FreeBSDKPrintf)) 8292 H.DoneProcessing(); 8293 } else if (Type == Sema::FST_Scanf) { 8294 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8295 numDataArgs, Str, HasVAListArg, Args, format_idx, 8296 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8297 8298 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8299 S.getLangOpts(), 8300 S.Context.getTargetInfo())) 8301 H.DoneProcessing(); 8302 } // TODO: handle other formats 8303 } 8304 8305 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8306 // Str - The format string. NOTE: this is NOT null-terminated! 8307 StringRef StrRef = FExpr->getString(); 8308 const char *Str = StrRef.data(); 8309 // Account for cases where the string literal is truncated in a declaration. 8310 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8311 assert(T && "String literal not of constant array type!"); 8312 size_t TypeSize = T->getSize().getZExtValue(); 8313 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8314 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8315 getLangOpts(), 8316 Context.getTargetInfo()); 8317 } 8318 8319 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8320 8321 // Returns the related absolute value function that is larger, of 0 if one 8322 // does not exist. 8323 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8324 switch (AbsFunction) { 8325 default: 8326 return 0; 8327 8328 case Builtin::BI__builtin_abs: 8329 return Builtin::BI__builtin_labs; 8330 case Builtin::BI__builtin_labs: 8331 return Builtin::BI__builtin_llabs; 8332 case Builtin::BI__builtin_llabs: 8333 return 0; 8334 8335 case Builtin::BI__builtin_fabsf: 8336 return Builtin::BI__builtin_fabs; 8337 case Builtin::BI__builtin_fabs: 8338 return Builtin::BI__builtin_fabsl; 8339 case Builtin::BI__builtin_fabsl: 8340 return 0; 8341 8342 case Builtin::BI__builtin_cabsf: 8343 return Builtin::BI__builtin_cabs; 8344 case Builtin::BI__builtin_cabs: 8345 return Builtin::BI__builtin_cabsl; 8346 case Builtin::BI__builtin_cabsl: 8347 return 0; 8348 8349 case Builtin::BIabs: 8350 return Builtin::BIlabs; 8351 case Builtin::BIlabs: 8352 return Builtin::BIllabs; 8353 case Builtin::BIllabs: 8354 return 0; 8355 8356 case Builtin::BIfabsf: 8357 return Builtin::BIfabs; 8358 case Builtin::BIfabs: 8359 return Builtin::BIfabsl; 8360 case Builtin::BIfabsl: 8361 return 0; 8362 8363 case Builtin::BIcabsf: 8364 return Builtin::BIcabs; 8365 case Builtin::BIcabs: 8366 return Builtin::BIcabsl; 8367 case Builtin::BIcabsl: 8368 return 0; 8369 } 8370 } 8371 8372 // Returns the argument type of the absolute value function. 8373 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8374 unsigned AbsType) { 8375 if (AbsType == 0) 8376 return QualType(); 8377 8378 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8379 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8380 if (Error != ASTContext::GE_None) 8381 return QualType(); 8382 8383 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8384 if (!FT) 8385 return QualType(); 8386 8387 if (FT->getNumParams() != 1) 8388 return QualType(); 8389 8390 return FT->getParamType(0); 8391 } 8392 8393 // Returns the best absolute value function, or zero, based on type and 8394 // current absolute value function. 8395 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8396 unsigned AbsFunctionKind) { 8397 unsigned BestKind = 0; 8398 uint64_t ArgSize = Context.getTypeSize(ArgType); 8399 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8400 Kind = getLargerAbsoluteValueFunction(Kind)) { 8401 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8402 if (Context.getTypeSize(ParamType) >= ArgSize) { 8403 if (BestKind == 0) 8404 BestKind = Kind; 8405 else if (Context.hasSameType(ParamType, ArgType)) { 8406 BestKind = Kind; 8407 break; 8408 } 8409 } 8410 } 8411 return BestKind; 8412 } 8413 8414 enum AbsoluteValueKind { 8415 AVK_Integer, 8416 AVK_Floating, 8417 AVK_Complex 8418 }; 8419 8420 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8421 if (T->isIntegralOrEnumerationType()) 8422 return AVK_Integer; 8423 if (T->isRealFloatingType()) 8424 return AVK_Floating; 8425 if (T->isAnyComplexType()) 8426 return AVK_Complex; 8427 8428 llvm_unreachable("Type not integer, floating, or complex"); 8429 } 8430 8431 // Changes the absolute value function to a different type. Preserves whether 8432 // the function is a builtin. 8433 static unsigned changeAbsFunction(unsigned AbsKind, 8434 AbsoluteValueKind ValueKind) { 8435 switch (ValueKind) { 8436 case AVK_Integer: 8437 switch (AbsKind) { 8438 default: 8439 return 0; 8440 case Builtin::BI__builtin_fabsf: 8441 case Builtin::BI__builtin_fabs: 8442 case Builtin::BI__builtin_fabsl: 8443 case Builtin::BI__builtin_cabsf: 8444 case Builtin::BI__builtin_cabs: 8445 case Builtin::BI__builtin_cabsl: 8446 return Builtin::BI__builtin_abs; 8447 case Builtin::BIfabsf: 8448 case Builtin::BIfabs: 8449 case Builtin::BIfabsl: 8450 case Builtin::BIcabsf: 8451 case Builtin::BIcabs: 8452 case Builtin::BIcabsl: 8453 return Builtin::BIabs; 8454 } 8455 case AVK_Floating: 8456 switch (AbsKind) { 8457 default: 8458 return 0; 8459 case Builtin::BI__builtin_abs: 8460 case Builtin::BI__builtin_labs: 8461 case Builtin::BI__builtin_llabs: 8462 case Builtin::BI__builtin_cabsf: 8463 case Builtin::BI__builtin_cabs: 8464 case Builtin::BI__builtin_cabsl: 8465 return Builtin::BI__builtin_fabsf; 8466 case Builtin::BIabs: 8467 case Builtin::BIlabs: 8468 case Builtin::BIllabs: 8469 case Builtin::BIcabsf: 8470 case Builtin::BIcabs: 8471 case Builtin::BIcabsl: 8472 return Builtin::BIfabsf; 8473 } 8474 case AVK_Complex: 8475 switch (AbsKind) { 8476 default: 8477 return 0; 8478 case Builtin::BI__builtin_abs: 8479 case Builtin::BI__builtin_labs: 8480 case Builtin::BI__builtin_llabs: 8481 case Builtin::BI__builtin_fabsf: 8482 case Builtin::BI__builtin_fabs: 8483 case Builtin::BI__builtin_fabsl: 8484 return Builtin::BI__builtin_cabsf; 8485 case Builtin::BIabs: 8486 case Builtin::BIlabs: 8487 case Builtin::BIllabs: 8488 case Builtin::BIfabsf: 8489 case Builtin::BIfabs: 8490 case Builtin::BIfabsl: 8491 return Builtin::BIcabsf; 8492 } 8493 } 8494 llvm_unreachable("Unable to convert function"); 8495 } 8496 8497 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8498 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8499 if (!FnInfo) 8500 return 0; 8501 8502 switch (FDecl->getBuiltinID()) { 8503 default: 8504 return 0; 8505 case Builtin::BI__builtin_abs: 8506 case Builtin::BI__builtin_fabs: 8507 case Builtin::BI__builtin_fabsf: 8508 case Builtin::BI__builtin_fabsl: 8509 case Builtin::BI__builtin_labs: 8510 case Builtin::BI__builtin_llabs: 8511 case Builtin::BI__builtin_cabs: 8512 case Builtin::BI__builtin_cabsf: 8513 case Builtin::BI__builtin_cabsl: 8514 case Builtin::BIabs: 8515 case Builtin::BIlabs: 8516 case Builtin::BIllabs: 8517 case Builtin::BIfabs: 8518 case Builtin::BIfabsf: 8519 case Builtin::BIfabsl: 8520 case Builtin::BIcabs: 8521 case Builtin::BIcabsf: 8522 case Builtin::BIcabsl: 8523 return FDecl->getBuiltinID(); 8524 } 8525 llvm_unreachable("Unknown Builtin type"); 8526 } 8527 8528 // If the replacement is valid, emit a note with replacement function. 8529 // Additionally, suggest including the proper header if not already included. 8530 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8531 unsigned AbsKind, QualType ArgType) { 8532 bool EmitHeaderHint = true; 8533 const char *HeaderName = nullptr; 8534 const char *FunctionName = nullptr; 8535 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8536 FunctionName = "std::abs"; 8537 if (ArgType->isIntegralOrEnumerationType()) { 8538 HeaderName = "cstdlib"; 8539 } else if (ArgType->isRealFloatingType()) { 8540 HeaderName = "cmath"; 8541 } else { 8542 llvm_unreachable("Invalid Type"); 8543 } 8544 8545 // Lookup all std::abs 8546 if (NamespaceDecl *Std = S.getStdNamespace()) { 8547 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8548 R.suppressDiagnostics(); 8549 S.LookupQualifiedName(R, Std); 8550 8551 for (const auto *I : R) { 8552 const FunctionDecl *FDecl = nullptr; 8553 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8554 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8555 } else { 8556 FDecl = dyn_cast<FunctionDecl>(I); 8557 } 8558 if (!FDecl) 8559 continue; 8560 8561 // Found std::abs(), check that they are the right ones. 8562 if (FDecl->getNumParams() != 1) 8563 continue; 8564 8565 // Check that the parameter type can handle the argument. 8566 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8567 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8568 S.Context.getTypeSize(ArgType) <= 8569 S.Context.getTypeSize(ParamType)) { 8570 // Found a function, don't need the header hint. 8571 EmitHeaderHint = false; 8572 break; 8573 } 8574 } 8575 } 8576 } else { 8577 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8578 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8579 8580 if (HeaderName) { 8581 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8582 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8583 R.suppressDiagnostics(); 8584 S.LookupName(R, S.getCurScope()); 8585 8586 if (R.isSingleResult()) { 8587 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8588 if (FD && FD->getBuiltinID() == AbsKind) { 8589 EmitHeaderHint = false; 8590 } else { 8591 return; 8592 } 8593 } else if (!R.empty()) { 8594 return; 8595 } 8596 } 8597 } 8598 8599 S.Diag(Loc, diag::note_replace_abs_function) 8600 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8601 8602 if (!HeaderName) 8603 return; 8604 8605 if (!EmitHeaderHint) 8606 return; 8607 8608 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 8609 << FunctionName; 8610 } 8611 8612 template <std::size_t StrLen> 8613 static bool IsStdFunction(const FunctionDecl *FDecl, 8614 const char (&Str)[StrLen]) { 8615 if (!FDecl) 8616 return false; 8617 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 8618 return false; 8619 if (!FDecl->isInStdNamespace()) 8620 return false; 8621 8622 return true; 8623 } 8624 8625 // Warn when using the wrong abs() function. 8626 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 8627 const FunctionDecl *FDecl) { 8628 if (Call->getNumArgs() != 1) 8629 return; 8630 8631 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 8632 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 8633 if (AbsKind == 0 && !IsStdAbs) 8634 return; 8635 8636 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8637 QualType ParamType = Call->getArg(0)->getType(); 8638 8639 // Unsigned types cannot be negative. Suggest removing the absolute value 8640 // function call. 8641 if (ArgType->isUnsignedIntegerType()) { 8642 const char *FunctionName = 8643 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 8644 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 8645 Diag(Call->getExprLoc(), diag::note_remove_abs) 8646 << FunctionName 8647 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 8648 return; 8649 } 8650 8651 // Taking the absolute value of a pointer is very suspicious, they probably 8652 // wanted to index into an array, dereference a pointer, call a function, etc. 8653 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 8654 unsigned DiagType = 0; 8655 if (ArgType->isFunctionType()) 8656 DiagType = 1; 8657 else if (ArgType->isArrayType()) 8658 DiagType = 2; 8659 8660 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 8661 return; 8662 } 8663 8664 // std::abs has overloads which prevent most of the absolute value problems 8665 // from occurring. 8666 if (IsStdAbs) 8667 return; 8668 8669 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 8670 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 8671 8672 // The argument and parameter are the same kind. Check if they are the right 8673 // size. 8674 if (ArgValueKind == ParamValueKind) { 8675 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 8676 return; 8677 8678 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 8679 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 8680 << FDecl << ArgType << ParamType; 8681 8682 if (NewAbsKind == 0) 8683 return; 8684 8685 emitReplacement(*this, Call->getExprLoc(), 8686 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8687 return; 8688 } 8689 8690 // ArgValueKind != ParamValueKind 8691 // The wrong type of absolute value function was used. Attempt to find the 8692 // proper one. 8693 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 8694 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 8695 if (NewAbsKind == 0) 8696 return; 8697 8698 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 8699 << FDecl << ParamValueKind << ArgValueKind; 8700 8701 emitReplacement(*this, Call->getExprLoc(), 8702 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8703 } 8704 8705 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 8706 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 8707 const FunctionDecl *FDecl) { 8708 if (!Call || !FDecl) return; 8709 8710 // Ignore template specializations and macros. 8711 if (inTemplateInstantiation()) return; 8712 if (Call->getExprLoc().isMacroID()) return; 8713 8714 // Only care about the one template argument, two function parameter std::max 8715 if (Call->getNumArgs() != 2) return; 8716 if (!IsStdFunction(FDecl, "max")) return; 8717 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 8718 if (!ArgList) return; 8719 if (ArgList->size() != 1) return; 8720 8721 // Check that template type argument is unsigned integer. 8722 const auto& TA = ArgList->get(0); 8723 if (TA.getKind() != TemplateArgument::Type) return; 8724 QualType ArgType = TA.getAsType(); 8725 if (!ArgType->isUnsignedIntegerType()) return; 8726 8727 // See if either argument is a literal zero. 8728 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 8729 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 8730 if (!MTE) return false; 8731 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 8732 if (!Num) return false; 8733 if (Num->getValue() != 0) return false; 8734 return true; 8735 }; 8736 8737 const Expr *FirstArg = Call->getArg(0); 8738 const Expr *SecondArg = Call->getArg(1); 8739 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 8740 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 8741 8742 // Only warn when exactly one argument is zero. 8743 if (IsFirstArgZero == IsSecondArgZero) return; 8744 8745 SourceRange FirstRange = FirstArg->getSourceRange(); 8746 SourceRange SecondRange = SecondArg->getSourceRange(); 8747 8748 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 8749 8750 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 8751 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 8752 8753 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 8754 SourceRange RemovalRange; 8755 if (IsFirstArgZero) { 8756 RemovalRange = SourceRange(FirstRange.getBegin(), 8757 SecondRange.getBegin().getLocWithOffset(-1)); 8758 } else { 8759 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 8760 SecondRange.getEnd()); 8761 } 8762 8763 Diag(Call->getExprLoc(), diag::note_remove_max_call) 8764 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 8765 << FixItHint::CreateRemoval(RemovalRange); 8766 } 8767 8768 //===--- CHECK: Standard memory functions ---------------------------------===// 8769 8770 /// Takes the expression passed to the size_t parameter of functions 8771 /// such as memcmp, strncat, etc and warns if it's a comparison. 8772 /// 8773 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 8774 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 8775 IdentifierInfo *FnName, 8776 SourceLocation FnLoc, 8777 SourceLocation RParenLoc) { 8778 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 8779 if (!Size) 8780 return false; 8781 8782 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 8783 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 8784 return false; 8785 8786 SourceRange SizeRange = Size->getSourceRange(); 8787 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 8788 << SizeRange << FnName; 8789 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 8790 << FnName 8791 << FixItHint::CreateInsertion( 8792 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 8793 << FixItHint::CreateRemoval(RParenLoc); 8794 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 8795 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 8796 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 8797 ")"); 8798 8799 return true; 8800 } 8801 8802 /// Determine whether the given type is or contains a dynamic class type 8803 /// (e.g., whether it has a vtable). 8804 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 8805 bool &IsContained) { 8806 // Look through array types while ignoring qualifiers. 8807 const Type *Ty = T->getBaseElementTypeUnsafe(); 8808 IsContained = false; 8809 8810 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 8811 RD = RD ? RD->getDefinition() : nullptr; 8812 if (!RD || RD->isInvalidDecl()) 8813 return nullptr; 8814 8815 if (RD->isDynamicClass()) 8816 return RD; 8817 8818 // Check all the fields. If any bases were dynamic, the class is dynamic. 8819 // It's impossible for a class to transitively contain itself by value, so 8820 // infinite recursion is impossible. 8821 for (auto *FD : RD->fields()) { 8822 bool SubContained; 8823 if (const CXXRecordDecl *ContainedRD = 8824 getContainedDynamicClass(FD->getType(), SubContained)) { 8825 IsContained = true; 8826 return ContainedRD; 8827 } 8828 } 8829 8830 return nullptr; 8831 } 8832 8833 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 8834 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 8835 if (Unary->getKind() == UETT_SizeOf) 8836 return Unary; 8837 return nullptr; 8838 } 8839 8840 /// If E is a sizeof expression, returns its argument expression, 8841 /// otherwise returns NULL. 8842 static const Expr *getSizeOfExprArg(const Expr *E) { 8843 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8844 if (!SizeOf->isArgumentType()) 8845 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 8846 return nullptr; 8847 } 8848 8849 /// If E is a sizeof expression, returns its argument type. 8850 static QualType getSizeOfArgType(const Expr *E) { 8851 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8852 return SizeOf->getTypeOfArgument(); 8853 return QualType(); 8854 } 8855 8856 namespace { 8857 8858 struct SearchNonTrivialToInitializeField 8859 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 8860 using Super = 8861 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 8862 8863 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 8864 8865 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 8866 SourceLocation SL) { 8867 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8868 asDerived().visitArray(PDIK, AT, SL); 8869 return; 8870 } 8871 8872 Super::visitWithKind(PDIK, FT, SL); 8873 } 8874 8875 void visitARCStrong(QualType FT, SourceLocation SL) { 8876 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8877 } 8878 void visitARCWeak(QualType FT, SourceLocation SL) { 8879 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8880 } 8881 void visitStruct(QualType FT, SourceLocation SL) { 8882 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8883 visit(FD->getType(), FD->getLocation()); 8884 } 8885 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 8886 const ArrayType *AT, SourceLocation SL) { 8887 visit(getContext().getBaseElementType(AT), SL); 8888 } 8889 void visitTrivial(QualType FT, SourceLocation SL) {} 8890 8891 static void diag(QualType RT, const Expr *E, Sema &S) { 8892 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 8893 } 8894 8895 ASTContext &getContext() { return S.getASTContext(); } 8896 8897 const Expr *E; 8898 Sema &S; 8899 }; 8900 8901 struct SearchNonTrivialToCopyField 8902 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 8903 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 8904 8905 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 8906 8907 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 8908 SourceLocation SL) { 8909 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8910 asDerived().visitArray(PCK, AT, SL); 8911 return; 8912 } 8913 8914 Super::visitWithKind(PCK, FT, SL); 8915 } 8916 8917 void visitARCStrong(QualType FT, SourceLocation SL) { 8918 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8919 } 8920 void visitARCWeak(QualType FT, SourceLocation SL) { 8921 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8922 } 8923 void visitStruct(QualType FT, SourceLocation SL) { 8924 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8925 visit(FD->getType(), FD->getLocation()); 8926 } 8927 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 8928 SourceLocation SL) { 8929 visit(getContext().getBaseElementType(AT), SL); 8930 } 8931 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 8932 SourceLocation SL) {} 8933 void visitTrivial(QualType FT, SourceLocation SL) {} 8934 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 8935 8936 static void diag(QualType RT, const Expr *E, Sema &S) { 8937 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 8938 } 8939 8940 ASTContext &getContext() { return S.getASTContext(); } 8941 8942 const Expr *E; 8943 Sema &S; 8944 }; 8945 8946 } 8947 8948 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 8949 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 8950 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 8951 8952 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 8953 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 8954 return false; 8955 8956 return doesExprLikelyComputeSize(BO->getLHS()) || 8957 doesExprLikelyComputeSize(BO->getRHS()); 8958 } 8959 8960 return getAsSizeOfExpr(SizeofExpr) != nullptr; 8961 } 8962 8963 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 8964 /// 8965 /// \code 8966 /// #define MACRO 0 8967 /// foo(MACRO); 8968 /// foo(0); 8969 /// \endcode 8970 /// 8971 /// This should return true for the first call to foo, but not for the second 8972 /// (regardless of whether foo is a macro or function). 8973 static bool isArgumentExpandedFromMacro(SourceManager &SM, 8974 SourceLocation CallLoc, 8975 SourceLocation ArgLoc) { 8976 if (!CallLoc.isMacroID()) 8977 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 8978 8979 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 8980 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 8981 } 8982 8983 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 8984 /// last two arguments transposed. 8985 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 8986 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 8987 return; 8988 8989 const Expr *SizeArg = 8990 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 8991 8992 auto isLiteralZero = [](const Expr *E) { 8993 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 8994 }; 8995 8996 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 8997 SourceLocation CallLoc = Call->getRParenLoc(); 8998 SourceManager &SM = S.getSourceManager(); 8999 if (isLiteralZero(SizeArg) && 9000 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9001 9002 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9003 9004 // Some platforms #define bzero to __builtin_memset. See if this is the 9005 // case, and if so, emit a better diagnostic. 9006 if (BId == Builtin::BIbzero || 9007 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9008 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9009 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9010 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9011 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9012 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9013 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9014 } 9015 return; 9016 } 9017 9018 // If the second argument to a memset is a sizeof expression and the third 9019 // isn't, this is also likely an error. This should catch 9020 // 'memset(buf, sizeof(buf), 0xff)'. 9021 if (BId == Builtin::BImemset && 9022 doesExprLikelyComputeSize(Call->getArg(1)) && 9023 !doesExprLikelyComputeSize(Call->getArg(2))) { 9024 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9025 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9026 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9027 return; 9028 } 9029 } 9030 9031 /// Check for dangerous or invalid arguments to memset(). 9032 /// 9033 /// This issues warnings on known problematic, dangerous or unspecified 9034 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9035 /// function calls. 9036 /// 9037 /// \param Call The call expression to diagnose. 9038 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9039 unsigned BId, 9040 IdentifierInfo *FnName) { 9041 assert(BId != 0); 9042 9043 // It is possible to have a non-standard definition of memset. Validate 9044 // we have enough arguments, and if not, abort further checking. 9045 unsigned ExpectedNumArgs = 9046 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9047 if (Call->getNumArgs() < ExpectedNumArgs) 9048 return; 9049 9050 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9051 BId == Builtin::BIstrndup ? 1 : 2); 9052 unsigned LenArg = 9053 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9054 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9055 9056 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9057 Call->getBeginLoc(), Call->getRParenLoc())) 9058 return; 9059 9060 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9061 CheckMemaccessSize(*this, BId, Call); 9062 9063 // We have special checking when the length is a sizeof expression. 9064 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9065 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9066 llvm::FoldingSetNodeID SizeOfArgID; 9067 9068 // Although widely used, 'bzero' is not a standard function. Be more strict 9069 // with the argument types before allowing diagnostics and only allow the 9070 // form bzero(ptr, sizeof(...)). 9071 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9072 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9073 return; 9074 9075 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9076 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9077 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9078 9079 QualType DestTy = Dest->getType(); 9080 QualType PointeeTy; 9081 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9082 PointeeTy = DestPtrTy->getPointeeType(); 9083 9084 // Never warn about void type pointers. This can be used to suppress 9085 // false positives. 9086 if (PointeeTy->isVoidType()) 9087 continue; 9088 9089 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9090 // actually comparing the expressions for equality. Because computing the 9091 // expression IDs can be expensive, we only do this if the diagnostic is 9092 // enabled. 9093 if (SizeOfArg && 9094 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9095 SizeOfArg->getExprLoc())) { 9096 // We only compute IDs for expressions if the warning is enabled, and 9097 // cache the sizeof arg's ID. 9098 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9099 SizeOfArg->Profile(SizeOfArgID, Context, true); 9100 llvm::FoldingSetNodeID DestID; 9101 Dest->Profile(DestID, Context, true); 9102 if (DestID == SizeOfArgID) { 9103 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9104 // over sizeof(src) as well. 9105 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9106 StringRef ReadableName = FnName->getName(); 9107 9108 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9109 if (UnaryOp->getOpcode() == UO_AddrOf) 9110 ActionIdx = 1; // If its an address-of operator, just remove it. 9111 if (!PointeeTy->isIncompleteType() && 9112 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9113 ActionIdx = 2; // If the pointee's size is sizeof(char), 9114 // suggest an explicit length. 9115 9116 // If the function is defined as a builtin macro, do not show macro 9117 // expansion. 9118 SourceLocation SL = SizeOfArg->getExprLoc(); 9119 SourceRange DSR = Dest->getSourceRange(); 9120 SourceRange SSR = SizeOfArg->getSourceRange(); 9121 SourceManager &SM = getSourceManager(); 9122 9123 if (SM.isMacroArgExpansion(SL)) { 9124 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9125 SL = SM.getSpellingLoc(SL); 9126 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9127 SM.getSpellingLoc(DSR.getEnd())); 9128 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9129 SM.getSpellingLoc(SSR.getEnd())); 9130 } 9131 9132 DiagRuntimeBehavior(SL, SizeOfArg, 9133 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9134 << ReadableName 9135 << PointeeTy 9136 << DestTy 9137 << DSR 9138 << SSR); 9139 DiagRuntimeBehavior(SL, SizeOfArg, 9140 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9141 << ActionIdx 9142 << SSR); 9143 9144 break; 9145 } 9146 } 9147 9148 // Also check for cases where the sizeof argument is the exact same 9149 // type as the memory argument, and where it points to a user-defined 9150 // record type. 9151 if (SizeOfArgTy != QualType()) { 9152 if (PointeeTy->isRecordType() && 9153 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9154 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9155 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9156 << FnName << SizeOfArgTy << ArgIdx 9157 << PointeeTy << Dest->getSourceRange() 9158 << LenExpr->getSourceRange()); 9159 break; 9160 } 9161 } 9162 } else if (DestTy->isArrayType()) { 9163 PointeeTy = DestTy; 9164 } 9165 9166 if (PointeeTy == QualType()) 9167 continue; 9168 9169 // Always complain about dynamic classes. 9170 bool IsContained; 9171 if (const CXXRecordDecl *ContainedRD = 9172 getContainedDynamicClass(PointeeTy, IsContained)) { 9173 9174 unsigned OperationType = 0; 9175 // "overwritten" if we're warning about the destination for any call 9176 // but memcmp; otherwise a verb appropriate to the call. 9177 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 9178 if (BId == Builtin::BImemcpy) 9179 OperationType = 1; 9180 else if(BId == Builtin::BImemmove) 9181 OperationType = 2; 9182 else if (BId == Builtin::BImemcmp) 9183 OperationType = 3; 9184 } 9185 9186 DiagRuntimeBehavior( 9187 Dest->getExprLoc(), Dest, 9188 PDiag(diag::warn_dyn_class_memaccess) 9189 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 9190 << FnName << IsContained << ContainedRD << OperationType 9191 << Call->getCallee()->getSourceRange()); 9192 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9193 BId != Builtin::BImemset) 9194 DiagRuntimeBehavior( 9195 Dest->getExprLoc(), Dest, 9196 PDiag(diag::warn_arc_object_memaccess) 9197 << ArgIdx << FnName << PointeeTy 9198 << Call->getCallee()->getSourceRange()); 9199 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9200 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9201 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9202 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9203 PDiag(diag::warn_cstruct_memaccess) 9204 << ArgIdx << FnName << PointeeTy << 0); 9205 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9206 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9207 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9208 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9209 PDiag(diag::warn_cstruct_memaccess) 9210 << ArgIdx << FnName << PointeeTy << 1); 9211 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9212 } else { 9213 continue; 9214 } 9215 } else 9216 continue; 9217 9218 DiagRuntimeBehavior( 9219 Dest->getExprLoc(), Dest, 9220 PDiag(diag::note_bad_memaccess_silence) 9221 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9222 break; 9223 } 9224 } 9225 9226 // A little helper routine: ignore addition and subtraction of integer literals. 9227 // This intentionally does not ignore all integer constant expressions because 9228 // we don't want to remove sizeof(). 9229 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9230 Ex = Ex->IgnoreParenCasts(); 9231 9232 while (true) { 9233 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9234 if (!BO || !BO->isAdditiveOp()) 9235 break; 9236 9237 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9238 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9239 9240 if (isa<IntegerLiteral>(RHS)) 9241 Ex = LHS; 9242 else if (isa<IntegerLiteral>(LHS)) 9243 Ex = RHS; 9244 else 9245 break; 9246 } 9247 9248 return Ex; 9249 } 9250 9251 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9252 ASTContext &Context) { 9253 // Only handle constant-sized or VLAs, but not flexible members. 9254 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9255 // Only issue the FIXIT for arrays of size > 1. 9256 if (CAT->getSize().getSExtValue() <= 1) 9257 return false; 9258 } else if (!Ty->isVariableArrayType()) { 9259 return false; 9260 } 9261 return true; 9262 } 9263 9264 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9265 // be the size of the source, instead of the destination. 9266 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9267 IdentifierInfo *FnName) { 9268 9269 // Don't crash if the user has the wrong number of arguments 9270 unsigned NumArgs = Call->getNumArgs(); 9271 if ((NumArgs != 3) && (NumArgs != 4)) 9272 return; 9273 9274 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9275 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9276 const Expr *CompareWithSrc = nullptr; 9277 9278 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9279 Call->getBeginLoc(), Call->getRParenLoc())) 9280 return; 9281 9282 // Look for 'strlcpy(dst, x, sizeof(x))' 9283 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9284 CompareWithSrc = Ex; 9285 else { 9286 // Look for 'strlcpy(dst, x, strlen(x))' 9287 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9288 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9289 SizeCall->getNumArgs() == 1) 9290 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9291 } 9292 } 9293 9294 if (!CompareWithSrc) 9295 return; 9296 9297 // Determine if the argument to sizeof/strlen is equal to the source 9298 // argument. In principle there's all kinds of things you could do 9299 // here, for instance creating an == expression and evaluating it with 9300 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9301 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9302 if (!SrcArgDRE) 9303 return; 9304 9305 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9306 if (!CompareWithSrcDRE || 9307 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9308 return; 9309 9310 const Expr *OriginalSizeArg = Call->getArg(2); 9311 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9312 << OriginalSizeArg->getSourceRange() << FnName; 9313 9314 // Output a FIXIT hint if the destination is an array (rather than a 9315 // pointer to an array). This could be enhanced to handle some 9316 // pointers if we know the actual size, like if DstArg is 'array+2' 9317 // we could say 'sizeof(array)-2'. 9318 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9319 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9320 return; 9321 9322 SmallString<128> sizeString; 9323 llvm::raw_svector_ostream OS(sizeString); 9324 OS << "sizeof("; 9325 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9326 OS << ")"; 9327 9328 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9329 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9330 OS.str()); 9331 } 9332 9333 /// Check if two expressions refer to the same declaration. 9334 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9335 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9336 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9337 return D1->getDecl() == D2->getDecl(); 9338 return false; 9339 } 9340 9341 static const Expr *getStrlenExprArg(const Expr *E) { 9342 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9343 const FunctionDecl *FD = CE->getDirectCallee(); 9344 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9345 return nullptr; 9346 return CE->getArg(0)->IgnoreParenCasts(); 9347 } 9348 return nullptr; 9349 } 9350 9351 // Warn on anti-patterns as the 'size' argument to strncat. 9352 // The correct size argument should look like following: 9353 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9354 void Sema::CheckStrncatArguments(const CallExpr *CE, 9355 IdentifierInfo *FnName) { 9356 // Don't crash if the user has the wrong number of arguments. 9357 if (CE->getNumArgs() < 3) 9358 return; 9359 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9360 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9361 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9362 9363 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9364 CE->getRParenLoc())) 9365 return; 9366 9367 // Identify common expressions, which are wrongly used as the size argument 9368 // to strncat and may lead to buffer overflows. 9369 unsigned PatternType = 0; 9370 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9371 // - sizeof(dst) 9372 if (referToTheSameDecl(SizeOfArg, DstArg)) 9373 PatternType = 1; 9374 // - sizeof(src) 9375 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9376 PatternType = 2; 9377 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9378 if (BE->getOpcode() == BO_Sub) { 9379 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9380 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9381 // - sizeof(dst) - strlen(dst) 9382 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9383 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9384 PatternType = 1; 9385 // - sizeof(src) - (anything) 9386 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9387 PatternType = 2; 9388 } 9389 } 9390 9391 if (PatternType == 0) 9392 return; 9393 9394 // Generate the diagnostic. 9395 SourceLocation SL = LenArg->getBeginLoc(); 9396 SourceRange SR = LenArg->getSourceRange(); 9397 SourceManager &SM = getSourceManager(); 9398 9399 // If the function is defined as a builtin macro, do not show macro expansion. 9400 if (SM.isMacroArgExpansion(SL)) { 9401 SL = SM.getSpellingLoc(SL); 9402 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9403 SM.getSpellingLoc(SR.getEnd())); 9404 } 9405 9406 // Check if the destination is an array (rather than a pointer to an array). 9407 QualType DstTy = DstArg->getType(); 9408 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9409 Context); 9410 if (!isKnownSizeArray) { 9411 if (PatternType == 1) 9412 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9413 else 9414 Diag(SL, diag::warn_strncat_src_size) << SR; 9415 return; 9416 } 9417 9418 if (PatternType == 1) 9419 Diag(SL, diag::warn_strncat_large_size) << SR; 9420 else 9421 Diag(SL, diag::warn_strncat_src_size) << SR; 9422 9423 SmallString<128> sizeString; 9424 llvm::raw_svector_ostream OS(sizeString); 9425 OS << "sizeof("; 9426 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9427 OS << ") - "; 9428 OS << "strlen("; 9429 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9430 OS << ") - 1"; 9431 9432 Diag(SL, diag::note_strncat_wrong_size) 9433 << FixItHint::CreateReplacement(SR, OS.str()); 9434 } 9435 9436 void 9437 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9438 SourceLocation ReturnLoc, 9439 bool isObjCMethod, 9440 const AttrVec *Attrs, 9441 const FunctionDecl *FD) { 9442 // Check if the return value is null but should not be. 9443 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9444 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9445 CheckNonNullExpr(*this, RetValExp)) 9446 Diag(ReturnLoc, diag::warn_null_ret) 9447 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9448 9449 // C++11 [basic.stc.dynamic.allocation]p4: 9450 // If an allocation function declared with a non-throwing 9451 // exception-specification fails to allocate storage, it shall return 9452 // a null pointer. Any other allocation function that fails to allocate 9453 // storage shall indicate failure only by throwing an exception [...] 9454 if (FD) { 9455 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9456 if (Op == OO_New || Op == OO_Array_New) { 9457 const FunctionProtoType *Proto 9458 = FD->getType()->castAs<FunctionProtoType>(); 9459 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9460 CheckNonNullExpr(*this, RetValExp)) 9461 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9462 << FD << getLangOpts().CPlusPlus11; 9463 } 9464 } 9465 } 9466 9467 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9468 9469 /// Check for comparisons of floating point operands using != and ==. 9470 /// Issue a warning if these are no self-comparisons, as they are not likely 9471 /// to do what the programmer intended. 9472 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9473 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9474 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9475 9476 // Special case: check for x == x (which is OK). 9477 // Do not emit warnings for such cases. 9478 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9479 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9480 if (DRL->getDecl() == DRR->getDecl()) 9481 return; 9482 9483 // Special case: check for comparisons against literals that can be exactly 9484 // represented by APFloat. In such cases, do not emit a warning. This 9485 // is a heuristic: often comparison against such literals are used to 9486 // detect if a value in a variable has not changed. This clearly can 9487 // lead to false negatives. 9488 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9489 if (FLL->isExact()) 9490 return; 9491 } else 9492 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9493 if (FLR->isExact()) 9494 return; 9495 9496 // Check for comparisons with builtin types. 9497 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9498 if (CL->getBuiltinCallee()) 9499 return; 9500 9501 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9502 if (CR->getBuiltinCallee()) 9503 return; 9504 9505 // Emit the diagnostic. 9506 Diag(Loc, diag::warn_floatingpoint_eq) 9507 << LHS->getSourceRange() << RHS->getSourceRange(); 9508 } 9509 9510 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9511 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9512 9513 namespace { 9514 9515 /// Structure recording the 'active' range of an integer-valued 9516 /// expression. 9517 struct IntRange { 9518 /// The number of bits active in the int. 9519 unsigned Width; 9520 9521 /// True if the int is known not to have negative values. 9522 bool NonNegative; 9523 9524 IntRange(unsigned Width, bool NonNegative) 9525 : Width(Width), NonNegative(NonNegative) {} 9526 9527 /// Returns the range of the bool type. 9528 static IntRange forBoolType() { 9529 return IntRange(1, true); 9530 } 9531 9532 /// Returns the range of an opaque value of the given integral type. 9533 static IntRange forValueOfType(ASTContext &C, QualType T) { 9534 return forValueOfCanonicalType(C, 9535 T->getCanonicalTypeInternal().getTypePtr()); 9536 } 9537 9538 /// Returns the range of an opaque value of a canonical integral type. 9539 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9540 assert(T->isCanonicalUnqualified()); 9541 9542 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9543 T = VT->getElementType().getTypePtr(); 9544 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9545 T = CT->getElementType().getTypePtr(); 9546 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9547 T = AT->getValueType().getTypePtr(); 9548 9549 if (!C.getLangOpts().CPlusPlus) { 9550 // For enum types in C code, use the underlying datatype. 9551 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9552 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9553 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9554 // For enum types in C++, use the known bit width of the enumerators. 9555 EnumDecl *Enum = ET->getDecl(); 9556 // In C++11, enums can have a fixed underlying type. Use this type to 9557 // compute the range. 9558 if (Enum->isFixed()) { 9559 return IntRange(C.getIntWidth(QualType(T, 0)), 9560 !ET->isSignedIntegerOrEnumerationType()); 9561 } 9562 9563 unsigned NumPositive = Enum->getNumPositiveBits(); 9564 unsigned NumNegative = Enum->getNumNegativeBits(); 9565 9566 if (NumNegative == 0) 9567 return IntRange(NumPositive, true/*NonNegative*/); 9568 else 9569 return IntRange(std::max(NumPositive + 1, NumNegative), 9570 false/*NonNegative*/); 9571 } 9572 9573 const BuiltinType *BT = cast<BuiltinType>(T); 9574 assert(BT->isInteger()); 9575 9576 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9577 } 9578 9579 /// Returns the "target" range of a canonical integral type, i.e. 9580 /// the range of values expressible in the type. 9581 /// 9582 /// This matches forValueOfCanonicalType except that enums have the 9583 /// full range of their type, not the range of their enumerators. 9584 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9585 assert(T->isCanonicalUnqualified()); 9586 9587 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9588 T = VT->getElementType().getTypePtr(); 9589 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9590 T = CT->getElementType().getTypePtr(); 9591 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9592 T = AT->getValueType().getTypePtr(); 9593 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9594 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9595 9596 const BuiltinType *BT = cast<BuiltinType>(T); 9597 assert(BT->isInteger()); 9598 9599 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9600 } 9601 9602 /// Returns the supremum of two ranges: i.e. their conservative merge. 9603 static IntRange join(IntRange L, IntRange R) { 9604 return IntRange(std::max(L.Width, R.Width), 9605 L.NonNegative && R.NonNegative); 9606 } 9607 9608 /// Returns the infinum of two ranges: i.e. their aggressive merge. 9609 static IntRange meet(IntRange L, IntRange R) { 9610 return IntRange(std::min(L.Width, R.Width), 9611 L.NonNegative || R.NonNegative); 9612 } 9613 }; 9614 9615 } // namespace 9616 9617 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 9618 unsigned MaxWidth) { 9619 if (value.isSigned() && value.isNegative()) 9620 return IntRange(value.getMinSignedBits(), false); 9621 9622 if (value.getBitWidth() > MaxWidth) 9623 value = value.trunc(MaxWidth); 9624 9625 // isNonNegative() just checks the sign bit without considering 9626 // signedness. 9627 return IntRange(value.getActiveBits(), true); 9628 } 9629 9630 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 9631 unsigned MaxWidth) { 9632 if (result.isInt()) 9633 return GetValueRange(C, result.getInt(), MaxWidth); 9634 9635 if (result.isVector()) { 9636 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 9637 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 9638 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 9639 R = IntRange::join(R, El); 9640 } 9641 return R; 9642 } 9643 9644 if (result.isComplexInt()) { 9645 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 9646 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 9647 return IntRange::join(R, I); 9648 } 9649 9650 // This can happen with lossless casts to intptr_t of "based" lvalues. 9651 // Assume it might use arbitrary bits. 9652 // FIXME: The only reason we need to pass the type in here is to get 9653 // the sign right on this one case. It would be nice if APValue 9654 // preserved this. 9655 assert(result.isLValue() || result.isAddrLabelDiff()); 9656 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 9657 } 9658 9659 static QualType GetExprType(const Expr *E) { 9660 QualType Ty = E->getType(); 9661 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 9662 Ty = AtomicRHS->getValueType(); 9663 return Ty; 9664 } 9665 9666 /// Pseudo-evaluate the given integer expression, estimating the 9667 /// range of values it might take. 9668 /// 9669 /// \param MaxWidth - the width to which the value will be truncated 9670 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 9671 E = E->IgnoreParens(); 9672 9673 // Try a full evaluation first. 9674 Expr::EvalResult result; 9675 if (E->EvaluateAsRValue(result, C)) 9676 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 9677 9678 // I think we only want to look through implicit casts here; if the 9679 // user has an explicit widening cast, we should treat the value as 9680 // being of the new, wider type. 9681 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 9682 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 9683 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 9684 9685 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 9686 9687 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 9688 CE->getCastKind() == CK_BooleanToSignedIntegral; 9689 9690 // Assume that non-integer casts can span the full range of the type. 9691 if (!isIntegerCast) 9692 return OutputTypeRange; 9693 9694 IntRange SubRange 9695 = GetExprRange(C, CE->getSubExpr(), 9696 std::min(MaxWidth, OutputTypeRange.Width)); 9697 9698 // Bail out if the subexpr's range is as wide as the cast type. 9699 if (SubRange.Width >= OutputTypeRange.Width) 9700 return OutputTypeRange; 9701 9702 // Otherwise, we take the smaller width, and we're non-negative if 9703 // either the output type or the subexpr is. 9704 return IntRange(SubRange.Width, 9705 SubRange.NonNegative || OutputTypeRange.NonNegative); 9706 } 9707 9708 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9709 // If we can fold the condition, just take that operand. 9710 bool CondResult; 9711 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9712 return GetExprRange(C, CondResult ? CO->getTrueExpr() 9713 : CO->getFalseExpr(), 9714 MaxWidth); 9715 9716 // Otherwise, conservatively merge. 9717 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 9718 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 9719 return IntRange::join(L, R); 9720 } 9721 9722 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9723 switch (BO->getOpcode()) { 9724 case BO_Cmp: 9725 llvm_unreachable("builtin <=> should have class type"); 9726 9727 // Boolean-valued operations are single-bit and positive. 9728 case BO_LAnd: 9729 case BO_LOr: 9730 case BO_LT: 9731 case BO_GT: 9732 case BO_LE: 9733 case BO_GE: 9734 case BO_EQ: 9735 case BO_NE: 9736 return IntRange::forBoolType(); 9737 9738 // The type of the assignments is the type of the LHS, so the RHS 9739 // is not necessarily the same type. 9740 case BO_MulAssign: 9741 case BO_DivAssign: 9742 case BO_RemAssign: 9743 case BO_AddAssign: 9744 case BO_SubAssign: 9745 case BO_XorAssign: 9746 case BO_OrAssign: 9747 // TODO: bitfields? 9748 return IntRange::forValueOfType(C, GetExprType(E)); 9749 9750 // Simple assignments just pass through the RHS, which will have 9751 // been coerced to the LHS type. 9752 case BO_Assign: 9753 // TODO: bitfields? 9754 return GetExprRange(C, BO->getRHS(), MaxWidth); 9755 9756 // Operations with opaque sources are black-listed. 9757 case BO_PtrMemD: 9758 case BO_PtrMemI: 9759 return IntRange::forValueOfType(C, GetExprType(E)); 9760 9761 // Bitwise-and uses the *infinum* of the two source ranges. 9762 case BO_And: 9763 case BO_AndAssign: 9764 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 9765 GetExprRange(C, BO->getRHS(), MaxWidth)); 9766 9767 // Left shift gets black-listed based on a judgement call. 9768 case BO_Shl: 9769 // ...except that we want to treat '1 << (blah)' as logically 9770 // positive. It's an important idiom. 9771 if (IntegerLiteral *I 9772 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 9773 if (I->getValue() == 1) { 9774 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 9775 return IntRange(R.Width, /*NonNegative*/ true); 9776 } 9777 } 9778 LLVM_FALLTHROUGH; 9779 9780 case BO_ShlAssign: 9781 return IntRange::forValueOfType(C, GetExprType(E)); 9782 9783 // Right shift by a constant can narrow its left argument. 9784 case BO_Shr: 9785 case BO_ShrAssign: { 9786 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9787 9788 // If the shift amount is a positive constant, drop the width by 9789 // that much. 9790 llvm::APSInt shift; 9791 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 9792 shift.isNonNegative()) { 9793 unsigned zext = shift.getZExtValue(); 9794 if (zext >= L.Width) 9795 L.Width = (L.NonNegative ? 0 : 1); 9796 else 9797 L.Width -= zext; 9798 } 9799 9800 return L; 9801 } 9802 9803 // Comma acts as its right operand. 9804 case BO_Comma: 9805 return GetExprRange(C, BO->getRHS(), MaxWidth); 9806 9807 // Black-list pointer subtractions. 9808 case BO_Sub: 9809 if (BO->getLHS()->getType()->isPointerType()) 9810 return IntRange::forValueOfType(C, GetExprType(E)); 9811 break; 9812 9813 // The width of a division result is mostly determined by the size 9814 // of the LHS. 9815 case BO_Div: { 9816 // Don't 'pre-truncate' the operands. 9817 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9818 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9819 9820 // If the divisor is constant, use that. 9821 llvm::APSInt divisor; 9822 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 9823 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 9824 if (log2 >= L.Width) 9825 L.Width = (L.NonNegative ? 0 : 1); 9826 else 9827 L.Width = std::min(L.Width - log2, MaxWidth); 9828 return L; 9829 } 9830 9831 // Otherwise, just use the LHS's width. 9832 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9833 return IntRange(L.Width, L.NonNegative && R.NonNegative); 9834 } 9835 9836 // The result of a remainder can't be larger than the result of 9837 // either side. 9838 case BO_Rem: { 9839 // Don't 'pre-truncate' the operands. 9840 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9841 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9842 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9843 9844 IntRange meet = IntRange::meet(L, R); 9845 meet.Width = std::min(meet.Width, MaxWidth); 9846 return meet; 9847 } 9848 9849 // The default behavior is okay for these. 9850 case BO_Mul: 9851 case BO_Add: 9852 case BO_Xor: 9853 case BO_Or: 9854 break; 9855 } 9856 9857 // The default case is to treat the operation as if it were closed 9858 // on the narrowest type that encompasses both operands. 9859 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9860 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 9861 return IntRange::join(L, R); 9862 } 9863 9864 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 9865 switch (UO->getOpcode()) { 9866 // Boolean-valued operations are white-listed. 9867 case UO_LNot: 9868 return IntRange::forBoolType(); 9869 9870 // Operations with opaque sources are black-listed. 9871 case UO_Deref: 9872 case UO_AddrOf: // should be impossible 9873 return IntRange::forValueOfType(C, GetExprType(E)); 9874 9875 default: 9876 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 9877 } 9878 } 9879 9880 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 9881 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 9882 9883 if (const auto *BitField = E->getSourceBitField()) 9884 return IntRange(BitField->getBitWidthValue(C), 9885 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 9886 9887 return IntRange::forValueOfType(C, GetExprType(E)); 9888 } 9889 9890 static IntRange GetExprRange(ASTContext &C, const Expr *E) { 9891 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 9892 } 9893 9894 /// Checks whether the given value, which currently has the given 9895 /// source semantics, has the same value when coerced through the 9896 /// target semantics. 9897 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 9898 const llvm::fltSemantics &Src, 9899 const llvm::fltSemantics &Tgt) { 9900 llvm::APFloat truncated = value; 9901 9902 bool ignored; 9903 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 9904 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 9905 9906 return truncated.bitwiseIsEqual(value); 9907 } 9908 9909 /// Checks whether the given value, which currently has the given 9910 /// source semantics, has the same value when coerced through the 9911 /// target semantics. 9912 /// 9913 /// The value might be a vector of floats (or a complex number). 9914 static bool IsSameFloatAfterCast(const APValue &value, 9915 const llvm::fltSemantics &Src, 9916 const llvm::fltSemantics &Tgt) { 9917 if (value.isFloat()) 9918 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 9919 9920 if (value.isVector()) { 9921 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 9922 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 9923 return false; 9924 return true; 9925 } 9926 9927 assert(value.isComplexFloat()); 9928 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 9929 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 9930 } 9931 9932 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 9933 9934 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 9935 // Suppress cases where we are comparing against an enum constant. 9936 if (const DeclRefExpr *DR = 9937 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 9938 if (isa<EnumConstantDecl>(DR->getDecl())) 9939 return true; 9940 9941 // Suppress cases where the '0' value is expanded from a macro. 9942 if (E->getBeginLoc().isMacroID()) 9943 return true; 9944 9945 return false; 9946 } 9947 9948 static bool isKnownToHaveUnsignedValue(Expr *E) { 9949 return E->getType()->isIntegerType() && 9950 (!E->getType()->isSignedIntegerType() || 9951 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 9952 } 9953 9954 namespace { 9955 /// The promoted range of values of a type. In general this has the 9956 /// following structure: 9957 /// 9958 /// |-----------| . . . |-----------| 9959 /// ^ ^ ^ ^ 9960 /// Min HoleMin HoleMax Max 9961 /// 9962 /// ... where there is only a hole if a signed type is promoted to unsigned 9963 /// (in which case Min and Max are the smallest and largest representable 9964 /// values). 9965 struct PromotedRange { 9966 // Min, or HoleMax if there is a hole. 9967 llvm::APSInt PromotedMin; 9968 // Max, or HoleMin if there is a hole. 9969 llvm::APSInt PromotedMax; 9970 9971 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 9972 if (R.Width == 0) 9973 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 9974 else if (R.Width >= BitWidth && !Unsigned) { 9975 // Promotion made the type *narrower*. This happens when promoting 9976 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 9977 // Treat all values of 'signed int' as being in range for now. 9978 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 9979 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 9980 } else { 9981 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 9982 .extOrTrunc(BitWidth); 9983 PromotedMin.setIsUnsigned(Unsigned); 9984 9985 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 9986 .extOrTrunc(BitWidth); 9987 PromotedMax.setIsUnsigned(Unsigned); 9988 } 9989 } 9990 9991 // Determine whether this range is contiguous (has no hole). 9992 bool isContiguous() const { return PromotedMin <= PromotedMax; } 9993 9994 // Where a constant value is within the range. 9995 enum ComparisonResult { 9996 LT = 0x1, 9997 LE = 0x2, 9998 GT = 0x4, 9999 GE = 0x8, 10000 EQ = 0x10, 10001 NE = 0x20, 10002 InRangeFlag = 0x40, 10003 10004 Less = LE | LT | NE, 10005 Min = LE | InRangeFlag, 10006 InRange = InRangeFlag, 10007 Max = GE | InRangeFlag, 10008 Greater = GE | GT | NE, 10009 10010 OnlyValue = LE | GE | EQ | InRangeFlag, 10011 InHole = NE 10012 }; 10013 10014 ComparisonResult compare(const llvm::APSInt &Value) const { 10015 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10016 Value.isUnsigned() == PromotedMin.isUnsigned()); 10017 if (!isContiguous()) { 10018 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10019 if (Value.isMinValue()) return Min; 10020 if (Value.isMaxValue()) return Max; 10021 if (Value >= PromotedMin) return InRange; 10022 if (Value <= PromotedMax) return InRange; 10023 return InHole; 10024 } 10025 10026 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10027 case -1: return Less; 10028 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10029 case 1: 10030 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10031 case -1: return InRange; 10032 case 0: return Max; 10033 case 1: return Greater; 10034 } 10035 } 10036 10037 llvm_unreachable("impossible compare result"); 10038 } 10039 10040 static llvm::Optional<StringRef> 10041 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10042 if (Op == BO_Cmp) { 10043 ComparisonResult LTFlag = LT, GTFlag = GT; 10044 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10045 10046 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10047 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10048 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10049 return llvm::None; 10050 } 10051 10052 ComparisonResult TrueFlag, FalseFlag; 10053 if (Op == BO_EQ) { 10054 TrueFlag = EQ; 10055 FalseFlag = NE; 10056 } else if (Op == BO_NE) { 10057 TrueFlag = NE; 10058 FalseFlag = EQ; 10059 } else { 10060 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10061 TrueFlag = LT; 10062 FalseFlag = GE; 10063 } else { 10064 TrueFlag = GT; 10065 FalseFlag = LE; 10066 } 10067 if (Op == BO_GE || Op == BO_LE) 10068 std::swap(TrueFlag, FalseFlag); 10069 } 10070 if (R & TrueFlag) 10071 return StringRef("true"); 10072 if (R & FalseFlag) 10073 return StringRef("false"); 10074 return llvm::None; 10075 } 10076 }; 10077 } 10078 10079 static bool HasEnumType(Expr *E) { 10080 // Strip off implicit integral promotions. 10081 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10082 if (ICE->getCastKind() != CK_IntegralCast && 10083 ICE->getCastKind() != CK_NoOp) 10084 break; 10085 E = ICE->getSubExpr(); 10086 } 10087 10088 return E->getType()->isEnumeralType(); 10089 } 10090 10091 static int classifyConstantValue(Expr *Constant) { 10092 // The values of this enumeration are used in the diagnostics 10093 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10094 enum ConstantValueKind { 10095 Miscellaneous = 0, 10096 LiteralTrue, 10097 LiteralFalse 10098 }; 10099 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10100 return BL->getValue() ? ConstantValueKind::LiteralTrue 10101 : ConstantValueKind::LiteralFalse; 10102 return ConstantValueKind::Miscellaneous; 10103 } 10104 10105 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10106 Expr *Constant, Expr *Other, 10107 const llvm::APSInt &Value, 10108 bool RhsConstant) { 10109 if (S.inTemplateInstantiation()) 10110 return false; 10111 10112 Expr *OriginalOther = Other; 10113 10114 Constant = Constant->IgnoreParenImpCasts(); 10115 Other = Other->IgnoreParenImpCasts(); 10116 10117 // Suppress warnings on tautological comparisons between values of the same 10118 // enumeration type. There are only two ways we could warn on this: 10119 // - If the constant is outside the range of representable values of 10120 // the enumeration. In such a case, we should warn about the cast 10121 // to enumeration type, not about the comparison. 10122 // - If the constant is the maximum / minimum in-range value. For an 10123 // enumeratin type, such comparisons can be meaningful and useful. 10124 if (Constant->getType()->isEnumeralType() && 10125 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10126 return false; 10127 10128 // TODO: Investigate using GetExprRange() to get tighter bounds 10129 // on the bit ranges. 10130 QualType OtherT = Other->getType(); 10131 if (const auto *AT = OtherT->getAs<AtomicType>()) 10132 OtherT = AT->getValueType(); 10133 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10134 10135 // Whether we're treating Other as being a bool because of the form of 10136 // expression despite it having another type (typically 'int' in C). 10137 bool OtherIsBooleanDespiteType = 10138 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10139 if (OtherIsBooleanDespiteType) 10140 OtherRange = IntRange::forBoolType(); 10141 10142 // Determine the promoted range of the other type and see if a comparison of 10143 // the constant against that range is tautological. 10144 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10145 Value.isUnsigned()); 10146 auto Cmp = OtherPromotedRange.compare(Value); 10147 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10148 if (!Result) 10149 return false; 10150 10151 // Suppress the diagnostic for an in-range comparison if the constant comes 10152 // from a macro or enumerator. We don't want to diagnose 10153 // 10154 // some_long_value <= INT_MAX 10155 // 10156 // when sizeof(int) == sizeof(long). 10157 bool InRange = Cmp & PromotedRange::InRangeFlag; 10158 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10159 return false; 10160 10161 // If this is a comparison to an enum constant, include that 10162 // constant in the diagnostic. 10163 const EnumConstantDecl *ED = nullptr; 10164 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10165 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10166 10167 // Should be enough for uint128 (39 decimal digits) 10168 SmallString<64> PrettySourceValue; 10169 llvm::raw_svector_ostream OS(PrettySourceValue); 10170 if (ED) 10171 OS << '\'' << *ED << "' (" << Value << ")"; 10172 else 10173 OS << Value; 10174 10175 // FIXME: We use a somewhat different formatting for the in-range cases and 10176 // cases involving boolean values for historical reasons. We should pick a 10177 // consistent way of presenting these diagnostics. 10178 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10179 S.DiagRuntimeBehavior( 10180 E->getOperatorLoc(), E, 10181 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10182 : diag::warn_tautological_bool_compare) 10183 << OS.str() << classifyConstantValue(Constant) 10184 << OtherT << OtherIsBooleanDespiteType << *Result 10185 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10186 } else { 10187 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10188 ? (HasEnumType(OriginalOther) 10189 ? diag::warn_unsigned_enum_always_true_comparison 10190 : diag::warn_unsigned_always_true_comparison) 10191 : diag::warn_tautological_constant_compare; 10192 10193 S.Diag(E->getOperatorLoc(), Diag) 10194 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10195 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10196 } 10197 10198 return true; 10199 } 10200 10201 /// Analyze the operands of the given comparison. Implements the 10202 /// fallback case from AnalyzeComparison. 10203 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10204 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10205 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10206 } 10207 10208 /// Implements -Wsign-compare. 10209 /// 10210 /// \param E the binary operator to check for warnings 10211 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10212 // The type the comparison is being performed in. 10213 QualType T = E->getLHS()->getType(); 10214 10215 // Only analyze comparison operators where both sides have been converted to 10216 // the same type. 10217 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10218 return AnalyzeImpConvsInComparison(S, E); 10219 10220 // Don't analyze value-dependent comparisons directly. 10221 if (E->isValueDependent()) 10222 return AnalyzeImpConvsInComparison(S, E); 10223 10224 Expr *LHS = E->getLHS(); 10225 Expr *RHS = E->getRHS(); 10226 10227 if (T->isIntegralType(S.Context)) { 10228 llvm::APSInt RHSValue; 10229 llvm::APSInt LHSValue; 10230 10231 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10232 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10233 10234 // We don't care about expressions whose result is a constant. 10235 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10236 return AnalyzeImpConvsInComparison(S, E); 10237 10238 // We only care about expressions where just one side is literal 10239 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10240 // Is the constant on the RHS or LHS? 10241 const bool RhsConstant = IsRHSIntegralLiteral; 10242 Expr *Const = RhsConstant ? RHS : LHS; 10243 Expr *Other = RhsConstant ? LHS : RHS; 10244 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10245 10246 // Check whether an integer constant comparison results in a value 10247 // of 'true' or 'false'. 10248 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10249 return AnalyzeImpConvsInComparison(S, E); 10250 } 10251 } 10252 10253 if (!T->hasUnsignedIntegerRepresentation()) { 10254 // We don't do anything special if this isn't an unsigned integral 10255 // comparison: we're only interested in integral comparisons, and 10256 // signed comparisons only happen in cases we don't care to warn about. 10257 return AnalyzeImpConvsInComparison(S, E); 10258 } 10259 10260 LHS = LHS->IgnoreParenImpCasts(); 10261 RHS = RHS->IgnoreParenImpCasts(); 10262 10263 if (!S.getLangOpts().CPlusPlus) { 10264 // Avoid warning about comparison of integers with different signs when 10265 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10266 // the type of `E`. 10267 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10268 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10269 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10270 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10271 } 10272 10273 // Check to see if one of the (unmodified) operands is of different 10274 // signedness. 10275 Expr *signedOperand, *unsignedOperand; 10276 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10277 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10278 "unsigned comparison between two signed integer expressions?"); 10279 signedOperand = LHS; 10280 unsignedOperand = RHS; 10281 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10282 signedOperand = RHS; 10283 unsignedOperand = LHS; 10284 } else { 10285 return AnalyzeImpConvsInComparison(S, E); 10286 } 10287 10288 // Otherwise, calculate the effective range of the signed operand. 10289 IntRange signedRange = GetExprRange(S.Context, signedOperand); 10290 10291 // Go ahead and analyze implicit conversions in the operands. Note 10292 // that we skip the implicit conversions on both sides. 10293 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10294 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10295 10296 // If the signed range is non-negative, -Wsign-compare won't fire. 10297 if (signedRange.NonNegative) 10298 return; 10299 10300 // For (in)equality comparisons, if the unsigned operand is a 10301 // constant which cannot collide with a overflowed signed operand, 10302 // then reinterpreting the signed operand as unsigned will not 10303 // change the result of the comparison. 10304 if (E->isEqualityOp()) { 10305 unsigned comparisonWidth = S.Context.getIntWidth(T); 10306 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 10307 10308 // We should never be unable to prove that the unsigned operand is 10309 // non-negative. 10310 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10311 10312 if (unsignedRange.Width < comparisonWidth) 10313 return; 10314 } 10315 10316 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10317 S.PDiag(diag::warn_mixed_sign_comparison) 10318 << LHS->getType() << RHS->getType() 10319 << LHS->getSourceRange() << RHS->getSourceRange()); 10320 } 10321 10322 /// Analyzes an attempt to assign the given value to a bitfield. 10323 /// 10324 /// Returns true if there was something fishy about the attempt. 10325 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10326 SourceLocation InitLoc) { 10327 assert(Bitfield->isBitField()); 10328 if (Bitfield->isInvalidDecl()) 10329 return false; 10330 10331 // White-list bool bitfields. 10332 QualType BitfieldType = Bitfield->getType(); 10333 if (BitfieldType->isBooleanType()) 10334 return false; 10335 10336 if (BitfieldType->isEnumeralType()) { 10337 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 10338 // If the underlying enum type was not explicitly specified as an unsigned 10339 // type and the enum contain only positive values, MSVC++ will cause an 10340 // inconsistency by storing this as a signed type. 10341 if (S.getLangOpts().CPlusPlus11 && 10342 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10343 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10344 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10345 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10346 << BitfieldEnumDecl->getNameAsString(); 10347 } 10348 } 10349 10350 if (Bitfield->getType()->isBooleanType()) 10351 return false; 10352 10353 // Ignore value- or type-dependent expressions. 10354 if (Bitfield->getBitWidth()->isValueDependent() || 10355 Bitfield->getBitWidth()->isTypeDependent() || 10356 Init->isValueDependent() || 10357 Init->isTypeDependent()) 10358 return false; 10359 10360 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10361 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10362 10363 Expr::EvalResult Result; 10364 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10365 Expr::SE_AllowSideEffects)) { 10366 // The RHS is not constant. If the RHS has an enum type, make sure the 10367 // bitfield is wide enough to hold all the values of the enum without 10368 // truncation. 10369 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10370 EnumDecl *ED = EnumTy->getDecl(); 10371 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10372 10373 // Enum types are implicitly signed on Windows, so check if there are any 10374 // negative enumerators to see if the enum was intended to be signed or 10375 // not. 10376 bool SignedEnum = ED->getNumNegativeBits() > 0; 10377 10378 // Check for surprising sign changes when assigning enum values to a 10379 // bitfield of different signedness. If the bitfield is signed and we 10380 // have exactly the right number of bits to store this unsigned enum, 10381 // suggest changing the enum to an unsigned type. This typically happens 10382 // on Windows where unfixed enums always use an underlying type of 'int'. 10383 unsigned DiagID = 0; 10384 if (SignedEnum && !SignedBitfield) { 10385 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10386 } else if (SignedBitfield && !SignedEnum && 10387 ED->getNumPositiveBits() == FieldWidth) { 10388 DiagID = diag::warn_signed_bitfield_enum_conversion; 10389 } 10390 10391 if (DiagID) { 10392 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10393 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10394 SourceRange TypeRange = 10395 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10396 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10397 << SignedEnum << TypeRange; 10398 } 10399 10400 // Compute the required bitwidth. If the enum has negative values, we need 10401 // one more bit than the normal number of positive bits to represent the 10402 // sign bit. 10403 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10404 ED->getNumNegativeBits()) 10405 : ED->getNumPositiveBits(); 10406 10407 // Check the bitwidth. 10408 if (BitsNeeded > FieldWidth) { 10409 Expr *WidthExpr = Bitfield->getBitWidth(); 10410 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10411 << Bitfield << ED; 10412 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10413 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10414 } 10415 } 10416 10417 return false; 10418 } 10419 10420 llvm::APSInt Value = Result.Val.getInt(); 10421 10422 unsigned OriginalWidth = Value.getBitWidth(); 10423 10424 if (!Value.isSigned() || Value.isNegative()) 10425 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10426 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10427 OriginalWidth = Value.getMinSignedBits(); 10428 10429 if (OriginalWidth <= FieldWidth) 10430 return false; 10431 10432 // Compute the value which the bitfield will contain. 10433 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10434 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10435 10436 // Check whether the stored value is equal to the original value. 10437 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10438 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10439 return false; 10440 10441 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10442 // therefore don't strictly fit into a signed bitfield of width 1. 10443 if (FieldWidth == 1 && Value == 1) 10444 return false; 10445 10446 std::string PrettyValue = Value.toString(10); 10447 std::string PrettyTrunc = TruncatedValue.toString(10); 10448 10449 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10450 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10451 << Init->getSourceRange(); 10452 10453 return true; 10454 } 10455 10456 /// Analyze the given simple or compound assignment for warning-worthy 10457 /// operations. 10458 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10459 // Just recurse on the LHS. 10460 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10461 10462 // We want to recurse on the RHS as normal unless we're assigning to 10463 // a bitfield. 10464 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10465 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10466 E->getOperatorLoc())) { 10467 // Recurse, ignoring any implicit conversions on the RHS. 10468 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10469 E->getOperatorLoc()); 10470 } 10471 } 10472 10473 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10474 10475 // Diagnose implicitly sequentially-consistent atomic assignment. 10476 if (E->getLHS()->getType()->isAtomicType()) 10477 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10478 } 10479 10480 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10481 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10482 SourceLocation CContext, unsigned diag, 10483 bool pruneControlFlow = false) { 10484 if (pruneControlFlow) { 10485 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10486 S.PDiag(diag) 10487 << SourceType << T << E->getSourceRange() 10488 << SourceRange(CContext)); 10489 return; 10490 } 10491 S.Diag(E->getExprLoc(), diag) 10492 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10493 } 10494 10495 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10496 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10497 SourceLocation CContext, 10498 unsigned diag, bool pruneControlFlow = false) { 10499 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10500 } 10501 10502 /// Diagnose an implicit cast from a floating point value to an integer value. 10503 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10504 SourceLocation CContext) { 10505 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10506 const bool PruneWarnings = S.inTemplateInstantiation(); 10507 10508 Expr *InnerE = E->IgnoreParenImpCasts(); 10509 // We also want to warn on, e.g., "int i = -1.234" 10510 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10511 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10512 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10513 10514 const bool IsLiteral = 10515 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10516 10517 llvm::APFloat Value(0.0); 10518 bool IsConstant = 10519 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10520 if (!IsConstant) { 10521 return DiagnoseImpCast(S, E, T, CContext, 10522 diag::warn_impcast_float_integer, PruneWarnings); 10523 } 10524 10525 bool isExact = false; 10526 10527 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10528 T->hasUnsignedIntegerRepresentation()); 10529 llvm::APFloat::opStatus Result = Value.convertToInteger( 10530 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10531 10532 if (Result == llvm::APFloat::opOK && isExact) { 10533 if (IsLiteral) return; 10534 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 10535 PruneWarnings); 10536 } 10537 10538 // Conversion of a floating-point value to a non-bool integer where the 10539 // integral part cannot be represented by the integer type is undefined. 10540 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 10541 return DiagnoseImpCast( 10542 S, E, T, CContext, 10543 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 10544 : diag::warn_impcast_float_to_integer_out_of_range, 10545 PruneWarnings); 10546 10547 unsigned DiagID = 0; 10548 if (IsLiteral) { 10549 // Warn on floating point literal to integer. 10550 DiagID = diag::warn_impcast_literal_float_to_integer; 10551 } else if (IntegerValue == 0) { 10552 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 10553 return DiagnoseImpCast(S, E, T, CContext, 10554 diag::warn_impcast_float_integer, PruneWarnings); 10555 } 10556 // Warn on non-zero to zero conversion. 10557 DiagID = diag::warn_impcast_float_to_integer_zero; 10558 } else { 10559 if (IntegerValue.isUnsigned()) { 10560 if (!IntegerValue.isMaxValue()) { 10561 return DiagnoseImpCast(S, E, T, CContext, 10562 diag::warn_impcast_float_integer, PruneWarnings); 10563 } 10564 } else { // IntegerValue.isSigned() 10565 if (!IntegerValue.isMaxSignedValue() && 10566 !IntegerValue.isMinSignedValue()) { 10567 return DiagnoseImpCast(S, E, T, CContext, 10568 diag::warn_impcast_float_integer, PruneWarnings); 10569 } 10570 } 10571 // Warn on evaluatable floating point expression to integer conversion. 10572 DiagID = diag::warn_impcast_float_to_integer; 10573 } 10574 10575 // FIXME: Force the precision of the source value down so we don't print 10576 // digits which are usually useless (we don't really care here if we 10577 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10578 // would automatically print the shortest representation, but it's a bit 10579 // tricky to implement. 10580 SmallString<16> PrettySourceValue; 10581 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10582 precision = (precision * 59 + 195) / 196; 10583 Value.toString(PrettySourceValue, precision); 10584 10585 SmallString<16> PrettyTargetValue; 10586 if (IsBool) 10587 PrettyTargetValue = Value.isZero() ? "false" : "true"; 10588 else 10589 IntegerValue.toString(PrettyTargetValue); 10590 10591 if (PruneWarnings) { 10592 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10593 S.PDiag(DiagID) 10594 << E->getType() << T.getUnqualifiedType() 10595 << PrettySourceValue << PrettyTargetValue 10596 << E->getSourceRange() << SourceRange(CContext)); 10597 } else { 10598 S.Diag(E->getExprLoc(), DiagID) 10599 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 10600 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 10601 } 10602 } 10603 10604 /// Analyze the given compound assignment for the possible losing of 10605 /// floating-point precision. 10606 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 10607 assert(isa<CompoundAssignOperator>(E) && 10608 "Must be compound assignment operation"); 10609 // Recurse on the LHS and RHS in here 10610 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10611 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10612 10613 if (E->getLHS()->getType()->isAtomicType()) 10614 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 10615 10616 // Now check the outermost expression 10617 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 10618 const auto *RBT = cast<CompoundAssignOperator>(E) 10619 ->getComputationResultType() 10620 ->getAs<BuiltinType>(); 10621 10622 // The below checks assume source is floating point. 10623 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 10624 10625 // If source is floating point but target is not. 10626 if (!ResultBT->isFloatingPoint()) 10627 return DiagnoseFloatingImpCast(S, E, E->getRHS()->getType(), 10628 E->getExprLoc()); 10629 10630 // If both source and target are floating points. 10631 // Builtin FP kinds are ordered by increasing FP rank. 10632 if (ResultBT->getKind() < RBT->getKind() && 10633 // We don't want to warn for system macro. 10634 !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 10635 // warn about dropping FP rank. 10636 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 10637 diag::warn_impcast_float_result_precision); 10638 } 10639 10640 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 10641 IntRange Range) { 10642 if (!Range.Width) return "0"; 10643 10644 llvm::APSInt ValueInRange = Value; 10645 ValueInRange.setIsSigned(!Range.NonNegative); 10646 ValueInRange = ValueInRange.trunc(Range.Width); 10647 return ValueInRange.toString(10); 10648 } 10649 10650 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 10651 if (!isa<ImplicitCastExpr>(Ex)) 10652 return false; 10653 10654 Expr *InnerE = Ex->IgnoreParenImpCasts(); 10655 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 10656 const Type *Source = 10657 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 10658 if (Target->isDependentType()) 10659 return false; 10660 10661 const BuiltinType *FloatCandidateBT = 10662 dyn_cast<BuiltinType>(ToBool ? Source : Target); 10663 const Type *BoolCandidateType = ToBool ? Target : Source; 10664 10665 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 10666 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 10667 } 10668 10669 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 10670 SourceLocation CC) { 10671 unsigned NumArgs = TheCall->getNumArgs(); 10672 for (unsigned i = 0; i < NumArgs; ++i) { 10673 Expr *CurrA = TheCall->getArg(i); 10674 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 10675 continue; 10676 10677 bool IsSwapped = ((i > 0) && 10678 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 10679 IsSwapped |= ((i < (NumArgs - 1)) && 10680 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 10681 if (IsSwapped) { 10682 // Warn on this floating-point to bool conversion. 10683 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 10684 CurrA->getType(), CC, 10685 diag::warn_impcast_floating_point_to_bool); 10686 } 10687 } 10688 } 10689 10690 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 10691 SourceLocation CC) { 10692 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 10693 E->getExprLoc())) 10694 return; 10695 10696 // Don't warn on functions which have return type nullptr_t. 10697 if (isa<CallExpr>(E)) 10698 return; 10699 10700 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 10701 const Expr::NullPointerConstantKind NullKind = 10702 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 10703 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 10704 return; 10705 10706 // Return if target type is a safe conversion. 10707 if (T->isAnyPointerType() || T->isBlockPointerType() || 10708 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 10709 return; 10710 10711 SourceLocation Loc = E->getSourceRange().getBegin(); 10712 10713 // Venture through the macro stacks to get to the source of macro arguments. 10714 // The new location is a better location than the complete location that was 10715 // passed in. 10716 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 10717 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 10718 10719 // __null is usually wrapped in a macro. Go up a macro if that is the case. 10720 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 10721 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 10722 Loc, S.SourceMgr, S.getLangOpts()); 10723 if (MacroName == "NULL") 10724 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 10725 } 10726 10727 // Only warn if the null and context location are in the same macro expansion. 10728 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 10729 return; 10730 10731 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 10732 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 10733 << FixItHint::CreateReplacement(Loc, 10734 S.getFixItZeroLiteralForType(T, Loc)); 10735 } 10736 10737 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10738 ObjCArrayLiteral *ArrayLiteral); 10739 10740 static void 10741 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10742 ObjCDictionaryLiteral *DictionaryLiteral); 10743 10744 /// Check a single element within a collection literal against the 10745 /// target element type. 10746 static void checkObjCCollectionLiteralElement(Sema &S, 10747 QualType TargetElementType, 10748 Expr *Element, 10749 unsigned ElementKind) { 10750 // Skip a bitcast to 'id' or qualified 'id'. 10751 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 10752 if (ICE->getCastKind() == CK_BitCast && 10753 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 10754 Element = ICE->getSubExpr(); 10755 } 10756 10757 QualType ElementType = Element->getType(); 10758 ExprResult ElementResult(Element); 10759 if (ElementType->getAs<ObjCObjectPointerType>() && 10760 S.CheckSingleAssignmentConstraints(TargetElementType, 10761 ElementResult, 10762 false, false) 10763 != Sema::Compatible) { 10764 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 10765 << ElementType << ElementKind << TargetElementType 10766 << Element->getSourceRange(); 10767 } 10768 10769 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 10770 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 10771 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 10772 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 10773 } 10774 10775 /// Check an Objective-C array literal being converted to the given 10776 /// target type. 10777 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10778 ObjCArrayLiteral *ArrayLiteral) { 10779 if (!S.NSArrayDecl) 10780 return; 10781 10782 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10783 if (!TargetObjCPtr) 10784 return; 10785 10786 if (TargetObjCPtr->isUnspecialized() || 10787 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10788 != S.NSArrayDecl->getCanonicalDecl()) 10789 return; 10790 10791 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10792 if (TypeArgs.size() != 1) 10793 return; 10794 10795 QualType TargetElementType = TypeArgs[0]; 10796 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 10797 checkObjCCollectionLiteralElement(S, TargetElementType, 10798 ArrayLiteral->getElement(I), 10799 0); 10800 } 10801 } 10802 10803 /// Check an Objective-C dictionary literal being converted to the given 10804 /// target type. 10805 static void 10806 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10807 ObjCDictionaryLiteral *DictionaryLiteral) { 10808 if (!S.NSDictionaryDecl) 10809 return; 10810 10811 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10812 if (!TargetObjCPtr) 10813 return; 10814 10815 if (TargetObjCPtr->isUnspecialized() || 10816 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10817 != S.NSDictionaryDecl->getCanonicalDecl()) 10818 return; 10819 10820 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10821 if (TypeArgs.size() != 2) 10822 return; 10823 10824 QualType TargetKeyType = TypeArgs[0]; 10825 QualType TargetObjectType = TypeArgs[1]; 10826 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 10827 auto Element = DictionaryLiteral->getKeyValueElement(I); 10828 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 10829 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 10830 } 10831 } 10832 10833 // Helper function to filter out cases for constant width constant conversion. 10834 // Don't warn on char array initialization or for non-decimal values. 10835 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 10836 SourceLocation CC) { 10837 // If initializing from a constant, and the constant starts with '0', 10838 // then it is a binary, octal, or hexadecimal. Allow these constants 10839 // to fill all the bits, even if there is a sign change. 10840 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 10841 const char FirstLiteralCharacter = 10842 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 10843 if (FirstLiteralCharacter == '0') 10844 return false; 10845 } 10846 10847 // If the CC location points to a '{', and the type is char, then assume 10848 // assume it is an array initialization. 10849 if (CC.isValid() && T->isCharType()) { 10850 const char FirstContextCharacter = 10851 S.getSourceManager().getCharacterData(CC)[0]; 10852 if (FirstContextCharacter == '{') 10853 return false; 10854 } 10855 10856 return true; 10857 } 10858 10859 static void 10860 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, 10861 bool *ICContext = nullptr) { 10862 if (E->isTypeDependent() || E->isValueDependent()) return; 10863 10864 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 10865 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 10866 if (Source == Target) return; 10867 if (Target->isDependentType()) return; 10868 10869 // If the conversion context location is invalid don't complain. We also 10870 // don't want to emit a warning if the issue occurs from the expansion of 10871 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 10872 // delay this check as long as possible. Once we detect we are in that 10873 // scenario, we just return. 10874 if (CC.isInvalid()) 10875 return; 10876 10877 if (Source->isAtomicType()) 10878 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 10879 10880 // Diagnose implicit casts to bool. 10881 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 10882 if (isa<StringLiteral>(E)) 10883 // Warn on string literal to bool. Checks for string literals in logical 10884 // and expressions, for instance, assert(0 && "error here"), are 10885 // prevented by a check in AnalyzeImplicitConversions(). 10886 return DiagnoseImpCast(S, E, T, CC, 10887 diag::warn_impcast_string_literal_to_bool); 10888 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 10889 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 10890 // This covers the literal expressions that evaluate to Objective-C 10891 // objects. 10892 return DiagnoseImpCast(S, E, T, CC, 10893 diag::warn_impcast_objective_c_literal_to_bool); 10894 } 10895 if (Source->isPointerType() || Source->canDecayToPointerType()) { 10896 // Warn on pointer to bool conversion that is always true. 10897 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 10898 SourceRange(CC)); 10899 } 10900 } 10901 10902 // Check implicit casts from Objective-C collection literals to specialized 10903 // collection types, e.g., NSArray<NSString *> *. 10904 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 10905 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 10906 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 10907 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 10908 10909 // Strip vector types. 10910 if (isa<VectorType>(Source)) { 10911 if (!isa<VectorType>(Target)) { 10912 if (S.SourceMgr.isInSystemMacro(CC)) 10913 return; 10914 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 10915 } 10916 10917 // If the vector cast is cast between two vectors of the same size, it is 10918 // a bitcast, not a conversion. 10919 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 10920 return; 10921 10922 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 10923 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 10924 } 10925 if (auto VecTy = dyn_cast<VectorType>(Target)) 10926 Target = VecTy->getElementType().getTypePtr(); 10927 10928 // Strip complex types. 10929 if (isa<ComplexType>(Source)) { 10930 if (!isa<ComplexType>(Target)) { 10931 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 10932 return; 10933 10934 return DiagnoseImpCast(S, E, T, CC, 10935 S.getLangOpts().CPlusPlus 10936 ? diag::err_impcast_complex_scalar 10937 : diag::warn_impcast_complex_scalar); 10938 } 10939 10940 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 10941 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 10942 } 10943 10944 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 10945 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 10946 10947 // If the source is floating point... 10948 if (SourceBT && SourceBT->isFloatingPoint()) { 10949 // ...and the target is floating point... 10950 if (TargetBT && TargetBT->isFloatingPoint()) { 10951 // ...then warn if we're dropping FP rank. 10952 10953 // Builtin FP kinds are ordered by increasing FP rank. 10954 if (SourceBT->getKind() > TargetBT->getKind()) { 10955 // Don't warn about float constants that are precisely 10956 // representable in the target type. 10957 Expr::EvalResult result; 10958 if (E->EvaluateAsRValue(result, S.Context)) { 10959 // Value might be a float, a float vector, or a float complex. 10960 if (IsSameFloatAfterCast(result.Val, 10961 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 10962 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 10963 return; 10964 } 10965 10966 if (S.SourceMgr.isInSystemMacro(CC)) 10967 return; 10968 10969 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 10970 } 10971 // ... or possibly if we're increasing rank, too 10972 else if (TargetBT->getKind() > SourceBT->getKind()) { 10973 if (S.SourceMgr.isInSystemMacro(CC)) 10974 return; 10975 10976 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 10977 } 10978 return; 10979 } 10980 10981 // If the target is integral, always warn. 10982 if (TargetBT && TargetBT->isInteger()) { 10983 if (S.SourceMgr.isInSystemMacro(CC)) 10984 return; 10985 10986 DiagnoseFloatingImpCast(S, E, T, CC); 10987 } 10988 10989 // Detect the case where a call result is converted from floating-point to 10990 // to bool, and the final argument to the call is converted from bool, to 10991 // discover this typo: 10992 // 10993 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 10994 // 10995 // FIXME: This is an incredibly special case; is there some more general 10996 // way to detect this class of misplaced-parentheses bug? 10997 if (Target->isBooleanType() && isa<CallExpr>(E)) { 10998 // Check last argument of function call to see if it is an 10999 // implicit cast from a type matching the type the result 11000 // is being cast to. 11001 CallExpr *CEx = cast<CallExpr>(E); 11002 if (unsigned NumArgs = CEx->getNumArgs()) { 11003 Expr *LastA = CEx->getArg(NumArgs - 1); 11004 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11005 if (isa<ImplicitCastExpr>(LastA) && 11006 InnerE->getType()->isBooleanType()) { 11007 // Warn on this floating-point to bool conversion 11008 DiagnoseImpCast(S, E, T, CC, 11009 diag::warn_impcast_floating_point_to_bool); 11010 } 11011 } 11012 } 11013 return; 11014 } 11015 11016 DiagnoseNullConversion(S, E, T, CC); 11017 11018 S.DiscardMisalignedMemberAddress(Target, E); 11019 11020 if (!Source->isIntegerType() || !Target->isIntegerType()) 11021 return; 11022 11023 // TODO: remove this early return once the false positives for constant->bool 11024 // in templates, macros, etc, are reduced or removed. 11025 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11026 return; 11027 11028 IntRange SourceRange = GetExprRange(S.Context, E); 11029 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11030 11031 if (SourceRange.Width > TargetRange.Width) { 11032 // If the source is a constant, use a default-on diagnostic. 11033 // TODO: this should happen for bitfield stores, too. 11034 Expr::EvalResult Result; 11035 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11036 llvm::APSInt Value(32); 11037 Value = Result.Val.getInt(); 11038 11039 if (S.SourceMgr.isInSystemMacro(CC)) 11040 return; 11041 11042 std::string PrettySourceValue = Value.toString(10); 11043 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11044 11045 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11046 S.PDiag(diag::warn_impcast_integer_precision_constant) 11047 << PrettySourceValue << PrettyTargetValue 11048 << E->getType() << T << E->getSourceRange() 11049 << clang::SourceRange(CC)); 11050 return; 11051 } 11052 11053 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11054 if (S.SourceMgr.isInSystemMacro(CC)) 11055 return; 11056 11057 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11058 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11059 /* pruneControlFlow */ true); 11060 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11061 } 11062 11063 if (TargetRange.Width > SourceRange.Width) { 11064 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11065 if (UO->getOpcode() == UO_Minus) 11066 if (Source->isUnsignedIntegerType()) { 11067 if (Target->isUnsignedIntegerType()) 11068 return DiagnoseImpCast(S, E, T, CC, 11069 diag::warn_impcast_high_order_zero_bits); 11070 if (Target->isSignedIntegerType()) 11071 return DiagnoseImpCast(S, E, T, CC, 11072 diag::warn_impcast_nonnegative_result); 11073 } 11074 } 11075 11076 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11077 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11078 // Warn when doing a signed to signed conversion, warn if the positive 11079 // source value is exactly the width of the target type, which will 11080 // cause a negative value to be stored. 11081 11082 Expr::EvalResult Result; 11083 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11084 !S.SourceMgr.isInSystemMacro(CC)) { 11085 llvm::APSInt Value = Result.Val.getInt(); 11086 if (isSameWidthConstantConversion(S, E, T, CC)) { 11087 std::string PrettySourceValue = Value.toString(10); 11088 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11089 11090 S.DiagRuntimeBehavior( 11091 E->getExprLoc(), E, 11092 S.PDiag(diag::warn_impcast_integer_precision_constant) 11093 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11094 << E->getSourceRange() << clang::SourceRange(CC)); 11095 return; 11096 } 11097 } 11098 11099 // Fall through for non-constants to give a sign conversion warning. 11100 } 11101 11102 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11103 (!TargetRange.NonNegative && SourceRange.NonNegative && 11104 SourceRange.Width == TargetRange.Width)) { 11105 if (S.SourceMgr.isInSystemMacro(CC)) 11106 return; 11107 11108 unsigned DiagID = diag::warn_impcast_integer_sign; 11109 11110 // Traditionally, gcc has warned about this under -Wsign-compare. 11111 // We also want to warn about it in -Wconversion. 11112 // So if -Wconversion is off, use a completely identical diagnostic 11113 // in the sign-compare group. 11114 // The conditional-checking code will 11115 if (ICContext) { 11116 DiagID = diag::warn_impcast_integer_sign_conditional; 11117 *ICContext = true; 11118 } 11119 11120 return DiagnoseImpCast(S, E, T, CC, DiagID); 11121 } 11122 11123 // Diagnose conversions between different enumeration types. 11124 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11125 // type, to give us better diagnostics. 11126 QualType SourceType = E->getType(); 11127 if (!S.getLangOpts().CPlusPlus) { 11128 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11129 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11130 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11131 SourceType = S.Context.getTypeDeclType(Enum); 11132 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11133 } 11134 } 11135 11136 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11137 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11138 if (SourceEnum->getDecl()->hasNameForLinkage() && 11139 TargetEnum->getDecl()->hasNameForLinkage() && 11140 SourceEnum != TargetEnum) { 11141 if (S.SourceMgr.isInSystemMacro(CC)) 11142 return; 11143 11144 return DiagnoseImpCast(S, E, SourceType, T, CC, 11145 diag::warn_impcast_different_enum_types); 11146 } 11147 } 11148 11149 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11150 SourceLocation CC, QualType T); 11151 11152 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11153 SourceLocation CC, bool &ICContext) { 11154 E = E->IgnoreParenImpCasts(); 11155 11156 if (isa<ConditionalOperator>(E)) 11157 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11158 11159 AnalyzeImplicitConversions(S, E, CC); 11160 if (E->getType() != T) 11161 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11162 } 11163 11164 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11165 SourceLocation CC, QualType T) { 11166 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11167 11168 bool Suspicious = false; 11169 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11170 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11171 11172 // If -Wconversion would have warned about either of the candidates 11173 // for a signedness conversion to the context type... 11174 if (!Suspicious) return; 11175 11176 // ...but it's currently ignored... 11177 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11178 return; 11179 11180 // ...then check whether it would have warned about either of the 11181 // candidates for a signedness conversion to the condition type. 11182 if (E->getType() == T) return; 11183 11184 Suspicious = false; 11185 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11186 E->getType(), CC, &Suspicious); 11187 if (!Suspicious) 11188 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11189 E->getType(), CC, &Suspicious); 11190 } 11191 11192 /// Check conversion of given expression to boolean. 11193 /// Input argument E is a logical expression. 11194 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11195 if (S.getLangOpts().Bool) 11196 return; 11197 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11198 return; 11199 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11200 } 11201 11202 /// AnalyzeImplicitConversions - Find and report any interesting 11203 /// implicit conversions in the given expression. There are a couple 11204 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 11205 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, 11206 SourceLocation CC) { 11207 QualType T = OrigE->getType(); 11208 Expr *E = OrigE->IgnoreParenImpCasts(); 11209 11210 if (E->isTypeDependent() || E->isValueDependent()) 11211 return; 11212 11213 // For conditional operators, we analyze the arguments as if they 11214 // were being fed directly into the output. 11215 if (isa<ConditionalOperator>(E)) { 11216 ConditionalOperator *CO = cast<ConditionalOperator>(E); 11217 CheckConditionalOperator(S, CO, CC, T); 11218 return; 11219 } 11220 11221 // Check implicit argument conversions for function calls. 11222 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 11223 CheckImplicitArgumentConversions(S, Call, CC); 11224 11225 // Go ahead and check any implicit conversions we might have skipped. 11226 // The non-canonical typecheck is just an optimization; 11227 // CheckImplicitConversion will filter out dead implicit conversions. 11228 if (E->getType() != T) 11229 CheckImplicitConversion(S, E, T, CC); 11230 11231 // Now continue drilling into this expression. 11232 11233 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11234 // The bound subexpressions in a PseudoObjectExpr are not reachable 11235 // as transitive children. 11236 // FIXME: Use a more uniform representation for this. 11237 for (auto *SE : POE->semantics()) 11238 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11239 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 11240 } 11241 11242 // Skip past explicit casts. 11243 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11244 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11245 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11246 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11247 return AnalyzeImplicitConversions(S, E, CC); 11248 } 11249 11250 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11251 // Do a somewhat different check with comparison operators. 11252 if (BO->isComparisonOp()) 11253 return AnalyzeComparison(S, BO); 11254 11255 // And with simple assignments. 11256 if (BO->getOpcode() == BO_Assign) 11257 return AnalyzeAssignment(S, BO); 11258 // And with compound assignments. 11259 if (BO->isAssignmentOp()) 11260 return AnalyzeCompoundAssignment(S, BO); 11261 } 11262 11263 // These break the otherwise-useful invariant below. Fortunately, 11264 // we don't really need to recurse into them, because any internal 11265 // expressions should have been analyzed already when they were 11266 // built into statements. 11267 if (isa<StmtExpr>(E)) return; 11268 11269 // Don't descend into unevaluated contexts. 11270 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11271 11272 // Now just recurse over the expression's children. 11273 CC = E->getExprLoc(); 11274 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11275 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11276 for (Stmt *SubStmt : E->children()) { 11277 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11278 if (!ChildExpr) 11279 continue; 11280 11281 if (IsLogicalAndOperator && 11282 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11283 // Ignore checking string literals that are in logical and operators. 11284 // This is a common pattern for asserts. 11285 continue; 11286 AnalyzeImplicitConversions(S, ChildExpr, CC); 11287 } 11288 11289 if (BO && BO->isLogicalOp()) { 11290 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11291 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11292 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11293 11294 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11295 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11296 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11297 } 11298 11299 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 11300 if (U->getOpcode() == UO_LNot) { 11301 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11302 } else if (U->getOpcode() != UO_AddrOf) { 11303 if (U->getSubExpr()->getType()->isAtomicType()) 11304 S.Diag(U->getSubExpr()->getBeginLoc(), 11305 diag::warn_atomic_implicit_seq_cst); 11306 } 11307 } 11308 } 11309 11310 /// Diagnose integer type and any valid implicit conversion to it. 11311 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 11312 // Taking into account implicit conversions, 11313 // allow any integer. 11314 if (!E->getType()->isIntegerType()) { 11315 S.Diag(E->getBeginLoc(), 11316 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 11317 return true; 11318 } 11319 // Potentially emit standard warnings for implicit conversions if enabled 11320 // using -Wconversion. 11321 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 11322 return false; 11323 } 11324 11325 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 11326 // Returns true when emitting a warning about taking the address of a reference. 11327 static bool CheckForReference(Sema &SemaRef, const Expr *E, 11328 const PartialDiagnostic &PD) { 11329 E = E->IgnoreParenImpCasts(); 11330 11331 const FunctionDecl *FD = nullptr; 11332 11333 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11334 if (!DRE->getDecl()->getType()->isReferenceType()) 11335 return false; 11336 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11337 if (!M->getMemberDecl()->getType()->isReferenceType()) 11338 return false; 11339 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 11340 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 11341 return false; 11342 FD = Call->getDirectCallee(); 11343 } else { 11344 return false; 11345 } 11346 11347 SemaRef.Diag(E->getExprLoc(), PD); 11348 11349 // If possible, point to location of function. 11350 if (FD) { 11351 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 11352 } 11353 11354 return true; 11355 } 11356 11357 // Returns true if the SourceLocation is expanded from any macro body. 11358 // Returns false if the SourceLocation is invalid, is from not in a macro 11359 // expansion, or is from expanded from a top-level macro argument. 11360 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 11361 if (Loc.isInvalid()) 11362 return false; 11363 11364 while (Loc.isMacroID()) { 11365 if (SM.isMacroBodyExpansion(Loc)) 11366 return true; 11367 Loc = SM.getImmediateMacroCallerLoc(Loc); 11368 } 11369 11370 return false; 11371 } 11372 11373 /// Diagnose pointers that are always non-null. 11374 /// \param E the expression containing the pointer 11375 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 11376 /// compared to a null pointer 11377 /// \param IsEqual True when the comparison is equal to a null pointer 11378 /// \param Range Extra SourceRange to highlight in the diagnostic 11379 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 11380 Expr::NullPointerConstantKind NullKind, 11381 bool IsEqual, SourceRange Range) { 11382 if (!E) 11383 return; 11384 11385 // Don't warn inside macros. 11386 if (E->getExprLoc().isMacroID()) { 11387 const SourceManager &SM = getSourceManager(); 11388 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 11389 IsInAnyMacroBody(SM, Range.getBegin())) 11390 return; 11391 } 11392 E = E->IgnoreImpCasts(); 11393 11394 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 11395 11396 if (isa<CXXThisExpr>(E)) { 11397 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 11398 : diag::warn_this_bool_conversion; 11399 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 11400 return; 11401 } 11402 11403 bool IsAddressOf = false; 11404 11405 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11406 if (UO->getOpcode() != UO_AddrOf) 11407 return; 11408 IsAddressOf = true; 11409 E = UO->getSubExpr(); 11410 } 11411 11412 if (IsAddressOf) { 11413 unsigned DiagID = IsCompare 11414 ? diag::warn_address_of_reference_null_compare 11415 : diag::warn_address_of_reference_bool_conversion; 11416 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 11417 << IsEqual; 11418 if (CheckForReference(*this, E, PD)) { 11419 return; 11420 } 11421 } 11422 11423 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 11424 bool IsParam = isa<NonNullAttr>(NonnullAttr); 11425 std::string Str; 11426 llvm::raw_string_ostream S(Str); 11427 E->printPretty(S, nullptr, getPrintingPolicy()); 11428 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 11429 : diag::warn_cast_nonnull_to_bool; 11430 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 11431 << E->getSourceRange() << Range << IsEqual; 11432 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 11433 }; 11434 11435 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 11436 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 11437 if (auto *Callee = Call->getDirectCallee()) { 11438 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 11439 ComplainAboutNonnullParamOrCall(A); 11440 return; 11441 } 11442 } 11443 } 11444 11445 // Expect to find a single Decl. Skip anything more complicated. 11446 ValueDecl *D = nullptr; 11447 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 11448 D = R->getDecl(); 11449 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11450 D = M->getMemberDecl(); 11451 } 11452 11453 // Weak Decls can be null. 11454 if (!D || D->isWeak()) 11455 return; 11456 11457 // Check for parameter decl with nonnull attribute 11458 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 11459 if (getCurFunction() && 11460 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 11461 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 11462 ComplainAboutNonnullParamOrCall(A); 11463 return; 11464 } 11465 11466 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 11467 auto ParamIter = llvm::find(FD->parameters(), PV); 11468 assert(ParamIter != FD->param_end()); 11469 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 11470 11471 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 11472 if (!NonNull->args_size()) { 11473 ComplainAboutNonnullParamOrCall(NonNull); 11474 return; 11475 } 11476 11477 for (const ParamIdx &ArgNo : NonNull->args()) { 11478 if (ArgNo.getASTIndex() == ParamNo) { 11479 ComplainAboutNonnullParamOrCall(NonNull); 11480 return; 11481 } 11482 } 11483 } 11484 } 11485 } 11486 } 11487 11488 QualType T = D->getType(); 11489 const bool IsArray = T->isArrayType(); 11490 const bool IsFunction = T->isFunctionType(); 11491 11492 // Address of function is used to silence the function warning. 11493 if (IsAddressOf && IsFunction) { 11494 return; 11495 } 11496 11497 // Found nothing. 11498 if (!IsAddressOf && !IsFunction && !IsArray) 11499 return; 11500 11501 // Pretty print the expression for the diagnostic. 11502 std::string Str; 11503 llvm::raw_string_ostream S(Str); 11504 E->printPretty(S, nullptr, getPrintingPolicy()); 11505 11506 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 11507 : diag::warn_impcast_pointer_to_bool; 11508 enum { 11509 AddressOf, 11510 FunctionPointer, 11511 ArrayPointer 11512 } DiagType; 11513 if (IsAddressOf) 11514 DiagType = AddressOf; 11515 else if (IsFunction) 11516 DiagType = FunctionPointer; 11517 else if (IsArray) 11518 DiagType = ArrayPointer; 11519 else 11520 llvm_unreachable("Could not determine diagnostic."); 11521 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 11522 << Range << IsEqual; 11523 11524 if (!IsFunction) 11525 return; 11526 11527 // Suggest '&' to silence the function warning. 11528 Diag(E->getExprLoc(), diag::note_function_warning_silence) 11529 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 11530 11531 // Check to see if '()' fixit should be emitted. 11532 QualType ReturnType; 11533 UnresolvedSet<4> NonTemplateOverloads; 11534 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 11535 if (ReturnType.isNull()) 11536 return; 11537 11538 if (IsCompare) { 11539 // There are two cases here. If there is null constant, the only suggest 11540 // for a pointer return type. If the null is 0, then suggest if the return 11541 // type is a pointer or an integer type. 11542 if (!ReturnType->isPointerType()) { 11543 if (NullKind == Expr::NPCK_ZeroExpression || 11544 NullKind == Expr::NPCK_ZeroLiteral) { 11545 if (!ReturnType->isIntegerType()) 11546 return; 11547 } else { 11548 return; 11549 } 11550 } 11551 } else { // !IsCompare 11552 // For function to bool, only suggest if the function pointer has bool 11553 // return type. 11554 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 11555 return; 11556 } 11557 Diag(E->getExprLoc(), diag::note_function_to_function_call) 11558 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 11559 } 11560 11561 /// Diagnoses "dangerous" implicit conversions within the given 11562 /// expression (which is a full expression). Implements -Wconversion 11563 /// and -Wsign-compare. 11564 /// 11565 /// \param CC the "context" location of the implicit conversion, i.e. 11566 /// the most location of the syntactic entity requiring the implicit 11567 /// conversion 11568 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 11569 // Don't diagnose in unevaluated contexts. 11570 if (isUnevaluatedContext()) 11571 return; 11572 11573 // Don't diagnose for value- or type-dependent expressions. 11574 if (E->isTypeDependent() || E->isValueDependent()) 11575 return; 11576 11577 // Check for array bounds violations in cases where the check isn't triggered 11578 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 11579 // ArraySubscriptExpr is on the RHS of a variable initialization. 11580 CheckArrayAccess(E); 11581 11582 // This is not the right CC for (e.g.) a variable initialization. 11583 AnalyzeImplicitConversions(*this, E, CC); 11584 } 11585 11586 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 11587 /// Input argument E is a logical expression. 11588 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 11589 ::CheckBoolLikeConversion(*this, E, CC); 11590 } 11591 11592 /// Diagnose when expression is an integer constant expression and its evaluation 11593 /// results in integer overflow 11594 void Sema::CheckForIntOverflow (Expr *E) { 11595 // Use a work list to deal with nested struct initializers. 11596 SmallVector<Expr *, 2> Exprs(1, E); 11597 11598 do { 11599 Expr *OriginalE = Exprs.pop_back_val(); 11600 Expr *E = OriginalE->IgnoreParenCasts(); 11601 11602 if (isa<BinaryOperator>(E)) { 11603 E->EvaluateForOverflow(Context); 11604 continue; 11605 } 11606 11607 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 11608 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 11609 else if (isa<ObjCBoxedExpr>(OriginalE)) 11610 E->EvaluateForOverflow(Context); 11611 else if (auto Call = dyn_cast<CallExpr>(E)) 11612 Exprs.append(Call->arg_begin(), Call->arg_end()); 11613 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 11614 Exprs.append(Message->arg_begin(), Message->arg_end()); 11615 } while (!Exprs.empty()); 11616 } 11617 11618 namespace { 11619 11620 /// Visitor for expressions which looks for unsequenced operations on the 11621 /// same object. 11622 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 11623 using Base = EvaluatedExprVisitor<SequenceChecker>; 11624 11625 /// A tree of sequenced regions within an expression. Two regions are 11626 /// unsequenced if one is an ancestor or a descendent of the other. When we 11627 /// finish processing an expression with sequencing, such as a comma 11628 /// expression, we fold its tree nodes into its parent, since they are 11629 /// unsequenced with respect to nodes we will visit later. 11630 class SequenceTree { 11631 struct Value { 11632 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 11633 unsigned Parent : 31; 11634 unsigned Merged : 1; 11635 }; 11636 SmallVector<Value, 8> Values; 11637 11638 public: 11639 /// A region within an expression which may be sequenced with respect 11640 /// to some other region. 11641 class Seq { 11642 friend class SequenceTree; 11643 11644 unsigned Index = 0; 11645 11646 explicit Seq(unsigned N) : Index(N) {} 11647 11648 public: 11649 Seq() = default; 11650 }; 11651 11652 SequenceTree() { Values.push_back(Value(0)); } 11653 Seq root() const { return Seq(0); } 11654 11655 /// Create a new sequence of operations, which is an unsequenced 11656 /// subset of \p Parent. This sequence of operations is sequenced with 11657 /// respect to other children of \p Parent. 11658 Seq allocate(Seq Parent) { 11659 Values.push_back(Value(Parent.Index)); 11660 return Seq(Values.size() - 1); 11661 } 11662 11663 /// Merge a sequence of operations into its parent. 11664 void merge(Seq S) { 11665 Values[S.Index].Merged = true; 11666 } 11667 11668 /// Determine whether two operations are unsequenced. This operation 11669 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 11670 /// should have been merged into its parent as appropriate. 11671 bool isUnsequenced(Seq Cur, Seq Old) { 11672 unsigned C = representative(Cur.Index); 11673 unsigned Target = representative(Old.Index); 11674 while (C >= Target) { 11675 if (C == Target) 11676 return true; 11677 C = Values[C].Parent; 11678 } 11679 return false; 11680 } 11681 11682 private: 11683 /// Pick a representative for a sequence. 11684 unsigned representative(unsigned K) { 11685 if (Values[K].Merged) 11686 // Perform path compression as we go. 11687 return Values[K].Parent = representative(Values[K].Parent); 11688 return K; 11689 } 11690 }; 11691 11692 /// An object for which we can track unsequenced uses. 11693 using Object = NamedDecl *; 11694 11695 /// Different flavors of object usage which we track. We only track the 11696 /// least-sequenced usage of each kind. 11697 enum UsageKind { 11698 /// A read of an object. Multiple unsequenced reads are OK. 11699 UK_Use, 11700 11701 /// A modification of an object which is sequenced before the value 11702 /// computation of the expression, such as ++n in C++. 11703 UK_ModAsValue, 11704 11705 /// A modification of an object which is not sequenced before the value 11706 /// computation of the expression, such as n++. 11707 UK_ModAsSideEffect, 11708 11709 UK_Count = UK_ModAsSideEffect + 1 11710 }; 11711 11712 struct Usage { 11713 Expr *Use = nullptr; 11714 SequenceTree::Seq Seq; 11715 11716 Usage() = default; 11717 }; 11718 11719 struct UsageInfo { 11720 Usage Uses[UK_Count]; 11721 11722 /// Have we issued a diagnostic for this variable already? 11723 bool Diagnosed = false; 11724 11725 UsageInfo() = default; 11726 }; 11727 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 11728 11729 Sema &SemaRef; 11730 11731 /// Sequenced regions within the expression. 11732 SequenceTree Tree; 11733 11734 /// Declaration modifications and references which we have seen. 11735 UsageInfoMap UsageMap; 11736 11737 /// The region we are currently within. 11738 SequenceTree::Seq Region; 11739 11740 /// Filled in with declarations which were modified as a side-effect 11741 /// (that is, post-increment operations). 11742 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 11743 11744 /// Expressions to check later. We defer checking these to reduce 11745 /// stack usage. 11746 SmallVectorImpl<Expr *> &WorkList; 11747 11748 /// RAII object wrapping the visitation of a sequenced subexpression of an 11749 /// expression. At the end of this process, the side-effects of the evaluation 11750 /// become sequenced with respect to the value computation of the result, so 11751 /// we downgrade any UK_ModAsSideEffect within the evaluation to 11752 /// UK_ModAsValue. 11753 struct SequencedSubexpression { 11754 SequencedSubexpression(SequenceChecker &Self) 11755 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 11756 Self.ModAsSideEffect = &ModAsSideEffect; 11757 } 11758 11759 ~SequencedSubexpression() { 11760 for (auto &M : llvm::reverse(ModAsSideEffect)) { 11761 UsageInfo &U = Self.UsageMap[M.first]; 11762 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 11763 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 11764 SideEffectUsage = M.second; 11765 } 11766 Self.ModAsSideEffect = OldModAsSideEffect; 11767 } 11768 11769 SequenceChecker &Self; 11770 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 11771 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 11772 }; 11773 11774 /// RAII object wrapping the visitation of a subexpression which we might 11775 /// choose to evaluate as a constant. If any subexpression is evaluated and 11776 /// found to be non-constant, this allows us to suppress the evaluation of 11777 /// the outer expression. 11778 class EvaluationTracker { 11779 public: 11780 EvaluationTracker(SequenceChecker &Self) 11781 : Self(Self), Prev(Self.EvalTracker) { 11782 Self.EvalTracker = this; 11783 } 11784 11785 ~EvaluationTracker() { 11786 Self.EvalTracker = Prev; 11787 if (Prev) 11788 Prev->EvalOK &= EvalOK; 11789 } 11790 11791 bool evaluate(const Expr *E, bool &Result) { 11792 if (!EvalOK || E->isValueDependent()) 11793 return false; 11794 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 11795 return EvalOK; 11796 } 11797 11798 private: 11799 SequenceChecker &Self; 11800 EvaluationTracker *Prev; 11801 bool EvalOK = true; 11802 } *EvalTracker = nullptr; 11803 11804 /// Find the object which is produced by the specified expression, 11805 /// if any. 11806 Object getObject(Expr *E, bool Mod) const { 11807 E = E->IgnoreParenCasts(); 11808 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11809 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 11810 return getObject(UO->getSubExpr(), Mod); 11811 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11812 if (BO->getOpcode() == BO_Comma) 11813 return getObject(BO->getRHS(), Mod); 11814 if (Mod && BO->isAssignmentOp()) 11815 return getObject(BO->getLHS(), Mod); 11816 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11817 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 11818 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 11819 return ME->getMemberDecl(); 11820 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11821 // FIXME: If this is a reference, map through to its value. 11822 return DRE->getDecl(); 11823 return nullptr; 11824 } 11825 11826 /// Note that an object was modified or used by an expression. 11827 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 11828 Usage &U = UI.Uses[UK]; 11829 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 11830 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 11831 ModAsSideEffect->push_back(std::make_pair(O, U)); 11832 U.Use = Ref; 11833 U.Seq = Region; 11834 } 11835 } 11836 11837 /// Check whether a modification or use conflicts with a prior usage. 11838 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 11839 bool IsModMod) { 11840 if (UI.Diagnosed) 11841 return; 11842 11843 const Usage &U = UI.Uses[OtherKind]; 11844 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 11845 return; 11846 11847 Expr *Mod = U.Use; 11848 Expr *ModOrUse = Ref; 11849 if (OtherKind == UK_Use) 11850 std::swap(Mod, ModOrUse); 11851 11852 SemaRef.Diag(Mod->getExprLoc(), 11853 IsModMod ? diag::warn_unsequenced_mod_mod 11854 : diag::warn_unsequenced_mod_use) 11855 << O << SourceRange(ModOrUse->getExprLoc()); 11856 UI.Diagnosed = true; 11857 } 11858 11859 void notePreUse(Object O, Expr *Use) { 11860 UsageInfo &U = UsageMap[O]; 11861 // Uses conflict with other modifications. 11862 checkUsage(O, U, Use, UK_ModAsValue, false); 11863 } 11864 11865 void notePostUse(Object O, Expr *Use) { 11866 UsageInfo &U = UsageMap[O]; 11867 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 11868 addUsage(U, O, Use, UK_Use); 11869 } 11870 11871 void notePreMod(Object O, Expr *Mod) { 11872 UsageInfo &U = UsageMap[O]; 11873 // Modifications conflict with other modifications and with uses. 11874 checkUsage(O, U, Mod, UK_ModAsValue, true); 11875 checkUsage(O, U, Mod, UK_Use, false); 11876 } 11877 11878 void notePostMod(Object O, Expr *Use, UsageKind UK) { 11879 UsageInfo &U = UsageMap[O]; 11880 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 11881 addUsage(U, O, Use, UK); 11882 } 11883 11884 public: 11885 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 11886 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 11887 Visit(E); 11888 } 11889 11890 void VisitStmt(Stmt *S) { 11891 // Skip all statements which aren't expressions for now. 11892 } 11893 11894 void VisitExpr(Expr *E) { 11895 // By default, just recurse to evaluated subexpressions. 11896 Base::VisitStmt(E); 11897 } 11898 11899 void VisitCastExpr(CastExpr *E) { 11900 Object O = Object(); 11901 if (E->getCastKind() == CK_LValueToRValue) 11902 O = getObject(E->getSubExpr(), false); 11903 11904 if (O) 11905 notePreUse(O, E); 11906 VisitExpr(E); 11907 if (O) 11908 notePostUse(O, E); 11909 } 11910 11911 void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) { 11912 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 11913 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 11914 SequenceTree::Seq OldRegion = Region; 11915 11916 { 11917 SequencedSubexpression SeqBefore(*this); 11918 Region = BeforeRegion; 11919 Visit(SequencedBefore); 11920 } 11921 11922 Region = AfterRegion; 11923 Visit(SequencedAfter); 11924 11925 Region = OldRegion; 11926 11927 Tree.merge(BeforeRegion); 11928 Tree.merge(AfterRegion); 11929 } 11930 11931 void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) { 11932 // C++17 [expr.sub]p1: 11933 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 11934 // expression E1 is sequenced before the expression E2. 11935 if (SemaRef.getLangOpts().CPlusPlus17) 11936 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 11937 else 11938 Base::VisitStmt(ASE); 11939 } 11940 11941 void VisitBinComma(BinaryOperator *BO) { 11942 // C++11 [expr.comma]p1: 11943 // Every value computation and side effect associated with the left 11944 // expression is sequenced before every value computation and side 11945 // effect associated with the right expression. 11946 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 11947 } 11948 11949 void VisitBinAssign(BinaryOperator *BO) { 11950 // The modification is sequenced after the value computation of the LHS 11951 // and RHS, so check it before inspecting the operands and update the 11952 // map afterwards. 11953 Object O = getObject(BO->getLHS(), true); 11954 if (!O) 11955 return VisitExpr(BO); 11956 11957 notePreMod(O, BO); 11958 11959 // C++11 [expr.ass]p7: 11960 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 11961 // only once. 11962 // 11963 // Therefore, for a compound assignment operator, O is considered used 11964 // everywhere except within the evaluation of E1 itself. 11965 if (isa<CompoundAssignOperator>(BO)) 11966 notePreUse(O, BO); 11967 11968 Visit(BO->getLHS()); 11969 11970 if (isa<CompoundAssignOperator>(BO)) 11971 notePostUse(O, BO); 11972 11973 Visit(BO->getRHS()); 11974 11975 // C++11 [expr.ass]p1: 11976 // the assignment is sequenced [...] before the value computation of the 11977 // assignment expression. 11978 // C11 6.5.16/3 has no such rule. 11979 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11980 : UK_ModAsSideEffect); 11981 } 11982 11983 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 11984 VisitBinAssign(CAO); 11985 } 11986 11987 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11988 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11989 void VisitUnaryPreIncDec(UnaryOperator *UO) { 11990 Object O = getObject(UO->getSubExpr(), true); 11991 if (!O) 11992 return VisitExpr(UO); 11993 11994 notePreMod(O, UO); 11995 Visit(UO->getSubExpr()); 11996 // C++11 [expr.pre.incr]p1: 11997 // the expression ++x is equivalent to x+=1 11998 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11999 : UK_ModAsSideEffect); 12000 } 12001 12002 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12003 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12004 void VisitUnaryPostIncDec(UnaryOperator *UO) { 12005 Object O = getObject(UO->getSubExpr(), true); 12006 if (!O) 12007 return VisitExpr(UO); 12008 12009 notePreMod(O, UO); 12010 Visit(UO->getSubExpr()); 12011 notePostMod(O, UO, UK_ModAsSideEffect); 12012 } 12013 12014 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 12015 void VisitBinLOr(BinaryOperator *BO) { 12016 // The side-effects of the LHS of an '&&' are sequenced before the 12017 // value computation of the RHS, and hence before the value computation 12018 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 12019 // as if they were unconditionally sequenced. 12020 EvaluationTracker Eval(*this); 12021 { 12022 SequencedSubexpression Sequenced(*this); 12023 Visit(BO->getLHS()); 12024 } 12025 12026 bool Result; 12027 if (Eval.evaluate(BO->getLHS(), Result)) { 12028 if (!Result) 12029 Visit(BO->getRHS()); 12030 } else { 12031 // Check for unsequenced operations in the RHS, treating it as an 12032 // entirely separate evaluation. 12033 // 12034 // FIXME: If there are operations in the RHS which are unsequenced 12035 // with respect to operations outside the RHS, and those operations 12036 // are unconditionally evaluated, diagnose them. 12037 WorkList.push_back(BO->getRHS()); 12038 } 12039 } 12040 void VisitBinLAnd(BinaryOperator *BO) { 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 WorkList.push_back(BO->getRHS()); 12053 } 12054 } 12055 12056 // Only visit the condition, unless we can be sure which subexpression will 12057 // be chosen. 12058 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 12059 EvaluationTracker Eval(*this); 12060 { 12061 SequencedSubexpression Sequenced(*this); 12062 Visit(CO->getCond()); 12063 } 12064 12065 bool Result; 12066 if (Eval.evaluate(CO->getCond(), Result)) 12067 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 12068 else { 12069 WorkList.push_back(CO->getTrueExpr()); 12070 WorkList.push_back(CO->getFalseExpr()); 12071 } 12072 } 12073 12074 void VisitCallExpr(CallExpr *CE) { 12075 // C++11 [intro.execution]p15: 12076 // When calling a function [...], every value computation and side effect 12077 // associated with any argument expression, or with the postfix expression 12078 // designating the called function, is sequenced before execution of every 12079 // expression or statement in the body of the function [and thus before 12080 // the value computation of its result]. 12081 SequencedSubexpression Sequenced(*this); 12082 Base::VisitCallExpr(CE); 12083 12084 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 12085 } 12086 12087 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 12088 // This is a call, so all subexpressions are sequenced before the result. 12089 SequencedSubexpression Sequenced(*this); 12090 12091 if (!CCE->isListInitialization()) 12092 return VisitExpr(CCE); 12093 12094 // In C++11, list initializations are sequenced. 12095 SmallVector<SequenceTree::Seq, 32> Elts; 12096 SequenceTree::Seq Parent = Region; 12097 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 12098 E = CCE->arg_end(); 12099 I != E; ++I) { 12100 Region = Tree.allocate(Parent); 12101 Elts.push_back(Region); 12102 Visit(*I); 12103 } 12104 12105 // Forget that the initializers are sequenced. 12106 Region = Parent; 12107 for (unsigned I = 0; I < Elts.size(); ++I) 12108 Tree.merge(Elts[I]); 12109 } 12110 12111 void VisitInitListExpr(InitListExpr *ILE) { 12112 if (!SemaRef.getLangOpts().CPlusPlus11) 12113 return VisitExpr(ILE); 12114 12115 // In C++11, list initializations are sequenced. 12116 SmallVector<SequenceTree::Seq, 32> Elts; 12117 SequenceTree::Seq Parent = Region; 12118 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 12119 Expr *E = ILE->getInit(I); 12120 if (!E) continue; 12121 Region = Tree.allocate(Parent); 12122 Elts.push_back(Region); 12123 Visit(E); 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 12133 } // namespace 12134 12135 void Sema::CheckUnsequencedOperations(Expr *E) { 12136 SmallVector<Expr *, 8> WorkList; 12137 WorkList.push_back(E); 12138 while (!WorkList.empty()) { 12139 Expr *Item = WorkList.pop_back_val(); 12140 SequenceChecker(*this, Item, WorkList); 12141 } 12142 } 12143 12144 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 12145 bool IsConstexpr) { 12146 CheckImplicitConversions(E, CheckLoc); 12147 if (!E->isInstantiationDependent()) 12148 CheckUnsequencedOperations(E); 12149 if (!IsConstexpr && !E->isValueDependent()) 12150 CheckForIntOverflow(E); 12151 DiagnoseMisalignedMembers(); 12152 } 12153 12154 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 12155 FieldDecl *BitField, 12156 Expr *Init) { 12157 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 12158 } 12159 12160 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 12161 SourceLocation Loc) { 12162 if (!PType->isVariablyModifiedType()) 12163 return; 12164 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 12165 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 12166 return; 12167 } 12168 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 12169 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 12170 return; 12171 } 12172 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 12173 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 12174 return; 12175 } 12176 12177 const ArrayType *AT = S.Context.getAsArrayType(PType); 12178 if (!AT) 12179 return; 12180 12181 if (AT->getSizeModifier() != ArrayType::Star) { 12182 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 12183 return; 12184 } 12185 12186 S.Diag(Loc, diag::err_array_star_in_function_definition); 12187 } 12188 12189 /// CheckParmsForFunctionDef - Check that the parameters of the given 12190 /// function are appropriate for the definition of a function. This 12191 /// takes care of any checks that cannot be performed on the 12192 /// declaration itself, e.g., that the types of each of the function 12193 /// parameters are complete. 12194 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 12195 bool CheckParameterNames) { 12196 bool HasInvalidParm = false; 12197 for (ParmVarDecl *Param : Parameters) { 12198 // C99 6.7.5.3p4: the parameters in a parameter type list in a 12199 // function declarator that is part of a function definition of 12200 // that function shall not have incomplete type. 12201 // 12202 // This is also C++ [dcl.fct]p6. 12203 if (!Param->isInvalidDecl() && 12204 RequireCompleteType(Param->getLocation(), Param->getType(), 12205 diag::err_typecheck_decl_incomplete_type)) { 12206 Param->setInvalidDecl(); 12207 HasInvalidParm = true; 12208 } 12209 12210 // C99 6.9.1p5: If the declarator includes a parameter type list, the 12211 // declaration of each parameter shall include an identifier. 12212 if (CheckParameterNames && 12213 Param->getIdentifier() == nullptr && 12214 !Param->isImplicit() && 12215 !getLangOpts().CPlusPlus) 12216 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12217 12218 // C99 6.7.5.3p12: 12219 // If the function declarator is not part of a definition of that 12220 // function, parameters may have incomplete type and may use the [*] 12221 // notation in their sequences of declarator specifiers to specify 12222 // variable length array types. 12223 QualType PType = Param->getOriginalType(); 12224 // FIXME: This diagnostic should point the '[*]' if source-location 12225 // information is added for it. 12226 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 12227 12228 // If the parameter is a c++ class type and it has to be destructed in the 12229 // callee function, declare the destructor so that it can be called by the 12230 // callee function. Do not perform any direct access check on the dtor here. 12231 if (!Param->isInvalidDecl()) { 12232 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 12233 if (!ClassDecl->isInvalidDecl() && 12234 !ClassDecl->hasIrrelevantDestructor() && 12235 !ClassDecl->isDependentContext() && 12236 ClassDecl->isParamDestroyedInCallee()) { 12237 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12238 MarkFunctionReferenced(Param->getLocation(), Destructor); 12239 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 12240 } 12241 } 12242 } 12243 12244 // Parameters with the pass_object_size attribute only need to be marked 12245 // constant at function definitions. Because we lack information about 12246 // whether we're on a declaration or definition when we're instantiating the 12247 // attribute, we need to check for constness here. 12248 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 12249 if (!Param->getType().isConstQualified()) 12250 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 12251 << Attr->getSpelling() << 1; 12252 12253 // Check for parameter names shadowing fields from the class. 12254 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 12255 // The owning context for the parameter should be the function, but we 12256 // want to see if this function's declaration context is a record. 12257 DeclContext *DC = Param->getDeclContext(); 12258 if (DC && DC->isFunctionOrMethod()) { 12259 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 12260 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 12261 RD, /*DeclIsField*/ false); 12262 } 12263 } 12264 } 12265 12266 return HasInvalidParm; 12267 } 12268 12269 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 12270 /// or MemberExpr. 12271 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 12272 ASTContext &Context) { 12273 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 12274 return Context.getDeclAlign(DRE->getDecl()); 12275 12276 if (const auto *ME = dyn_cast<MemberExpr>(E)) 12277 return Context.getDeclAlign(ME->getMemberDecl()); 12278 12279 return TypeAlign; 12280 } 12281 12282 /// CheckCastAlign - Implements -Wcast-align, which warns when a 12283 /// pointer cast increases the alignment requirements. 12284 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 12285 // This is actually a lot of work to potentially be doing on every 12286 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 12287 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 12288 return; 12289 12290 // Ignore dependent types. 12291 if (T->isDependentType() || Op->getType()->isDependentType()) 12292 return; 12293 12294 // Require that the destination be a pointer type. 12295 const PointerType *DestPtr = T->getAs<PointerType>(); 12296 if (!DestPtr) return; 12297 12298 // If the destination has alignment 1, we're done. 12299 QualType DestPointee = DestPtr->getPointeeType(); 12300 if (DestPointee->isIncompleteType()) return; 12301 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 12302 if (DestAlign.isOne()) return; 12303 12304 // Require that the source be a pointer type. 12305 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 12306 if (!SrcPtr) return; 12307 QualType SrcPointee = SrcPtr->getPointeeType(); 12308 12309 // Whitelist casts from cv void*. We already implicitly 12310 // whitelisted casts to cv void*, since they have alignment 1. 12311 // Also whitelist casts involving incomplete types, which implicitly 12312 // includes 'void'. 12313 if (SrcPointee->isIncompleteType()) return; 12314 12315 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 12316 12317 if (auto *CE = dyn_cast<CastExpr>(Op)) { 12318 if (CE->getCastKind() == CK_ArrayToPointerDecay) 12319 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 12320 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 12321 if (UO->getOpcode() == UO_AddrOf) 12322 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 12323 } 12324 12325 if (SrcAlign >= DestAlign) return; 12326 12327 Diag(TRange.getBegin(), diag::warn_cast_align) 12328 << Op->getType() << T 12329 << static_cast<unsigned>(SrcAlign.getQuantity()) 12330 << static_cast<unsigned>(DestAlign.getQuantity()) 12331 << TRange << Op->getSourceRange(); 12332 } 12333 12334 /// Check whether this array fits the idiom of a size-one tail padded 12335 /// array member of a struct. 12336 /// 12337 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 12338 /// commonly used to emulate flexible arrays in C89 code. 12339 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 12340 const NamedDecl *ND) { 12341 if (Size != 1 || !ND) return false; 12342 12343 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 12344 if (!FD) return false; 12345 12346 // Don't consider sizes resulting from macro expansions or template argument 12347 // substitution to form C89 tail-padded arrays. 12348 12349 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 12350 while (TInfo) { 12351 TypeLoc TL = TInfo->getTypeLoc(); 12352 // Look through typedefs. 12353 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 12354 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 12355 TInfo = TDL->getTypeSourceInfo(); 12356 continue; 12357 } 12358 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 12359 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 12360 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 12361 return false; 12362 } 12363 break; 12364 } 12365 12366 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 12367 if (!RD) return false; 12368 if (RD->isUnion()) return false; 12369 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12370 if (!CRD->isStandardLayout()) return false; 12371 } 12372 12373 // See if this is the last field decl in the record. 12374 const Decl *D = FD; 12375 while ((D = D->getNextDeclInContext())) 12376 if (isa<FieldDecl>(D)) 12377 return false; 12378 return true; 12379 } 12380 12381 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 12382 const ArraySubscriptExpr *ASE, 12383 bool AllowOnePastEnd, bool IndexNegated) { 12384 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 12385 if (IndexExpr->isValueDependent()) 12386 return; 12387 12388 const Type *EffectiveType = 12389 BaseExpr->getType()->getPointeeOrArrayElementType(); 12390 BaseExpr = BaseExpr->IgnoreParenCasts(); 12391 const ConstantArrayType *ArrayTy = 12392 Context.getAsConstantArrayType(BaseExpr->getType()); 12393 12394 if (!ArrayTy) 12395 return; 12396 12397 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 12398 12399 Expr::EvalResult Result; 12400 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 12401 return; 12402 12403 llvm::APSInt index = Result.Val.getInt(); 12404 if (IndexNegated) 12405 index = -index; 12406 12407 const NamedDecl *ND = nullptr; 12408 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12409 ND = DRE->getDecl(); 12410 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12411 ND = ME->getMemberDecl(); 12412 12413 if (index.isUnsigned() || !index.isNegative()) { 12414 // It is possible that the type of the base expression after 12415 // IgnoreParenCasts is incomplete, even though the type of the base 12416 // expression before IgnoreParenCasts is complete (see PR39746 for an 12417 // example). In this case we have no information about whether the array 12418 // access exceeds the array bounds. However we can still diagnose an array 12419 // access which precedes the array bounds. 12420 if (BaseType->isIncompleteType()) 12421 return; 12422 12423 llvm::APInt size = ArrayTy->getSize(); 12424 if (!size.isStrictlyPositive()) 12425 return; 12426 12427 if (BaseType != EffectiveType) { 12428 // Make sure we're comparing apples to apples when comparing index to size 12429 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 12430 uint64_t array_typesize = Context.getTypeSize(BaseType); 12431 // Handle ptrarith_typesize being zero, such as when casting to void* 12432 if (!ptrarith_typesize) ptrarith_typesize = 1; 12433 if (ptrarith_typesize != array_typesize) { 12434 // There's a cast to a different size type involved 12435 uint64_t ratio = array_typesize / ptrarith_typesize; 12436 // TODO: Be smarter about handling cases where array_typesize is not a 12437 // multiple of ptrarith_typesize 12438 if (ptrarith_typesize * ratio == array_typesize) 12439 size *= llvm::APInt(size.getBitWidth(), ratio); 12440 } 12441 } 12442 12443 if (size.getBitWidth() > index.getBitWidth()) 12444 index = index.zext(size.getBitWidth()); 12445 else if (size.getBitWidth() < index.getBitWidth()) 12446 size = size.zext(index.getBitWidth()); 12447 12448 // For array subscripting the index must be less than size, but for pointer 12449 // arithmetic also allow the index (offset) to be equal to size since 12450 // computing the next address after the end of the array is legal and 12451 // commonly done e.g. in C++ iterators and range-based for loops. 12452 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 12453 return; 12454 12455 // Also don't warn for arrays of size 1 which are members of some 12456 // structure. These are often used to approximate flexible arrays in C89 12457 // code. 12458 if (IsTailPaddedMemberArray(*this, size, ND)) 12459 return; 12460 12461 // Suppress the warning if the subscript expression (as identified by the 12462 // ']' location) and the index expression are both from macro expansions 12463 // within a system header. 12464 if (ASE) { 12465 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 12466 ASE->getRBracketLoc()); 12467 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 12468 SourceLocation IndexLoc = 12469 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 12470 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 12471 return; 12472 } 12473 } 12474 12475 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 12476 if (ASE) 12477 DiagID = diag::warn_array_index_exceeds_bounds; 12478 12479 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12480 PDiag(DiagID) << index.toString(10, true) 12481 << size.toString(10, true) 12482 << (unsigned)size.getLimitedValue(~0U) 12483 << IndexExpr->getSourceRange()); 12484 } else { 12485 unsigned DiagID = diag::warn_array_index_precedes_bounds; 12486 if (!ASE) { 12487 DiagID = diag::warn_ptr_arith_precedes_bounds; 12488 if (index.isNegative()) index = -index; 12489 } 12490 12491 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12492 PDiag(DiagID) << index.toString(10, true) 12493 << IndexExpr->getSourceRange()); 12494 } 12495 12496 if (!ND) { 12497 // Try harder to find a NamedDecl to point at in the note. 12498 while (const ArraySubscriptExpr *ASE = 12499 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 12500 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 12501 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12502 ND = DRE->getDecl(); 12503 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12504 ND = ME->getMemberDecl(); 12505 } 12506 12507 if (ND) 12508 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 12509 PDiag(diag::note_array_index_out_of_bounds) 12510 << ND->getDeclName()); 12511 } 12512 12513 void Sema::CheckArrayAccess(const Expr *expr) { 12514 int AllowOnePastEnd = 0; 12515 while (expr) { 12516 expr = expr->IgnoreParenImpCasts(); 12517 switch (expr->getStmtClass()) { 12518 case Stmt::ArraySubscriptExprClass: { 12519 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 12520 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 12521 AllowOnePastEnd > 0); 12522 expr = ASE->getBase(); 12523 break; 12524 } 12525 case Stmt::MemberExprClass: { 12526 expr = cast<MemberExpr>(expr)->getBase(); 12527 break; 12528 } 12529 case Stmt::OMPArraySectionExprClass: { 12530 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 12531 if (ASE->getLowerBound()) 12532 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 12533 /*ASE=*/nullptr, AllowOnePastEnd > 0); 12534 return; 12535 } 12536 case Stmt::UnaryOperatorClass: { 12537 // Only unwrap the * and & unary operators 12538 const UnaryOperator *UO = cast<UnaryOperator>(expr); 12539 expr = UO->getSubExpr(); 12540 switch (UO->getOpcode()) { 12541 case UO_AddrOf: 12542 AllowOnePastEnd++; 12543 break; 12544 case UO_Deref: 12545 AllowOnePastEnd--; 12546 break; 12547 default: 12548 return; 12549 } 12550 break; 12551 } 12552 case Stmt::ConditionalOperatorClass: { 12553 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 12554 if (const Expr *lhs = cond->getLHS()) 12555 CheckArrayAccess(lhs); 12556 if (const Expr *rhs = cond->getRHS()) 12557 CheckArrayAccess(rhs); 12558 return; 12559 } 12560 case Stmt::CXXOperatorCallExprClass: { 12561 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 12562 for (const auto *Arg : OCE->arguments()) 12563 CheckArrayAccess(Arg); 12564 return; 12565 } 12566 default: 12567 return; 12568 } 12569 } 12570 } 12571 12572 //===--- CHECK: Objective-C retain cycles ----------------------------------// 12573 12574 namespace { 12575 12576 struct RetainCycleOwner { 12577 VarDecl *Variable = nullptr; 12578 SourceRange Range; 12579 SourceLocation Loc; 12580 bool Indirect = false; 12581 12582 RetainCycleOwner() = default; 12583 12584 void setLocsFrom(Expr *e) { 12585 Loc = e->getExprLoc(); 12586 Range = e->getSourceRange(); 12587 } 12588 }; 12589 12590 } // namespace 12591 12592 /// Consider whether capturing the given variable can possibly lead to 12593 /// a retain cycle. 12594 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 12595 // In ARC, it's captured strongly iff the variable has __strong 12596 // lifetime. In MRR, it's captured strongly if the variable is 12597 // __block and has an appropriate type. 12598 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12599 return false; 12600 12601 owner.Variable = var; 12602 if (ref) 12603 owner.setLocsFrom(ref); 12604 return true; 12605 } 12606 12607 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 12608 while (true) { 12609 e = e->IgnoreParens(); 12610 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 12611 switch (cast->getCastKind()) { 12612 case CK_BitCast: 12613 case CK_LValueBitCast: 12614 case CK_LValueToRValue: 12615 case CK_ARCReclaimReturnedObject: 12616 e = cast->getSubExpr(); 12617 continue; 12618 12619 default: 12620 return false; 12621 } 12622 } 12623 12624 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 12625 ObjCIvarDecl *ivar = ref->getDecl(); 12626 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12627 return false; 12628 12629 // Try to find a retain cycle in the base. 12630 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 12631 return false; 12632 12633 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 12634 owner.Indirect = true; 12635 return true; 12636 } 12637 12638 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 12639 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 12640 if (!var) return false; 12641 return considerVariable(var, ref, owner); 12642 } 12643 12644 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 12645 if (member->isArrow()) return false; 12646 12647 // Don't count this as an indirect ownership. 12648 e = member->getBase(); 12649 continue; 12650 } 12651 12652 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 12653 // Only pay attention to pseudo-objects on property references. 12654 ObjCPropertyRefExpr *pre 12655 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 12656 ->IgnoreParens()); 12657 if (!pre) return false; 12658 if (pre->isImplicitProperty()) return false; 12659 ObjCPropertyDecl *property = pre->getExplicitProperty(); 12660 if (!property->isRetaining() && 12661 !(property->getPropertyIvarDecl() && 12662 property->getPropertyIvarDecl()->getType() 12663 .getObjCLifetime() == Qualifiers::OCL_Strong)) 12664 return false; 12665 12666 owner.Indirect = true; 12667 if (pre->isSuperReceiver()) { 12668 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 12669 if (!owner.Variable) 12670 return false; 12671 owner.Loc = pre->getLocation(); 12672 owner.Range = pre->getSourceRange(); 12673 return true; 12674 } 12675 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 12676 ->getSourceExpr()); 12677 continue; 12678 } 12679 12680 // Array ivars? 12681 12682 return false; 12683 } 12684 } 12685 12686 namespace { 12687 12688 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 12689 ASTContext &Context; 12690 VarDecl *Variable; 12691 Expr *Capturer = nullptr; 12692 bool VarWillBeReased = false; 12693 12694 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 12695 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 12696 Context(Context), Variable(variable) {} 12697 12698 void VisitDeclRefExpr(DeclRefExpr *ref) { 12699 if (ref->getDecl() == Variable && !Capturer) 12700 Capturer = ref; 12701 } 12702 12703 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 12704 if (Capturer) return; 12705 Visit(ref->getBase()); 12706 if (Capturer && ref->isFreeIvar()) 12707 Capturer = ref; 12708 } 12709 12710 void VisitBlockExpr(BlockExpr *block) { 12711 // Look inside nested blocks 12712 if (block->getBlockDecl()->capturesVariable(Variable)) 12713 Visit(block->getBlockDecl()->getBody()); 12714 } 12715 12716 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 12717 if (Capturer) return; 12718 if (OVE->getSourceExpr()) 12719 Visit(OVE->getSourceExpr()); 12720 } 12721 12722 void VisitBinaryOperator(BinaryOperator *BinOp) { 12723 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 12724 return; 12725 Expr *LHS = BinOp->getLHS(); 12726 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 12727 if (DRE->getDecl() != Variable) 12728 return; 12729 if (Expr *RHS = BinOp->getRHS()) { 12730 RHS = RHS->IgnoreParenCasts(); 12731 llvm::APSInt Value; 12732 VarWillBeReased = 12733 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 12734 } 12735 } 12736 } 12737 }; 12738 12739 } // namespace 12740 12741 /// Check whether the given argument is a block which captures a 12742 /// variable. 12743 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 12744 assert(owner.Variable && owner.Loc.isValid()); 12745 12746 e = e->IgnoreParenCasts(); 12747 12748 // Look through [^{...} copy] and Block_copy(^{...}). 12749 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 12750 Selector Cmd = ME->getSelector(); 12751 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 12752 e = ME->getInstanceReceiver(); 12753 if (!e) 12754 return nullptr; 12755 e = e->IgnoreParenCasts(); 12756 } 12757 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 12758 if (CE->getNumArgs() == 1) { 12759 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 12760 if (Fn) { 12761 const IdentifierInfo *FnI = Fn->getIdentifier(); 12762 if (FnI && FnI->isStr("_Block_copy")) { 12763 e = CE->getArg(0)->IgnoreParenCasts(); 12764 } 12765 } 12766 } 12767 } 12768 12769 BlockExpr *block = dyn_cast<BlockExpr>(e); 12770 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 12771 return nullptr; 12772 12773 FindCaptureVisitor visitor(S.Context, owner.Variable); 12774 visitor.Visit(block->getBlockDecl()->getBody()); 12775 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 12776 } 12777 12778 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 12779 RetainCycleOwner &owner) { 12780 assert(capturer); 12781 assert(owner.Variable && owner.Loc.isValid()); 12782 12783 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 12784 << owner.Variable << capturer->getSourceRange(); 12785 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 12786 << owner.Indirect << owner.Range; 12787 } 12788 12789 /// Check for a keyword selector that starts with the word 'add' or 12790 /// 'set'. 12791 static bool isSetterLikeSelector(Selector sel) { 12792 if (sel.isUnarySelector()) return false; 12793 12794 StringRef str = sel.getNameForSlot(0); 12795 while (!str.empty() && str.front() == '_') str = str.substr(1); 12796 if (str.startswith("set")) 12797 str = str.substr(3); 12798 else if (str.startswith("add")) { 12799 // Specially whitelist 'addOperationWithBlock:'. 12800 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 12801 return false; 12802 str = str.substr(3); 12803 } 12804 else 12805 return false; 12806 12807 if (str.empty()) return true; 12808 return !isLowercase(str.front()); 12809 } 12810 12811 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 12812 ObjCMessageExpr *Message) { 12813 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 12814 Message->getReceiverInterface(), 12815 NSAPI::ClassId_NSMutableArray); 12816 if (!IsMutableArray) { 12817 return None; 12818 } 12819 12820 Selector Sel = Message->getSelector(); 12821 12822 Optional<NSAPI::NSArrayMethodKind> MKOpt = 12823 S.NSAPIObj->getNSArrayMethodKind(Sel); 12824 if (!MKOpt) { 12825 return None; 12826 } 12827 12828 NSAPI::NSArrayMethodKind MK = *MKOpt; 12829 12830 switch (MK) { 12831 case NSAPI::NSMutableArr_addObject: 12832 case NSAPI::NSMutableArr_insertObjectAtIndex: 12833 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 12834 return 0; 12835 case NSAPI::NSMutableArr_replaceObjectAtIndex: 12836 return 1; 12837 12838 default: 12839 return None; 12840 } 12841 12842 return None; 12843 } 12844 12845 static 12846 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 12847 ObjCMessageExpr *Message) { 12848 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 12849 Message->getReceiverInterface(), 12850 NSAPI::ClassId_NSMutableDictionary); 12851 if (!IsMutableDictionary) { 12852 return None; 12853 } 12854 12855 Selector Sel = Message->getSelector(); 12856 12857 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 12858 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 12859 if (!MKOpt) { 12860 return None; 12861 } 12862 12863 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 12864 12865 switch (MK) { 12866 case NSAPI::NSMutableDict_setObjectForKey: 12867 case NSAPI::NSMutableDict_setValueForKey: 12868 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 12869 return 0; 12870 12871 default: 12872 return None; 12873 } 12874 12875 return None; 12876 } 12877 12878 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 12879 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 12880 Message->getReceiverInterface(), 12881 NSAPI::ClassId_NSMutableSet); 12882 12883 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 12884 Message->getReceiverInterface(), 12885 NSAPI::ClassId_NSMutableOrderedSet); 12886 if (!IsMutableSet && !IsMutableOrderedSet) { 12887 return None; 12888 } 12889 12890 Selector Sel = Message->getSelector(); 12891 12892 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 12893 if (!MKOpt) { 12894 return None; 12895 } 12896 12897 NSAPI::NSSetMethodKind MK = *MKOpt; 12898 12899 switch (MK) { 12900 case NSAPI::NSMutableSet_addObject: 12901 case NSAPI::NSOrderedSet_setObjectAtIndex: 12902 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 12903 case NSAPI::NSOrderedSet_insertObjectAtIndex: 12904 return 0; 12905 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 12906 return 1; 12907 } 12908 12909 return None; 12910 } 12911 12912 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 12913 if (!Message->isInstanceMessage()) { 12914 return; 12915 } 12916 12917 Optional<int> ArgOpt; 12918 12919 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 12920 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 12921 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 12922 return; 12923 } 12924 12925 int ArgIndex = *ArgOpt; 12926 12927 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 12928 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 12929 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 12930 } 12931 12932 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 12933 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12934 if (ArgRE->isObjCSelfExpr()) { 12935 Diag(Message->getSourceRange().getBegin(), 12936 diag::warn_objc_circular_container) 12937 << ArgRE->getDecl() << StringRef("'super'"); 12938 } 12939 } 12940 } else { 12941 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 12942 12943 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 12944 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 12945 } 12946 12947 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 12948 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12949 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 12950 ValueDecl *Decl = ReceiverRE->getDecl(); 12951 Diag(Message->getSourceRange().getBegin(), 12952 diag::warn_objc_circular_container) 12953 << Decl << Decl; 12954 if (!ArgRE->isObjCSelfExpr()) { 12955 Diag(Decl->getLocation(), 12956 diag::note_objc_circular_container_declared_here) 12957 << Decl; 12958 } 12959 } 12960 } 12961 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 12962 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 12963 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 12964 ObjCIvarDecl *Decl = IvarRE->getDecl(); 12965 Diag(Message->getSourceRange().getBegin(), 12966 diag::warn_objc_circular_container) 12967 << Decl << Decl; 12968 Diag(Decl->getLocation(), 12969 diag::note_objc_circular_container_declared_here) 12970 << Decl; 12971 } 12972 } 12973 } 12974 } 12975 } 12976 12977 /// Check a message send to see if it's likely to cause a retain cycle. 12978 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 12979 // Only check instance methods whose selector looks like a setter. 12980 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 12981 return; 12982 12983 // Try to find a variable that the receiver is strongly owned by. 12984 RetainCycleOwner owner; 12985 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 12986 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 12987 return; 12988 } else { 12989 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 12990 owner.Variable = getCurMethodDecl()->getSelfDecl(); 12991 owner.Loc = msg->getSuperLoc(); 12992 owner.Range = msg->getSuperLoc(); 12993 } 12994 12995 // Check whether the receiver is captured by any of the arguments. 12996 const ObjCMethodDecl *MD = msg->getMethodDecl(); 12997 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 12998 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 12999 // noescape blocks should not be retained by the method. 13000 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 13001 continue; 13002 return diagnoseRetainCycle(*this, capturer, owner); 13003 } 13004 } 13005 } 13006 13007 /// Check a property assign to see if it's likely to cause a retain cycle. 13008 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 13009 RetainCycleOwner owner; 13010 if (!findRetainCycleOwner(*this, receiver, owner)) 13011 return; 13012 13013 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 13014 diagnoseRetainCycle(*this, capturer, owner); 13015 } 13016 13017 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 13018 RetainCycleOwner Owner; 13019 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 13020 return; 13021 13022 // Because we don't have an expression for the variable, we have to set the 13023 // location explicitly here. 13024 Owner.Loc = Var->getLocation(); 13025 Owner.Range = Var->getSourceRange(); 13026 13027 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 13028 diagnoseRetainCycle(*this, Capturer, Owner); 13029 } 13030 13031 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 13032 Expr *RHS, bool isProperty) { 13033 // Check if RHS is an Objective-C object literal, which also can get 13034 // immediately zapped in a weak reference. Note that we explicitly 13035 // allow ObjCStringLiterals, since those are designed to never really die. 13036 RHS = RHS->IgnoreParenImpCasts(); 13037 13038 // This enum needs to match with the 'select' in 13039 // warn_objc_arc_literal_assign (off-by-1). 13040 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 13041 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 13042 return false; 13043 13044 S.Diag(Loc, diag::warn_arc_literal_assign) 13045 << (unsigned) Kind 13046 << (isProperty ? 0 : 1) 13047 << RHS->getSourceRange(); 13048 13049 return true; 13050 } 13051 13052 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 13053 Qualifiers::ObjCLifetime LT, 13054 Expr *RHS, bool isProperty) { 13055 // Strip off any implicit cast added to get to the one ARC-specific. 13056 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13057 if (cast->getCastKind() == CK_ARCConsumeObject) { 13058 S.Diag(Loc, diag::warn_arc_retained_assign) 13059 << (LT == Qualifiers::OCL_ExplicitNone) 13060 << (isProperty ? 0 : 1) 13061 << RHS->getSourceRange(); 13062 return true; 13063 } 13064 RHS = cast->getSubExpr(); 13065 } 13066 13067 if (LT == Qualifiers::OCL_Weak && 13068 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 13069 return true; 13070 13071 return false; 13072 } 13073 13074 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 13075 QualType LHS, Expr *RHS) { 13076 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 13077 13078 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 13079 return false; 13080 13081 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 13082 return true; 13083 13084 return false; 13085 } 13086 13087 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 13088 Expr *LHS, Expr *RHS) { 13089 QualType LHSType; 13090 // PropertyRef on LHS type need be directly obtained from 13091 // its declaration as it has a PseudoType. 13092 ObjCPropertyRefExpr *PRE 13093 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 13094 if (PRE && !PRE->isImplicitProperty()) { 13095 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13096 if (PD) 13097 LHSType = PD->getType(); 13098 } 13099 13100 if (LHSType.isNull()) 13101 LHSType = LHS->getType(); 13102 13103 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 13104 13105 if (LT == Qualifiers::OCL_Weak) { 13106 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 13107 getCurFunction()->markSafeWeakUse(LHS); 13108 } 13109 13110 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 13111 return; 13112 13113 // FIXME. Check for other life times. 13114 if (LT != Qualifiers::OCL_None) 13115 return; 13116 13117 if (PRE) { 13118 if (PRE->isImplicitProperty()) 13119 return; 13120 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13121 if (!PD) 13122 return; 13123 13124 unsigned Attributes = PD->getPropertyAttributes(); 13125 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 13126 // when 'assign' attribute was not explicitly specified 13127 // by user, ignore it and rely on property type itself 13128 // for lifetime info. 13129 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 13130 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 13131 LHSType->isObjCRetainableType()) 13132 return; 13133 13134 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13135 if (cast->getCastKind() == CK_ARCConsumeObject) { 13136 Diag(Loc, diag::warn_arc_retained_property_assign) 13137 << RHS->getSourceRange(); 13138 return; 13139 } 13140 RHS = cast->getSubExpr(); 13141 } 13142 } 13143 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 13144 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 13145 return; 13146 } 13147 } 13148 } 13149 13150 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 13151 13152 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 13153 SourceLocation StmtLoc, 13154 const NullStmt *Body) { 13155 // Do not warn if the body is a macro that expands to nothing, e.g: 13156 // 13157 // #define CALL(x) 13158 // if (condition) 13159 // CALL(0); 13160 if (Body->hasLeadingEmptyMacro()) 13161 return false; 13162 13163 // Get line numbers of statement and body. 13164 bool StmtLineInvalid; 13165 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 13166 &StmtLineInvalid); 13167 if (StmtLineInvalid) 13168 return false; 13169 13170 bool BodyLineInvalid; 13171 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 13172 &BodyLineInvalid); 13173 if (BodyLineInvalid) 13174 return false; 13175 13176 // Warn if null statement and body are on the same line. 13177 if (StmtLine != BodyLine) 13178 return false; 13179 13180 return true; 13181 } 13182 13183 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 13184 const Stmt *Body, 13185 unsigned DiagID) { 13186 // Since this is a syntactic check, don't emit diagnostic for template 13187 // instantiations, this just adds noise. 13188 if (CurrentInstantiationScope) 13189 return; 13190 13191 // The body should be a null statement. 13192 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13193 if (!NBody) 13194 return; 13195 13196 // Do the usual checks. 13197 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13198 return; 13199 13200 Diag(NBody->getSemiLoc(), DiagID); 13201 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13202 } 13203 13204 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 13205 const Stmt *PossibleBody) { 13206 assert(!CurrentInstantiationScope); // Ensured by caller 13207 13208 SourceLocation StmtLoc; 13209 const Stmt *Body; 13210 unsigned DiagID; 13211 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 13212 StmtLoc = FS->getRParenLoc(); 13213 Body = FS->getBody(); 13214 DiagID = diag::warn_empty_for_body; 13215 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 13216 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 13217 Body = WS->getBody(); 13218 DiagID = diag::warn_empty_while_body; 13219 } else 13220 return; // Neither `for' nor `while'. 13221 13222 // The body should be a null statement. 13223 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13224 if (!NBody) 13225 return; 13226 13227 // Skip expensive checks if diagnostic is disabled. 13228 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 13229 return; 13230 13231 // Do the usual checks. 13232 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13233 return; 13234 13235 // `for(...);' and `while(...);' are popular idioms, so in order to keep 13236 // noise level low, emit diagnostics only if for/while is followed by a 13237 // CompoundStmt, e.g.: 13238 // for (int i = 0; i < n; i++); 13239 // { 13240 // a(i); 13241 // } 13242 // or if for/while is followed by a statement with more indentation 13243 // than for/while itself: 13244 // for (int i = 0; i < n; i++); 13245 // a(i); 13246 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 13247 if (!ProbableTypo) { 13248 bool BodyColInvalid; 13249 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 13250 PossibleBody->getBeginLoc(), &BodyColInvalid); 13251 if (BodyColInvalid) 13252 return; 13253 13254 bool StmtColInvalid; 13255 unsigned StmtCol = 13256 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 13257 if (StmtColInvalid) 13258 return; 13259 13260 if (BodyCol > StmtCol) 13261 ProbableTypo = true; 13262 } 13263 13264 if (ProbableTypo) { 13265 Diag(NBody->getSemiLoc(), DiagID); 13266 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13267 } 13268 } 13269 13270 //===--- CHECK: Warn on self move with std::move. -------------------------===// 13271 13272 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 13273 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 13274 SourceLocation OpLoc) { 13275 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 13276 return; 13277 13278 if (inTemplateInstantiation()) 13279 return; 13280 13281 // Strip parens and casts away. 13282 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13283 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13284 13285 // Check for a call expression 13286 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 13287 if (!CE || CE->getNumArgs() != 1) 13288 return; 13289 13290 // Check for a call to std::move 13291 if (!CE->isCallToStdMove()) 13292 return; 13293 13294 // Get argument from std::move 13295 RHSExpr = CE->getArg(0); 13296 13297 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13298 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13299 13300 // Two DeclRefExpr's, check that the decls are the same. 13301 if (LHSDeclRef && RHSDeclRef) { 13302 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13303 return; 13304 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13305 RHSDeclRef->getDecl()->getCanonicalDecl()) 13306 return; 13307 13308 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13309 << LHSExpr->getSourceRange() 13310 << RHSExpr->getSourceRange(); 13311 return; 13312 } 13313 13314 // Member variables require a different approach to check for self moves. 13315 // MemberExpr's are the same if every nested MemberExpr refers to the same 13316 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 13317 // the base Expr's are CXXThisExpr's. 13318 const Expr *LHSBase = LHSExpr; 13319 const Expr *RHSBase = RHSExpr; 13320 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 13321 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 13322 if (!LHSME || !RHSME) 13323 return; 13324 13325 while (LHSME && RHSME) { 13326 if (LHSME->getMemberDecl()->getCanonicalDecl() != 13327 RHSME->getMemberDecl()->getCanonicalDecl()) 13328 return; 13329 13330 LHSBase = LHSME->getBase(); 13331 RHSBase = RHSME->getBase(); 13332 LHSME = dyn_cast<MemberExpr>(LHSBase); 13333 RHSME = dyn_cast<MemberExpr>(RHSBase); 13334 } 13335 13336 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 13337 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 13338 if (LHSDeclRef && RHSDeclRef) { 13339 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13340 return; 13341 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13342 RHSDeclRef->getDecl()->getCanonicalDecl()) 13343 return; 13344 13345 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13346 << LHSExpr->getSourceRange() 13347 << RHSExpr->getSourceRange(); 13348 return; 13349 } 13350 13351 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 13352 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13353 << LHSExpr->getSourceRange() 13354 << RHSExpr->getSourceRange(); 13355 } 13356 13357 //===--- Layout compatibility ----------------------------------------------// 13358 13359 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 13360 13361 /// Check if two enumeration types are layout-compatible. 13362 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 13363 // C++11 [dcl.enum] p8: 13364 // Two enumeration types are layout-compatible if they have the same 13365 // underlying type. 13366 return ED1->isComplete() && ED2->isComplete() && 13367 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 13368 } 13369 13370 /// Check if two fields are layout-compatible. 13371 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 13372 FieldDecl *Field2) { 13373 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 13374 return false; 13375 13376 if (Field1->isBitField() != Field2->isBitField()) 13377 return false; 13378 13379 if (Field1->isBitField()) { 13380 // Make sure that the bit-fields are the same length. 13381 unsigned Bits1 = Field1->getBitWidthValue(C); 13382 unsigned Bits2 = Field2->getBitWidthValue(C); 13383 13384 if (Bits1 != Bits2) 13385 return false; 13386 } 13387 13388 return true; 13389 } 13390 13391 /// Check if two standard-layout structs are layout-compatible. 13392 /// (C++11 [class.mem] p17) 13393 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 13394 RecordDecl *RD2) { 13395 // If both records are C++ classes, check that base classes match. 13396 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 13397 // If one of records is a CXXRecordDecl we are in C++ mode, 13398 // thus the other one is a CXXRecordDecl, too. 13399 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 13400 // Check number of base classes. 13401 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 13402 return false; 13403 13404 // Check the base classes. 13405 for (CXXRecordDecl::base_class_const_iterator 13406 Base1 = D1CXX->bases_begin(), 13407 BaseEnd1 = D1CXX->bases_end(), 13408 Base2 = D2CXX->bases_begin(); 13409 Base1 != BaseEnd1; 13410 ++Base1, ++Base2) { 13411 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 13412 return false; 13413 } 13414 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 13415 // If only RD2 is a C++ class, it should have zero base classes. 13416 if (D2CXX->getNumBases() > 0) 13417 return false; 13418 } 13419 13420 // Check the fields. 13421 RecordDecl::field_iterator Field2 = RD2->field_begin(), 13422 Field2End = RD2->field_end(), 13423 Field1 = RD1->field_begin(), 13424 Field1End = RD1->field_end(); 13425 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 13426 if (!isLayoutCompatible(C, *Field1, *Field2)) 13427 return false; 13428 } 13429 if (Field1 != Field1End || Field2 != Field2End) 13430 return false; 13431 13432 return true; 13433 } 13434 13435 /// Check if two standard-layout unions are layout-compatible. 13436 /// (C++11 [class.mem] p18) 13437 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 13438 RecordDecl *RD2) { 13439 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 13440 for (auto *Field2 : RD2->fields()) 13441 UnmatchedFields.insert(Field2); 13442 13443 for (auto *Field1 : RD1->fields()) { 13444 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 13445 I = UnmatchedFields.begin(), 13446 E = UnmatchedFields.end(); 13447 13448 for ( ; I != E; ++I) { 13449 if (isLayoutCompatible(C, Field1, *I)) { 13450 bool Result = UnmatchedFields.erase(*I); 13451 (void) Result; 13452 assert(Result); 13453 break; 13454 } 13455 } 13456 if (I == E) 13457 return false; 13458 } 13459 13460 return UnmatchedFields.empty(); 13461 } 13462 13463 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 13464 RecordDecl *RD2) { 13465 if (RD1->isUnion() != RD2->isUnion()) 13466 return false; 13467 13468 if (RD1->isUnion()) 13469 return isLayoutCompatibleUnion(C, RD1, RD2); 13470 else 13471 return isLayoutCompatibleStruct(C, RD1, RD2); 13472 } 13473 13474 /// Check if two types are layout-compatible in C++11 sense. 13475 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 13476 if (T1.isNull() || T2.isNull()) 13477 return false; 13478 13479 // C++11 [basic.types] p11: 13480 // If two types T1 and T2 are the same type, then T1 and T2 are 13481 // layout-compatible types. 13482 if (C.hasSameType(T1, T2)) 13483 return true; 13484 13485 T1 = T1.getCanonicalType().getUnqualifiedType(); 13486 T2 = T2.getCanonicalType().getUnqualifiedType(); 13487 13488 const Type::TypeClass TC1 = T1->getTypeClass(); 13489 const Type::TypeClass TC2 = T2->getTypeClass(); 13490 13491 if (TC1 != TC2) 13492 return false; 13493 13494 if (TC1 == Type::Enum) { 13495 return isLayoutCompatible(C, 13496 cast<EnumType>(T1)->getDecl(), 13497 cast<EnumType>(T2)->getDecl()); 13498 } else if (TC1 == Type::Record) { 13499 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 13500 return false; 13501 13502 return isLayoutCompatible(C, 13503 cast<RecordType>(T1)->getDecl(), 13504 cast<RecordType>(T2)->getDecl()); 13505 } 13506 13507 return false; 13508 } 13509 13510 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 13511 13512 /// Given a type tag expression find the type tag itself. 13513 /// 13514 /// \param TypeExpr Type tag expression, as it appears in user's code. 13515 /// 13516 /// \param VD Declaration of an identifier that appears in a type tag. 13517 /// 13518 /// \param MagicValue Type tag magic value. 13519 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 13520 const ValueDecl **VD, uint64_t *MagicValue) { 13521 while(true) { 13522 if (!TypeExpr) 13523 return false; 13524 13525 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 13526 13527 switch (TypeExpr->getStmtClass()) { 13528 case Stmt::UnaryOperatorClass: { 13529 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 13530 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 13531 TypeExpr = UO->getSubExpr(); 13532 continue; 13533 } 13534 return false; 13535 } 13536 13537 case Stmt::DeclRefExprClass: { 13538 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 13539 *VD = DRE->getDecl(); 13540 return true; 13541 } 13542 13543 case Stmt::IntegerLiteralClass: { 13544 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 13545 llvm::APInt MagicValueAPInt = IL->getValue(); 13546 if (MagicValueAPInt.getActiveBits() <= 64) { 13547 *MagicValue = MagicValueAPInt.getZExtValue(); 13548 return true; 13549 } else 13550 return false; 13551 } 13552 13553 case Stmt::BinaryConditionalOperatorClass: 13554 case Stmt::ConditionalOperatorClass: { 13555 const AbstractConditionalOperator *ACO = 13556 cast<AbstractConditionalOperator>(TypeExpr); 13557 bool Result; 13558 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 13559 if (Result) 13560 TypeExpr = ACO->getTrueExpr(); 13561 else 13562 TypeExpr = ACO->getFalseExpr(); 13563 continue; 13564 } 13565 return false; 13566 } 13567 13568 case Stmt::BinaryOperatorClass: { 13569 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 13570 if (BO->getOpcode() == BO_Comma) { 13571 TypeExpr = BO->getRHS(); 13572 continue; 13573 } 13574 return false; 13575 } 13576 13577 default: 13578 return false; 13579 } 13580 } 13581 } 13582 13583 /// Retrieve the C type corresponding to type tag TypeExpr. 13584 /// 13585 /// \param TypeExpr Expression that specifies a type tag. 13586 /// 13587 /// \param MagicValues Registered magic values. 13588 /// 13589 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 13590 /// kind. 13591 /// 13592 /// \param TypeInfo Information about the corresponding C type. 13593 /// 13594 /// \returns true if the corresponding C type was found. 13595 static bool GetMatchingCType( 13596 const IdentifierInfo *ArgumentKind, 13597 const Expr *TypeExpr, const ASTContext &Ctx, 13598 const llvm::DenseMap<Sema::TypeTagMagicValue, 13599 Sema::TypeTagData> *MagicValues, 13600 bool &FoundWrongKind, 13601 Sema::TypeTagData &TypeInfo) { 13602 FoundWrongKind = false; 13603 13604 // Variable declaration that has type_tag_for_datatype attribute. 13605 const ValueDecl *VD = nullptr; 13606 13607 uint64_t MagicValue; 13608 13609 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 13610 return false; 13611 13612 if (VD) { 13613 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 13614 if (I->getArgumentKind() != ArgumentKind) { 13615 FoundWrongKind = true; 13616 return false; 13617 } 13618 TypeInfo.Type = I->getMatchingCType(); 13619 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 13620 TypeInfo.MustBeNull = I->getMustBeNull(); 13621 return true; 13622 } 13623 return false; 13624 } 13625 13626 if (!MagicValues) 13627 return false; 13628 13629 llvm::DenseMap<Sema::TypeTagMagicValue, 13630 Sema::TypeTagData>::const_iterator I = 13631 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 13632 if (I == MagicValues->end()) 13633 return false; 13634 13635 TypeInfo = I->second; 13636 return true; 13637 } 13638 13639 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 13640 uint64_t MagicValue, QualType Type, 13641 bool LayoutCompatible, 13642 bool MustBeNull) { 13643 if (!TypeTagForDatatypeMagicValues) 13644 TypeTagForDatatypeMagicValues.reset( 13645 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 13646 13647 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 13648 (*TypeTagForDatatypeMagicValues)[Magic] = 13649 TypeTagData(Type, LayoutCompatible, MustBeNull); 13650 } 13651 13652 static bool IsSameCharType(QualType T1, QualType T2) { 13653 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 13654 if (!BT1) 13655 return false; 13656 13657 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 13658 if (!BT2) 13659 return false; 13660 13661 BuiltinType::Kind T1Kind = BT1->getKind(); 13662 BuiltinType::Kind T2Kind = BT2->getKind(); 13663 13664 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 13665 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 13666 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 13667 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 13668 } 13669 13670 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 13671 const ArrayRef<const Expr *> ExprArgs, 13672 SourceLocation CallSiteLoc) { 13673 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 13674 bool IsPointerAttr = Attr->getIsPointer(); 13675 13676 // Retrieve the argument representing the 'type_tag'. 13677 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 13678 if (TypeTagIdxAST >= ExprArgs.size()) { 13679 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 13680 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 13681 return; 13682 } 13683 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 13684 bool FoundWrongKind; 13685 TypeTagData TypeInfo; 13686 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 13687 TypeTagForDatatypeMagicValues.get(), 13688 FoundWrongKind, TypeInfo)) { 13689 if (FoundWrongKind) 13690 Diag(TypeTagExpr->getExprLoc(), 13691 diag::warn_type_tag_for_datatype_wrong_kind) 13692 << TypeTagExpr->getSourceRange(); 13693 return; 13694 } 13695 13696 // Retrieve the argument representing the 'arg_idx'. 13697 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 13698 if (ArgumentIdxAST >= ExprArgs.size()) { 13699 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 13700 << 1 << Attr->getArgumentIdx().getSourceIndex(); 13701 return; 13702 } 13703 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 13704 if (IsPointerAttr) { 13705 // Skip implicit cast of pointer to `void *' (as a function argument). 13706 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 13707 if (ICE->getType()->isVoidPointerType() && 13708 ICE->getCastKind() == CK_BitCast) 13709 ArgumentExpr = ICE->getSubExpr(); 13710 } 13711 QualType ArgumentType = ArgumentExpr->getType(); 13712 13713 // Passing a `void*' pointer shouldn't trigger a warning. 13714 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 13715 return; 13716 13717 if (TypeInfo.MustBeNull) { 13718 // Type tag with matching void type requires a null pointer. 13719 if (!ArgumentExpr->isNullPointerConstant(Context, 13720 Expr::NPC_ValueDependentIsNotNull)) { 13721 Diag(ArgumentExpr->getExprLoc(), 13722 diag::warn_type_safety_null_pointer_required) 13723 << ArgumentKind->getName() 13724 << ArgumentExpr->getSourceRange() 13725 << TypeTagExpr->getSourceRange(); 13726 } 13727 return; 13728 } 13729 13730 QualType RequiredType = TypeInfo.Type; 13731 if (IsPointerAttr) 13732 RequiredType = Context.getPointerType(RequiredType); 13733 13734 bool mismatch = false; 13735 if (!TypeInfo.LayoutCompatible) { 13736 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 13737 13738 // C++11 [basic.fundamental] p1: 13739 // Plain char, signed char, and unsigned char are three distinct types. 13740 // 13741 // But we treat plain `char' as equivalent to `signed char' or `unsigned 13742 // char' depending on the current char signedness mode. 13743 if (mismatch) 13744 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 13745 RequiredType->getPointeeType())) || 13746 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 13747 mismatch = false; 13748 } else 13749 if (IsPointerAttr) 13750 mismatch = !isLayoutCompatible(Context, 13751 ArgumentType->getPointeeType(), 13752 RequiredType->getPointeeType()); 13753 else 13754 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 13755 13756 if (mismatch) 13757 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 13758 << ArgumentType << ArgumentKind 13759 << TypeInfo.LayoutCompatible << RequiredType 13760 << ArgumentExpr->getSourceRange() 13761 << TypeTagExpr->getSourceRange(); 13762 } 13763 13764 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 13765 CharUnits Alignment) { 13766 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 13767 } 13768 13769 void Sema::DiagnoseMisalignedMembers() { 13770 for (MisalignedMember &m : MisalignedMembers) { 13771 const NamedDecl *ND = m.RD; 13772 if (ND->getName().empty()) { 13773 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 13774 ND = TD; 13775 } 13776 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 13777 << m.MD << ND << m.E->getSourceRange(); 13778 } 13779 MisalignedMembers.clear(); 13780 } 13781 13782 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 13783 E = E->IgnoreParens(); 13784 if (!T->isPointerType() && !T->isIntegerType()) 13785 return; 13786 if (isa<UnaryOperator>(E) && 13787 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 13788 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 13789 if (isa<MemberExpr>(Op)) { 13790 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 13791 MisalignedMember(Op)); 13792 if (MA != MisalignedMembers.end() && 13793 (T->isIntegerType() || 13794 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 13795 Context.getTypeAlignInChars( 13796 T->getPointeeType()) <= MA->Alignment)))) 13797 MisalignedMembers.erase(MA); 13798 } 13799 } 13800 } 13801 13802 void Sema::RefersToMemberWithReducedAlignment( 13803 Expr *E, 13804 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 13805 Action) { 13806 const auto *ME = dyn_cast<MemberExpr>(E); 13807 if (!ME) 13808 return; 13809 13810 // No need to check expressions with an __unaligned-qualified type. 13811 if (E->getType().getQualifiers().hasUnaligned()) 13812 return; 13813 13814 // For a chain of MemberExpr like "a.b.c.d" this list 13815 // will keep FieldDecl's like [d, c, b]. 13816 SmallVector<FieldDecl *, 4> ReverseMemberChain; 13817 const MemberExpr *TopME = nullptr; 13818 bool AnyIsPacked = false; 13819 do { 13820 QualType BaseType = ME->getBase()->getType(); 13821 if (ME->isArrow()) 13822 BaseType = BaseType->getPointeeType(); 13823 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 13824 if (RD->isInvalidDecl()) 13825 return; 13826 13827 ValueDecl *MD = ME->getMemberDecl(); 13828 auto *FD = dyn_cast<FieldDecl>(MD); 13829 // We do not care about non-data members. 13830 if (!FD || FD->isInvalidDecl()) 13831 return; 13832 13833 AnyIsPacked = 13834 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 13835 ReverseMemberChain.push_back(FD); 13836 13837 TopME = ME; 13838 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 13839 } while (ME); 13840 assert(TopME && "We did not compute a topmost MemberExpr!"); 13841 13842 // Not the scope of this diagnostic. 13843 if (!AnyIsPacked) 13844 return; 13845 13846 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 13847 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 13848 // TODO: The innermost base of the member expression may be too complicated. 13849 // For now, just disregard these cases. This is left for future 13850 // improvement. 13851 if (!DRE && !isa<CXXThisExpr>(TopBase)) 13852 return; 13853 13854 // Alignment expected by the whole expression. 13855 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 13856 13857 // No need to do anything else with this case. 13858 if (ExpectedAlignment.isOne()) 13859 return; 13860 13861 // Synthesize offset of the whole access. 13862 CharUnits Offset; 13863 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 13864 I++) { 13865 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 13866 } 13867 13868 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 13869 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 13870 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 13871 13872 // The base expression of the innermost MemberExpr may give 13873 // stronger guarantees than the class containing the member. 13874 if (DRE && !TopME->isArrow()) { 13875 const ValueDecl *VD = DRE->getDecl(); 13876 if (!VD->getType()->isReferenceType()) 13877 CompleteObjectAlignment = 13878 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 13879 } 13880 13881 // Check if the synthesized offset fulfills the alignment. 13882 if (Offset % ExpectedAlignment != 0 || 13883 // It may fulfill the offset it but the effective alignment may still be 13884 // lower than the expected expression alignment. 13885 CompleteObjectAlignment < ExpectedAlignment) { 13886 // If this happens, we want to determine a sensible culprit of this. 13887 // Intuitively, watching the chain of member expressions from right to 13888 // left, we start with the required alignment (as required by the field 13889 // type) but some packed attribute in that chain has reduced the alignment. 13890 // It may happen that another packed structure increases it again. But if 13891 // we are here such increase has not been enough. So pointing the first 13892 // FieldDecl that either is packed or else its RecordDecl is, 13893 // seems reasonable. 13894 FieldDecl *FD = nullptr; 13895 CharUnits Alignment; 13896 for (FieldDecl *FDI : ReverseMemberChain) { 13897 if (FDI->hasAttr<PackedAttr>() || 13898 FDI->getParent()->hasAttr<PackedAttr>()) { 13899 FD = FDI; 13900 Alignment = std::min( 13901 Context.getTypeAlignInChars(FD->getType()), 13902 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 13903 break; 13904 } 13905 } 13906 assert(FD && "We did not find a packed FieldDecl!"); 13907 Action(E, FD->getParent(), FD, Alignment); 13908 } 13909 } 13910 13911 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 13912 using namespace std::placeholders; 13913 13914 RefersToMemberWithReducedAlignment( 13915 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 13916 _2, _3, _4)); 13917 } 13918