1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements extra semantic analysis beyond what is enforced 11 // by the C type system. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/AST/APValue.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/AttrIterator.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclBase.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclarationName.h" 25 #include "clang/AST/EvaluatedExprVisitor.h" 26 #include "clang/AST/Expr.h" 27 #include "clang/AST/ExprCXX.h" 28 #include "clang/AST/ExprObjC.h" 29 #include "clang/AST/ExprOpenMP.h" 30 #include "clang/AST/FormatString.h" 31 #include "clang/AST/NSAPI.h" 32 #include "clang/AST/NonTrivialTypeVisitor.h" 33 #include "clang/AST/OperationKinds.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSwitch.h" 79 #include "llvm/ADT/Triple.h" 80 #include "llvm/Support/AtomicOrdering.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/ConvertUTF.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/Format.h" 86 #include "llvm/Support/Locale.h" 87 #include "llvm/Support/MathExtras.h" 88 #include "llvm/Support/raw_ostream.h" 89 #include <algorithm> 90 #include <cassert> 91 #include <cstddef> 92 #include <cstdint> 93 #include <functional> 94 #include <limits> 95 #include <string> 96 #include <tuple> 97 #include <utility> 98 99 using namespace clang; 100 using namespace sema; 101 102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 103 unsigned ByteNo) const { 104 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 105 Context.getTargetInfo()); 106 } 107 108 /// Checks that a call expression's argument count is the desired number. 109 /// This is useful when doing custom type-checking. Returns true on error. 110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 111 unsigned argCount = call->getNumArgs(); 112 if (argCount == desiredArgCount) return false; 113 114 if (argCount < desiredArgCount) 115 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 116 << 0 /*function call*/ << desiredArgCount << argCount 117 << call->getSourceRange(); 118 119 // Highlight all the excess arguments. 120 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 121 call->getArg(argCount - 1)->getEndLoc()); 122 123 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 124 << 0 /*function call*/ << desiredArgCount << argCount 125 << call->getArg(1)->getSourceRange(); 126 } 127 128 /// Check that the first argument to __builtin_annotation is an integer 129 /// and the second argument is a non-wide string literal. 130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 131 if (checkArgCount(S, TheCall, 2)) 132 return true; 133 134 // First argument should be an integer. 135 Expr *ValArg = TheCall->getArg(0); 136 QualType Ty = ValArg->getType(); 137 if (!Ty->isIntegerType()) { 138 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 139 << ValArg->getSourceRange(); 140 return true; 141 } 142 143 // Second argument should be a constant string. 144 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 145 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 146 if (!Literal || !Literal->isAscii()) { 147 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 148 << StrArg->getSourceRange(); 149 return true; 150 } 151 152 TheCall->setType(Ty); 153 return false; 154 } 155 156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 157 // We need at least one argument. 158 if (TheCall->getNumArgs() < 1) { 159 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 160 << 0 << 1 << TheCall->getNumArgs() 161 << TheCall->getCallee()->getSourceRange(); 162 return true; 163 } 164 165 // All arguments should be wide string literals. 166 for (Expr *Arg : TheCall->arguments()) { 167 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 168 if (!Literal || !Literal->isWide()) { 169 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 170 << Arg->getSourceRange(); 171 return true; 172 } 173 } 174 175 return false; 176 } 177 178 /// Check that the argument to __builtin_addressof is a glvalue, and set the 179 /// result type to the corresponding pointer type. 180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 181 if (checkArgCount(S, TheCall, 1)) 182 return true; 183 184 ExprResult Arg(TheCall->getArg(0)); 185 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 186 if (ResultType.isNull()) 187 return true; 188 189 TheCall->setArg(0, Arg.get()); 190 TheCall->setType(ResultType); 191 return false; 192 } 193 194 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 195 if (checkArgCount(S, TheCall, 3)) 196 return true; 197 198 // First two arguments should be integers. 199 for (unsigned I = 0; I < 2; ++I) { 200 ExprResult Arg = TheCall->getArg(I); 201 QualType Ty = Arg.get()->getType(); 202 if (!Ty->isIntegerType()) { 203 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 204 << Ty << Arg.get()->getSourceRange(); 205 return true; 206 } 207 InitializedEntity Entity = InitializedEntity::InitializeParameter( 208 S.getASTContext(), Ty, /*consume*/ false); 209 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 210 if (Arg.isInvalid()) 211 return true; 212 TheCall->setArg(I, Arg.get()); 213 } 214 215 // Third argument should be a pointer to a non-const integer. 216 // IRGen correctly handles volatile, restrict, and address spaces, and 217 // the other qualifiers aren't possible. 218 { 219 ExprResult Arg = TheCall->getArg(2); 220 QualType Ty = Arg.get()->getType(); 221 const auto *PtrTy = Ty->getAs<PointerType>(); 222 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 223 !PtrTy->getPointeeType().isConstQualified())) { 224 S.Diag(Arg.get()->getBeginLoc(), 225 diag::err_overflow_builtin_must_be_ptr_int) 226 << Ty << Arg.get()->getSourceRange(); 227 return true; 228 } 229 InitializedEntity Entity = InitializedEntity::InitializeParameter( 230 S.getASTContext(), Ty, /*consume*/ false); 231 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 232 if (Arg.isInvalid()) 233 return true; 234 TheCall->setArg(2, Arg.get()); 235 } 236 return false; 237 } 238 239 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 240 CallExpr *TheCall, unsigned SizeIdx, 241 unsigned DstSizeIdx, 242 StringRef LikelyMacroName) { 243 if (TheCall->getNumArgs() <= SizeIdx || 244 TheCall->getNumArgs() <= DstSizeIdx) 245 return; 246 247 const Expr *SizeArg = TheCall->getArg(SizeIdx); 248 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 249 250 Expr::EvalResult SizeResult, DstSizeResult; 251 252 // find out if both sizes are known at compile time 253 if (!SizeArg->EvaluateAsInt(SizeResult, S.Context) || 254 !DstSizeArg->EvaluateAsInt(DstSizeResult, S.Context)) 255 return; 256 257 llvm::APSInt Size = SizeResult.Val.getInt(); 258 llvm::APSInt DstSize = DstSizeResult.Val.getInt(); 259 260 if (Size.ule(DstSize)) 261 return; 262 263 // Confirmed overflow, so generate the diagnostic. 264 StringRef FunctionName = FDecl->getName(); 265 SourceLocation SL = TheCall->getBeginLoc(); 266 SourceManager &SM = S.getSourceManager(); 267 // If we're in an expansion of a macro whose name corresponds to this builtin, 268 // use the simple macro name and location. 269 if (SL.isMacroID() && Lexer::getImmediateMacroName(SL, SM, S.getLangOpts()) == 270 LikelyMacroName) { 271 FunctionName = LikelyMacroName; 272 SL = SM.getImmediateMacroCallerLoc(SL); 273 } 274 275 S.Diag(SL, diag::warn_memcpy_chk_overflow) 276 << FunctionName << DstSize.toString(/*Radix=*/10) 277 << Size.toString(/*Radix=*/10); 278 } 279 280 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 281 if (checkArgCount(S, BuiltinCall, 2)) 282 return true; 283 284 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 285 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 286 Expr *Call = BuiltinCall->getArg(0); 287 Expr *Chain = BuiltinCall->getArg(1); 288 289 if (Call->getStmtClass() != Stmt::CallExprClass) { 290 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 291 << Call->getSourceRange(); 292 return true; 293 } 294 295 auto CE = cast<CallExpr>(Call); 296 if (CE->getCallee()->getType()->isBlockPointerType()) { 297 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 298 << Call->getSourceRange(); 299 return true; 300 } 301 302 const Decl *TargetDecl = CE->getCalleeDecl(); 303 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 304 if (FD->getBuiltinID()) { 305 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 306 << Call->getSourceRange(); 307 return true; 308 } 309 310 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 311 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 312 << Call->getSourceRange(); 313 return true; 314 } 315 316 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 317 if (ChainResult.isInvalid()) 318 return true; 319 if (!ChainResult.get()->getType()->isPointerType()) { 320 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 321 << Chain->getSourceRange(); 322 return true; 323 } 324 325 QualType ReturnTy = CE->getCallReturnType(S.Context); 326 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 327 QualType BuiltinTy = S.Context.getFunctionType( 328 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 329 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 330 331 Builtin = 332 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 333 334 BuiltinCall->setType(CE->getType()); 335 BuiltinCall->setValueKind(CE->getValueKind()); 336 BuiltinCall->setObjectKind(CE->getObjectKind()); 337 BuiltinCall->setCallee(Builtin); 338 BuiltinCall->setArg(1, ChainResult.get()); 339 340 return false; 341 } 342 343 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 344 Scope::ScopeFlags NeededScopeFlags, 345 unsigned DiagID) { 346 // Scopes aren't available during instantiation. Fortunately, builtin 347 // functions cannot be template args so they cannot be formed through template 348 // instantiation. Therefore checking once during the parse is sufficient. 349 if (SemaRef.inTemplateInstantiation()) 350 return false; 351 352 Scope *S = SemaRef.getCurScope(); 353 while (S && !S->isSEHExceptScope()) 354 S = S->getParent(); 355 if (!S || !(S->getFlags() & NeededScopeFlags)) { 356 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 357 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 358 << DRE->getDecl()->getIdentifier(); 359 return true; 360 } 361 362 return false; 363 } 364 365 static inline bool isBlockPointer(Expr *Arg) { 366 return Arg->getType()->isBlockPointerType(); 367 } 368 369 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 370 /// void*, which is a requirement of device side enqueue. 371 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 372 const BlockPointerType *BPT = 373 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 374 ArrayRef<QualType> Params = 375 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 376 unsigned ArgCounter = 0; 377 bool IllegalParams = false; 378 // Iterate through the block parameters until either one is found that is not 379 // a local void*, or the block is valid. 380 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 381 I != E; ++I, ++ArgCounter) { 382 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 383 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 384 LangAS::opencl_local) { 385 // Get the location of the error. If a block literal has been passed 386 // (BlockExpr) then we can point straight to the offending argument, 387 // else we just point to the variable reference. 388 SourceLocation ErrorLoc; 389 if (isa<BlockExpr>(BlockArg)) { 390 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 391 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 392 } else if (isa<DeclRefExpr>(BlockArg)) { 393 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 394 } 395 S.Diag(ErrorLoc, 396 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 397 IllegalParams = true; 398 } 399 } 400 401 return IllegalParams; 402 } 403 404 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 405 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 406 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 407 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 408 return true; 409 } 410 return false; 411 } 412 413 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 414 if (checkArgCount(S, TheCall, 2)) 415 return true; 416 417 if (checkOpenCLSubgroupExt(S, TheCall)) 418 return true; 419 420 // First argument is an ndrange_t type. 421 Expr *NDRangeArg = TheCall->getArg(0); 422 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 423 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 424 << TheCall->getDirectCallee() << "'ndrange_t'"; 425 return true; 426 } 427 428 Expr *BlockArg = TheCall->getArg(1); 429 if (!isBlockPointer(BlockArg)) { 430 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 431 << TheCall->getDirectCallee() << "block"; 432 return true; 433 } 434 return checkOpenCLBlockArgs(S, BlockArg); 435 } 436 437 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 438 /// get_kernel_work_group_size 439 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 440 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 441 if (checkArgCount(S, TheCall, 1)) 442 return true; 443 444 Expr *BlockArg = TheCall->getArg(0); 445 if (!isBlockPointer(BlockArg)) { 446 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 447 << TheCall->getDirectCallee() << "block"; 448 return true; 449 } 450 return checkOpenCLBlockArgs(S, BlockArg); 451 } 452 453 /// Diagnose integer type and any valid implicit conversion to it. 454 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 455 const QualType &IntType); 456 457 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 458 unsigned Start, unsigned End) { 459 bool IllegalParams = false; 460 for (unsigned I = Start; I <= End; ++I) 461 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 462 S.Context.getSizeType()); 463 return IllegalParams; 464 } 465 466 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 467 /// 'local void*' parameter of passed block. 468 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 469 Expr *BlockArg, 470 unsigned NumNonVarArgs) { 471 const BlockPointerType *BPT = 472 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 473 unsigned NumBlockParams = 474 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 475 unsigned TotalNumArgs = TheCall->getNumArgs(); 476 477 // For each argument passed to the block, a corresponding uint needs to 478 // be passed to describe the size of the local memory. 479 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 480 S.Diag(TheCall->getBeginLoc(), 481 diag::err_opencl_enqueue_kernel_local_size_args); 482 return true; 483 } 484 485 // Check that the sizes of the local memory are specified by integers. 486 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 487 TotalNumArgs - 1); 488 } 489 490 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 491 /// overload formats specified in Table 6.13.17.1. 492 /// int enqueue_kernel(queue_t queue, 493 /// kernel_enqueue_flags_t flags, 494 /// const ndrange_t ndrange, 495 /// void (^block)(void)) 496 /// int enqueue_kernel(queue_t queue, 497 /// kernel_enqueue_flags_t flags, 498 /// const ndrange_t ndrange, 499 /// uint num_events_in_wait_list, 500 /// clk_event_t *event_wait_list, 501 /// clk_event_t *event_ret, 502 /// void (^block)(void)) 503 /// int enqueue_kernel(queue_t queue, 504 /// kernel_enqueue_flags_t flags, 505 /// const ndrange_t ndrange, 506 /// void (^block)(local void*, ...), 507 /// uint size0, ...) 508 /// int enqueue_kernel(queue_t queue, 509 /// kernel_enqueue_flags_t flags, 510 /// const ndrange_t ndrange, 511 /// uint num_events_in_wait_list, 512 /// clk_event_t *event_wait_list, 513 /// clk_event_t *event_ret, 514 /// void (^block)(local void*, ...), 515 /// uint size0, ...) 516 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 517 unsigned NumArgs = TheCall->getNumArgs(); 518 519 if (NumArgs < 4) { 520 S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args); 521 return true; 522 } 523 524 Expr *Arg0 = TheCall->getArg(0); 525 Expr *Arg1 = TheCall->getArg(1); 526 Expr *Arg2 = TheCall->getArg(2); 527 Expr *Arg3 = TheCall->getArg(3); 528 529 // First argument always needs to be a queue_t type. 530 if (!Arg0->getType()->isQueueT()) { 531 S.Diag(TheCall->getArg(0)->getBeginLoc(), 532 diag::err_opencl_builtin_expected_type) 533 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 534 return true; 535 } 536 537 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 538 if (!Arg1->getType()->isIntegerType()) { 539 S.Diag(TheCall->getArg(1)->getBeginLoc(), 540 diag::err_opencl_builtin_expected_type) 541 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 542 return true; 543 } 544 545 // Third argument is always an ndrange_t type. 546 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 547 S.Diag(TheCall->getArg(2)->getBeginLoc(), 548 diag::err_opencl_builtin_expected_type) 549 << TheCall->getDirectCallee() << "'ndrange_t'"; 550 return true; 551 } 552 553 // With four arguments, there is only one form that the function could be 554 // called in: no events and no variable arguments. 555 if (NumArgs == 4) { 556 // check that the last argument is the right block type. 557 if (!isBlockPointer(Arg3)) { 558 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 559 << TheCall->getDirectCallee() << "block"; 560 return true; 561 } 562 // we have a block type, check the prototype 563 const BlockPointerType *BPT = 564 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 565 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 566 S.Diag(Arg3->getBeginLoc(), 567 diag::err_opencl_enqueue_kernel_blocks_no_args); 568 return true; 569 } 570 return false; 571 } 572 // we can have block + varargs. 573 if (isBlockPointer(Arg3)) 574 return (checkOpenCLBlockArgs(S, Arg3) || 575 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 576 // last two cases with either exactly 7 args or 7 args and varargs. 577 if (NumArgs >= 7) { 578 // check common block argument. 579 Expr *Arg6 = TheCall->getArg(6); 580 if (!isBlockPointer(Arg6)) { 581 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 582 << TheCall->getDirectCallee() << "block"; 583 return true; 584 } 585 if (checkOpenCLBlockArgs(S, Arg6)) 586 return true; 587 588 // Forth argument has to be any integer type. 589 if (!Arg3->getType()->isIntegerType()) { 590 S.Diag(TheCall->getArg(3)->getBeginLoc(), 591 diag::err_opencl_builtin_expected_type) 592 << TheCall->getDirectCallee() << "integer"; 593 return true; 594 } 595 // check remaining common arguments. 596 Expr *Arg4 = TheCall->getArg(4); 597 Expr *Arg5 = TheCall->getArg(5); 598 599 // Fifth argument is always passed as a pointer to clk_event_t. 600 if (!Arg4->isNullPointerConstant(S.Context, 601 Expr::NPC_ValueDependentIsNotNull) && 602 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 603 S.Diag(TheCall->getArg(4)->getBeginLoc(), 604 diag::err_opencl_builtin_expected_type) 605 << TheCall->getDirectCallee() 606 << S.Context.getPointerType(S.Context.OCLClkEventTy); 607 return true; 608 } 609 610 // Sixth argument is always passed as a pointer to clk_event_t. 611 if (!Arg5->isNullPointerConstant(S.Context, 612 Expr::NPC_ValueDependentIsNotNull) && 613 !(Arg5->getType()->isPointerType() && 614 Arg5->getType()->getPointeeType()->isClkEventT())) { 615 S.Diag(TheCall->getArg(5)->getBeginLoc(), 616 diag::err_opencl_builtin_expected_type) 617 << TheCall->getDirectCallee() 618 << S.Context.getPointerType(S.Context.OCLClkEventTy); 619 return true; 620 } 621 622 if (NumArgs == 7) 623 return false; 624 625 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 626 } 627 628 // None of the specific case has been detected, give generic error 629 S.Diag(TheCall->getBeginLoc(), 630 diag::err_opencl_enqueue_kernel_incorrect_args); 631 return true; 632 } 633 634 /// Returns OpenCL access qual. 635 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 636 return D->getAttr<OpenCLAccessAttr>(); 637 } 638 639 /// Returns true if pipe element type is different from the pointer. 640 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 641 const Expr *Arg0 = Call->getArg(0); 642 // First argument type should always be pipe. 643 if (!Arg0->getType()->isPipeType()) { 644 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 645 << Call->getDirectCallee() << Arg0->getSourceRange(); 646 return true; 647 } 648 OpenCLAccessAttr *AccessQual = 649 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 650 // Validates the access qualifier is compatible with the call. 651 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 652 // read_only and write_only, and assumed to be read_only if no qualifier is 653 // specified. 654 switch (Call->getDirectCallee()->getBuiltinID()) { 655 case Builtin::BIread_pipe: 656 case Builtin::BIreserve_read_pipe: 657 case Builtin::BIcommit_read_pipe: 658 case Builtin::BIwork_group_reserve_read_pipe: 659 case Builtin::BIsub_group_reserve_read_pipe: 660 case Builtin::BIwork_group_commit_read_pipe: 661 case Builtin::BIsub_group_commit_read_pipe: 662 if (!(!AccessQual || AccessQual->isReadOnly())) { 663 S.Diag(Arg0->getBeginLoc(), 664 diag::err_opencl_builtin_pipe_invalid_access_modifier) 665 << "read_only" << Arg0->getSourceRange(); 666 return true; 667 } 668 break; 669 case Builtin::BIwrite_pipe: 670 case Builtin::BIreserve_write_pipe: 671 case Builtin::BIcommit_write_pipe: 672 case Builtin::BIwork_group_reserve_write_pipe: 673 case Builtin::BIsub_group_reserve_write_pipe: 674 case Builtin::BIwork_group_commit_write_pipe: 675 case Builtin::BIsub_group_commit_write_pipe: 676 if (!(AccessQual && AccessQual->isWriteOnly())) { 677 S.Diag(Arg0->getBeginLoc(), 678 diag::err_opencl_builtin_pipe_invalid_access_modifier) 679 << "write_only" << Arg0->getSourceRange(); 680 return true; 681 } 682 break; 683 default: 684 break; 685 } 686 return false; 687 } 688 689 /// Returns true if pipe element type is different from the pointer. 690 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 691 const Expr *Arg0 = Call->getArg(0); 692 const Expr *ArgIdx = Call->getArg(Idx); 693 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 694 const QualType EltTy = PipeTy->getElementType(); 695 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 696 // The Idx argument should be a pointer and the type of the pointer and 697 // the type of pipe element should also be the same. 698 if (!ArgTy || 699 !S.Context.hasSameType( 700 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 701 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 702 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 703 << ArgIdx->getType() << ArgIdx->getSourceRange(); 704 return true; 705 } 706 return false; 707 } 708 709 // Performs semantic analysis for the read/write_pipe call. 710 // \param S Reference to the semantic analyzer. 711 // \param Call A pointer to the builtin call. 712 // \return True if a semantic error has been found, false otherwise. 713 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 714 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 715 // functions have two forms. 716 switch (Call->getNumArgs()) { 717 case 2: 718 if (checkOpenCLPipeArg(S, Call)) 719 return true; 720 // The call with 2 arguments should be 721 // read/write_pipe(pipe T, T*). 722 // Check packet type T. 723 if (checkOpenCLPipePacketType(S, Call, 1)) 724 return true; 725 break; 726 727 case 4: { 728 if (checkOpenCLPipeArg(S, Call)) 729 return true; 730 // The call with 4 arguments should be 731 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 732 // Check reserve_id_t. 733 if (!Call->getArg(1)->getType()->isReserveIDT()) { 734 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 735 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 736 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 737 return true; 738 } 739 740 // Check the index. 741 const Expr *Arg2 = Call->getArg(2); 742 if (!Arg2->getType()->isIntegerType() && 743 !Arg2->getType()->isUnsignedIntegerType()) { 744 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 745 << Call->getDirectCallee() << S.Context.UnsignedIntTy 746 << Arg2->getType() << Arg2->getSourceRange(); 747 return true; 748 } 749 750 // Check packet type T. 751 if (checkOpenCLPipePacketType(S, Call, 3)) 752 return true; 753 } break; 754 default: 755 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 756 << Call->getDirectCallee() << Call->getSourceRange(); 757 return true; 758 } 759 760 return false; 761 } 762 763 // Performs a semantic analysis on the {work_group_/sub_group_ 764 // /_}reserve_{read/write}_pipe 765 // \param S Reference to the semantic analyzer. 766 // \param Call The call to the builtin function to be analyzed. 767 // \return True if a semantic error was found, false otherwise. 768 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 769 if (checkArgCount(S, Call, 2)) 770 return true; 771 772 if (checkOpenCLPipeArg(S, Call)) 773 return true; 774 775 // Check the reserve size. 776 if (!Call->getArg(1)->getType()->isIntegerType() && 777 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 778 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 779 << Call->getDirectCallee() << S.Context.UnsignedIntTy 780 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 781 return true; 782 } 783 784 // Since return type of reserve_read/write_pipe built-in function is 785 // reserve_id_t, which is not defined in the builtin def file , we used int 786 // as return type and need to override the return type of these functions. 787 Call->setType(S.Context.OCLReserveIDTy); 788 789 return false; 790 } 791 792 // Performs a semantic analysis on {work_group_/sub_group_ 793 // /_}commit_{read/write}_pipe 794 // \param S Reference to the semantic analyzer. 795 // \param Call The call to the builtin function to be analyzed. 796 // \return True if a semantic error was found, false otherwise. 797 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 798 if (checkArgCount(S, Call, 2)) 799 return true; 800 801 if (checkOpenCLPipeArg(S, Call)) 802 return true; 803 804 // Check reserve_id_t. 805 if (!Call->getArg(1)->getType()->isReserveIDT()) { 806 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 807 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 808 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 809 return true; 810 } 811 812 return false; 813 } 814 815 // Performs a semantic analysis on the call to built-in Pipe 816 // Query Functions. 817 // \param S Reference to the semantic analyzer. 818 // \param Call The call to the builtin function to be analyzed. 819 // \return True if a semantic error was found, false otherwise. 820 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 821 if (checkArgCount(S, Call, 1)) 822 return true; 823 824 if (!Call->getArg(0)->getType()->isPipeType()) { 825 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 826 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 827 return true; 828 } 829 830 return false; 831 } 832 833 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 834 // Performs semantic analysis for the to_global/local/private call. 835 // \param S Reference to the semantic analyzer. 836 // \param BuiltinID ID of the builtin function. 837 // \param Call A pointer to the builtin call. 838 // \return True if a semantic error has been found, false otherwise. 839 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 840 CallExpr *Call) { 841 if (Call->getNumArgs() != 1) { 842 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 843 << Call->getDirectCallee() << Call->getSourceRange(); 844 return true; 845 } 846 847 auto RT = Call->getArg(0)->getType(); 848 if (!RT->isPointerType() || RT->getPointeeType() 849 .getAddressSpace() == LangAS::opencl_constant) { 850 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 851 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 852 return true; 853 } 854 855 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 856 S.Diag(Call->getArg(0)->getBeginLoc(), 857 diag::warn_opencl_generic_address_space_arg) 858 << Call->getDirectCallee()->getNameInfo().getAsString() 859 << Call->getArg(0)->getSourceRange(); 860 } 861 862 RT = RT->getPointeeType(); 863 auto Qual = RT.getQualifiers(); 864 switch (BuiltinID) { 865 case Builtin::BIto_global: 866 Qual.setAddressSpace(LangAS::opencl_global); 867 break; 868 case Builtin::BIto_local: 869 Qual.setAddressSpace(LangAS::opencl_local); 870 break; 871 case Builtin::BIto_private: 872 Qual.setAddressSpace(LangAS::opencl_private); 873 break; 874 default: 875 llvm_unreachable("Invalid builtin function"); 876 } 877 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 878 RT.getUnqualifiedType(), Qual))); 879 880 return false; 881 } 882 883 // Emit an error and return true if the current architecture is not in the list 884 // of supported architectures. 885 static bool 886 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 887 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 888 llvm::Triple::ArchType CurArch = 889 S.getASTContext().getTargetInfo().getTriple().getArch(); 890 if (llvm::is_contained(SupportedArchs, CurArch)) 891 return false; 892 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 893 << TheCall->getSourceRange(); 894 return true; 895 } 896 897 ExprResult 898 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 899 CallExpr *TheCall) { 900 ExprResult TheCallResult(TheCall); 901 902 // Find out if any arguments are required to be integer constant expressions. 903 unsigned ICEArguments = 0; 904 ASTContext::GetBuiltinTypeError Error; 905 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 906 if (Error != ASTContext::GE_None) 907 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 908 909 // If any arguments are required to be ICE's, check and diagnose. 910 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 911 // Skip arguments not required to be ICE's. 912 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 913 914 llvm::APSInt Result; 915 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 916 return true; 917 ICEArguments &= ~(1 << ArgNo); 918 } 919 920 switch (BuiltinID) { 921 case Builtin::BI__builtin___CFStringMakeConstantString: 922 assert(TheCall->getNumArgs() == 1 && 923 "Wrong # arguments to builtin CFStringMakeConstantString"); 924 if (CheckObjCString(TheCall->getArg(0))) 925 return ExprError(); 926 break; 927 case Builtin::BI__builtin_ms_va_start: 928 case Builtin::BI__builtin_stdarg_start: 929 case Builtin::BI__builtin_va_start: 930 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 931 return ExprError(); 932 break; 933 case Builtin::BI__va_start: { 934 switch (Context.getTargetInfo().getTriple().getArch()) { 935 case llvm::Triple::aarch64: 936 case llvm::Triple::arm: 937 case llvm::Triple::thumb: 938 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 939 return ExprError(); 940 break; 941 default: 942 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 943 return ExprError(); 944 break; 945 } 946 break; 947 } 948 949 // The acquire, release, and no fence variants are ARM and AArch64 only. 950 case Builtin::BI_interlockedbittestandset_acq: 951 case Builtin::BI_interlockedbittestandset_rel: 952 case Builtin::BI_interlockedbittestandset_nf: 953 case Builtin::BI_interlockedbittestandreset_acq: 954 case Builtin::BI_interlockedbittestandreset_rel: 955 case Builtin::BI_interlockedbittestandreset_nf: 956 if (CheckBuiltinTargetSupport( 957 *this, BuiltinID, TheCall, 958 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 959 return ExprError(); 960 break; 961 962 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 963 case Builtin::BI_bittest64: 964 case Builtin::BI_bittestandcomplement64: 965 case Builtin::BI_bittestandreset64: 966 case Builtin::BI_bittestandset64: 967 case Builtin::BI_interlockedbittestandreset64: 968 case Builtin::BI_interlockedbittestandset64: 969 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 970 {llvm::Triple::x86_64, llvm::Triple::arm, 971 llvm::Triple::thumb, llvm::Triple::aarch64})) 972 return ExprError(); 973 break; 974 975 case Builtin::BI__builtin_isgreater: 976 case Builtin::BI__builtin_isgreaterequal: 977 case Builtin::BI__builtin_isless: 978 case Builtin::BI__builtin_islessequal: 979 case Builtin::BI__builtin_islessgreater: 980 case Builtin::BI__builtin_isunordered: 981 if (SemaBuiltinUnorderedCompare(TheCall)) 982 return ExprError(); 983 break; 984 case Builtin::BI__builtin_fpclassify: 985 if (SemaBuiltinFPClassification(TheCall, 6)) 986 return ExprError(); 987 break; 988 case Builtin::BI__builtin_isfinite: 989 case Builtin::BI__builtin_isinf: 990 case Builtin::BI__builtin_isinf_sign: 991 case Builtin::BI__builtin_isnan: 992 case Builtin::BI__builtin_isnormal: 993 case Builtin::BI__builtin_signbit: 994 case Builtin::BI__builtin_signbitf: 995 case Builtin::BI__builtin_signbitl: 996 if (SemaBuiltinFPClassification(TheCall, 1)) 997 return ExprError(); 998 break; 999 case Builtin::BI__builtin_shufflevector: 1000 return SemaBuiltinShuffleVector(TheCall); 1001 // TheCall will be freed by the smart pointer here, but that's fine, since 1002 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1003 case Builtin::BI__builtin_prefetch: 1004 if (SemaBuiltinPrefetch(TheCall)) 1005 return ExprError(); 1006 break; 1007 case Builtin::BI__builtin_alloca_with_align: 1008 if (SemaBuiltinAllocaWithAlign(TheCall)) 1009 return ExprError(); 1010 break; 1011 case Builtin::BI__assume: 1012 case Builtin::BI__builtin_assume: 1013 if (SemaBuiltinAssume(TheCall)) 1014 return ExprError(); 1015 break; 1016 case Builtin::BI__builtin_assume_aligned: 1017 if (SemaBuiltinAssumeAligned(TheCall)) 1018 return ExprError(); 1019 break; 1020 case Builtin::BI__builtin_object_size: 1021 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1022 return ExprError(); 1023 break; 1024 case Builtin::BI__builtin_longjmp: 1025 if (SemaBuiltinLongjmp(TheCall)) 1026 return ExprError(); 1027 break; 1028 case Builtin::BI__builtin_setjmp: 1029 if (SemaBuiltinSetjmp(TheCall)) 1030 return ExprError(); 1031 break; 1032 case Builtin::BI_setjmp: 1033 case Builtin::BI_setjmpex: 1034 if (checkArgCount(*this, TheCall, 1)) 1035 return true; 1036 break; 1037 case Builtin::BI__builtin_classify_type: 1038 if (checkArgCount(*this, TheCall, 1)) return true; 1039 TheCall->setType(Context.IntTy); 1040 break; 1041 case Builtin::BI__builtin_constant_p: 1042 if (checkArgCount(*this, TheCall, 1)) return true; 1043 TheCall->setType(Context.IntTy); 1044 break; 1045 case Builtin::BI__sync_fetch_and_add: 1046 case Builtin::BI__sync_fetch_and_add_1: 1047 case Builtin::BI__sync_fetch_and_add_2: 1048 case Builtin::BI__sync_fetch_and_add_4: 1049 case Builtin::BI__sync_fetch_and_add_8: 1050 case Builtin::BI__sync_fetch_and_add_16: 1051 case Builtin::BI__sync_fetch_and_sub: 1052 case Builtin::BI__sync_fetch_and_sub_1: 1053 case Builtin::BI__sync_fetch_and_sub_2: 1054 case Builtin::BI__sync_fetch_and_sub_4: 1055 case Builtin::BI__sync_fetch_and_sub_8: 1056 case Builtin::BI__sync_fetch_and_sub_16: 1057 case Builtin::BI__sync_fetch_and_or: 1058 case Builtin::BI__sync_fetch_and_or_1: 1059 case Builtin::BI__sync_fetch_and_or_2: 1060 case Builtin::BI__sync_fetch_and_or_4: 1061 case Builtin::BI__sync_fetch_and_or_8: 1062 case Builtin::BI__sync_fetch_and_or_16: 1063 case Builtin::BI__sync_fetch_and_and: 1064 case Builtin::BI__sync_fetch_and_and_1: 1065 case Builtin::BI__sync_fetch_and_and_2: 1066 case Builtin::BI__sync_fetch_and_and_4: 1067 case Builtin::BI__sync_fetch_and_and_8: 1068 case Builtin::BI__sync_fetch_and_and_16: 1069 case Builtin::BI__sync_fetch_and_xor: 1070 case Builtin::BI__sync_fetch_and_xor_1: 1071 case Builtin::BI__sync_fetch_and_xor_2: 1072 case Builtin::BI__sync_fetch_and_xor_4: 1073 case Builtin::BI__sync_fetch_and_xor_8: 1074 case Builtin::BI__sync_fetch_and_xor_16: 1075 case Builtin::BI__sync_fetch_and_nand: 1076 case Builtin::BI__sync_fetch_and_nand_1: 1077 case Builtin::BI__sync_fetch_and_nand_2: 1078 case Builtin::BI__sync_fetch_and_nand_4: 1079 case Builtin::BI__sync_fetch_and_nand_8: 1080 case Builtin::BI__sync_fetch_and_nand_16: 1081 case Builtin::BI__sync_add_and_fetch: 1082 case Builtin::BI__sync_add_and_fetch_1: 1083 case Builtin::BI__sync_add_and_fetch_2: 1084 case Builtin::BI__sync_add_and_fetch_4: 1085 case Builtin::BI__sync_add_and_fetch_8: 1086 case Builtin::BI__sync_add_and_fetch_16: 1087 case Builtin::BI__sync_sub_and_fetch: 1088 case Builtin::BI__sync_sub_and_fetch_1: 1089 case Builtin::BI__sync_sub_and_fetch_2: 1090 case Builtin::BI__sync_sub_and_fetch_4: 1091 case Builtin::BI__sync_sub_and_fetch_8: 1092 case Builtin::BI__sync_sub_and_fetch_16: 1093 case Builtin::BI__sync_and_and_fetch: 1094 case Builtin::BI__sync_and_and_fetch_1: 1095 case Builtin::BI__sync_and_and_fetch_2: 1096 case Builtin::BI__sync_and_and_fetch_4: 1097 case Builtin::BI__sync_and_and_fetch_8: 1098 case Builtin::BI__sync_and_and_fetch_16: 1099 case Builtin::BI__sync_or_and_fetch: 1100 case Builtin::BI__sync_or_and_fetch_1: 1101 case Builtin::BI__sync_or_and_fetch_2: 1102 case Builtin::BI__sync_or_and_fetch_4: 1103 case Builtin::BI__sync_or_and_fetch_8: 1104 case Builtin::BI__sync_or_and_fetch_16: 1105 case Builtin::BI__sync_xor_and_fetch: 1106 case Builtin::BI__sync_xor_and_fetch_1: 1107 case Builtin::BI__sync_xor_and_fetch_2: 1108 case Builtin::BI__sync_xor_and_fetch_4: 1109 case Builtin::BI__sync_xor_and_fetch_8: 1110 case Builtin::BI__sync_xor_and_fetch_16: 1111 case Builtin::BI__sync_nand_and_fetch: 1112 case Builtin::BI__sync_nand_and_fetch_1: 1113 case Builtin::BI__sync_nand_and_fetch_2: 1114 case Builtin::BI__sync_nand_and_fetch_4: 1115 case Builtin::BI__sync_nand_and_fetch_8: 1116 case Builtin::BI__sync_nand_and_fetch_16: 1117 case Builtin::BI__sync_val_compare_and_swap: 1118 case Builtin::BI__sync_val_compare_and_swap_1: 1119 case Builtin::BI__sync_val_compare_and_swap_2: 1120 case Builtin::BI__sync_val_compare_and_swap_4: 1121 case Builtin::BI__sync_val_compare_and_swap_8: 1122 case Builtin::BI__sync_val_compare_and_swap_16: 1123 case Builtin::BI__sync_bool_compare_and_swap: 1124 case Builtin::BI__sync_bool_compare_and_swap_1: 1125 case Builtin::BI__sync_bool_compare_and_swap_2: 1126 case Builtin::BI__sync_bool_compare_and_swap_4: 1127 case Builtin::BI__sync_bool_compare_and_swap_8: 1128 case Builtin::BI__sync_bool_compare_and_swap_16: 1129 case Builtin::BI__sync_lock_test_and_set: 1130 case Builtin::BI__sync_lock_test_and_set_1: 1131 case Builtin::BI__sync_lock_test_and_set_2: 1132 case Builtin::BI__sync_lock_test_and_set_4: 1133 case Builtin::BI__sync_lock_test_and_set_8: 1134 case Builtin::BI__sync_lock_test_and_set_16: 1135 case Builtin::BI__sync_lock_release: 1136 case Builtin::BI__sync_lock_release_1: 1137 case Builtin::BI__sync_lock_release_2: 1138 case Builtin::BI__sync_lock_release_4: 1139 case Builtin::BI__sync_lock_release_8: 1140 case Builtin::BI__sync_lock_release_16: 1141 case Builtin::BI__sync_swap: 1142 case Builtin::BI__sync_swap_1: 1143 case Builtin::BI__sync_swap_2: 1144 case Builtin::BI__sync_swap_4: 1145 case Builtin::BI__sync_swap_8: 1146 case Builtin::BI__sync_swap_16: 1147 return SemaBuiltinAtomicOverloaded(TheCallResult); 1148 case Builtin::BI__sync_synchronize: 1149 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1150 << TheCall->getCallee()->getSourceRange(); 1151 break; 1152 case Builtin::BI__builtin_nontemporal_load: 1153 case Builtin::BI__builtin_nontemporal_store: 1154 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1155 #define BUILTIN(ID, TYPE, ATTRS) 1156 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1157 case Builtin::BI##ID: \ 1158 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1159 #include "clang/Basic/Builtins.def" 1160 case Builtin::BI__annotation: 1161 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1162 return ExprError(); 1163 break; 1164 case Builtin::BI__builtin_annotation: 1165 if (SemaBuiltinAnnotation(*this, TheCall)) 1166 return ExprError(); 1167 break; 1168 case Builtin::BI__builtin_addressof: 1169 if (SemaBuiltinAddressof(*this, TheCall)) 1170 return ExprError(); 1171 break; 1172 case Builtin::BI__builtin_add_overflow: 1173 case Builtin::BI__builtin_sub_overflow: 1174 case Builtin::BI__builtin_mul_overflow: 1175 if (SemaBuiltinOverflow(*this, TheCall)) 1176 return ExprError(); 1177 break; 1178 case Builtin::BI__builtin_operator_new: 1179 case Builtin::BI__builtin_operator_delete: { 1180 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1181 ExprResult Res = 1182 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1183 if (Res.isInvalid()) 1184 CorrectDelayedTyposInExpr(TheCallResult.get()); 1185 return Res; 1186 } 1187 case Builtin::BI__builtin_dump_struct: { 1188 // We first want to ensure we are called with 2 arguments 1189 if (checkArgCount(*this, TheCall, 2)) 1190 return ExprError(); 1191 // Ensure that the first argument is of type 'struct XX *' 1192 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1193 const QualType PtrArgType = PtrArg->getType(); 1194 if (!PtrArgType->isPointerType() || 1195 !PtrArgType->getPointeeType()->isRecordType()) { 1196 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1197 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1198 << "structure pointer"; 1199 return ExprError(); 1200 } 1201 1202 // Ensure that the second argument is of type 'FunctionType' 1203 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1204 const QualType FnPtrArgType = FnPtrArg->getType(); 1205 if (!FnPtrArgType->isPointerType()) { 1206 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1207 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1208 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1209 return ExprError(); 1210 } 1211 1212 const auto *FuncType = 1213 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1214 1215 if (!FuncType) { 1216 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1217 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1218 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1219 return ExprError(); 1220 } 1221 1222 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1223 if (!FT->getNumParams()) { 1224 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1225 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1226 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1227 return ExprError(); 1228 } 1229 QualType PT = FT->getParamType(0); 1230 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1231 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1232 !PT->getPointeeType().isConstQualified()) { 1233 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1234 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1235 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1236 return ExprError(); 1237 } 1238 } 1239 1240 TheCall->setType(Context.IntTy); 1241 break; 1242 } 1243 1244 // check secure string manipulation functions where overflows 1245 // are detectable at compile time 1246 case Builtin::BI__builtin___memcpy_chk: 1247 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memcpy"); 1248 break; 1249 case Builtin::BI__builtin___memmove_chk: 1250 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memmove"); 1251 break; 1252 case Builtin::BI__builtin___memset_chk: 1253 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memset"); 1254 break; 1255 case Builtin::BI__builtin___strlcat_chk: 1256 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcat"); 1257 break; 1258 case Builtin::BI__builtin___strlcpy_chk: 1259 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcpy"); 1260 break; 1261 case Builtin::BI__builtin___strncat_chk: 1262 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncat"); 1263 break; 1264 case Builtin::BI__builtin___strncpy_chk: 1265 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncpy"); 1266 break; 1267 case Builtin::BI__builtin___stpncpy_chk: 1268 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "stpncpy"); 1269 break; 1270 case Builtin::BI__builtin___memccpy_chk: 1271 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4, "memccpy"); 1272 break; 1273 case Builtin::BI__builtin___snprintf_chk: 1274 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "snprintf"); 1275 break; 1276 case Builtin::BI__builtin___vsnprintf_chk: 1277 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "vsnprintf"); 1278 break; 1279 case Builtin::BI__builtin_call_with_static_chain: 1280 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1281 return ExprError(); 1282 break; 1283 case Builtin::BI__exception_code: 1284 case Builtin::BI_exception_code: 1285 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1286 diag::err_seh___except_block)) 1287 return ExprError(); 1288 break; 1289 case Builtin::BI__exception_info: 1290 case Builtin::BI_exception_info: 1291 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1292 diag::err_seh___except_filter)) 1293 return ExprError(); 1294 break; 1295 case Builtin::BI__GetExceptionInfo: 1296 if (checkArgCount(*this, TheCall, 1)) 1297 return ExprError(); 1298 1299 if (CheckCXXThrowOperand( 1300 TheCall->getBeginLoc(), 1301 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1302 TheCall)) 1303 return ExprError(); 1304 1305 TheCall->setType(Context.VoidPtrTy); 1306 break; 1307 // OpenCL v2.0, s6.13.16 - Pipe functions 1308 case Builtin::BIread_pipe: 1309 case Builtin::BIwrite_pipe: 1310 // Since those two functions are declared with var args, we need a semantic 1311 // check for the argument. 1312 if (SemaBuiltinRWPipe(*this, TheCall)) 1313 return ExprError(); 1314 break; 1315 case Builtin::BIreserve_read_pipe: 1316 case Builtin::BIreserve_write_pipe: 1317 case Builtin::BIwork_group_reserve_read_pipe: 1318 case Builtin::BIwork_group_reserve_write_pipe: 1319 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1320 return ExprError(); 1321 break; 1322 case Builtin::BIsub_group_reserve_read_pipe: 1323 case Builtin::BIsub_group_reserve_write_pipe: 1324 if (checkOpenCLSubgroupExt(*this, TheCall) || 1325 SemaBuiltinReserveRWPipe(*this, TheCall)) 1326 return ExprError(); 1327 break; 1328 case Builtin::BIcommit_read_pipe: 1329 case Builtin::BIcommit_write_pipe: 1330 case Builtin::BIwork_group_commit_read_pipe: 1331 case Builtin::BIwork_group_commit_write_pipe: 1332 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1333 return ExprError(); 1334 break; 1335 case Builtin::BIsub_group_commit_read_pipe: 1336 case Builtin::BIsub_group_commit_write_pipe: 1337 if (checkOpenCLSubgroupExt(*this, TheCall) || 1338 SemaBuiltinCommitRWPipe(*this, TheCall)) 1339 return ExprError(); 1340 break; 1341 case Builtin::BIget_pipe_num_packets: 1342 case Builtin::BIget_pipe_max_packets: 1343 if (SemaBuiltinPipePackets(*this, TheCall)) 1344 return ExprError(); 1345 break; 1346 case Builtin::BIto_global: 1347 case Builtin::BIto_local: 1348 case Builtin::BIto_private: 1349 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1350 return ExprError(); 1351 break; 1352 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1353 case Builtin::BIenqueue_kernel: 1354 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1355 return ExprError(); 1356 break; 1357 case Builtin::BIget_kernel_work_group_size: 1358 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1359 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1360 return ExprError(); 1361 break; 1362 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1363 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1364 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1365 return ExprError(); 1366 break; 1367 case Builtin::BI__builtin_os_log_format: 1368 case Builtin::BI__builtin_os_log_format_buffer_size: 1369 if (SemaBuiltinOSLogFormat(TheCall)) 1370 return ExprError(); 1371 break; 1372 } 1373 1374 // Since the target specific builtins for each arch overlap, only check those 1375 // of the arch we are compiling for. 1376 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1377 switch (Context.getTargetInfo().getTriple().getArch()) { 1378 case llvm::Triple::arm: 1379 case llvm::Triple::armeb: 1380 case llvm::Triple::thumb: 1381 case llvm::Triple::thumbeb: 1382 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1383 return ExprError(); 1384 break; 1385 case llvm::Triple::aarch64: 1386 case llvm::Triple::aarch64_be: 1387 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1388 return ExprError(); 1389 break; 1390 case llvm::Triple::hexagon: 1391 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1392 return ExprError(); 1393 break; 1394 case llvm::Triple::mips: 1395 case llvm::Triple::mipsel: 1396 case llvm::Triple::mips64: 1397 case llvm::Triple::mips64el: 1398 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1399 return ExprError(); 1400 break; 1401 case llvm::Triple::systemz: 1402 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1403 return ExprError(); 1404 break; 1405 case llvm::Triple::x86: 1406 case llvm::Triple::x86_64: 1407 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1408 return ExprError(); 1409 break; 1410 case llvm::Triple::ppc: 1411 case llvm::Triple::ppc64: 1412 case llvm::Triple::ppc64le: 1413 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1414 return ExprError(); 1415 break; 1416 default: 1417 break; 1418 } 1419 } 1420 1421 return TheCallResult; 1422 } 1423 1424 // Get the valid immediate range for the specified NEON type code. 1425 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1426 NeonTypeFlags Type(t); 1427 int IsQuad = ForceQuad ? true : Type.isQuad(); 1428 switch (Type.getEltType()) { 1429 case NeonTypeFlags::Int8: 1430 case NeonTypeFlags::Poly8: 1431 return shift ? 7 : (8 << IsQuad) - 1; 1432 case NeonTypeFlags::Int16: 1433 case NeonTypeFlags::Poly16: 1434 return shift ? 15 : (4 << IsQuad) - 1; 1435 case NeonTypeFlags::Int32: 1436 return shift ? 31 : (2 << IsQuad) - 1; 1437 case NeonTypeFlags::Int64: 1438 case NeonTypeFlags::Poly64: 1439 return shift ? 63 : (1 << IsQuad) - 1; 1440 case NeonTypeFlags::Poly128: 1441 return shift ? 127 : (1 << IsQuad) - 1; 1442 case NeonTypeFlags::Float16: 1443 assert(!shift && "cannot shift float types!"); 1444 return (4 << IsQuad) - 1; 1445 case NeonTypeFlags::Float32: 1446 assert(!shift && "cannot shift float types!"); 1447 return (2 << IsQuad) - 1; 1448 case NeonTypeFlags::Float64: 1449 assert(!shift && "cannot shift float types!"); 1450 return (1 << IsQuad) - 1; 1451 } 1452 llvm_unreachable("Invalid NeonTypeFlag!"); 1453 } 1454 1455 /// getNeonEltType - Return the QualType corresponding to the elements of 1456 /// the vector type specified by the NeonTypeFlags. This is used to check 1457 /// the pointer arguments for Neon load/store intrinsics. 1458 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1459 bool IsPolyUnsigned, bool IsInt64Long) { 1460 switch (Flags.getEltType()) { 1461 case NeonTypeFlags::Int8: 1462 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1463 case NeonTypeFlags::Int16: 1464 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1465 case NeonTypeFlags::Int32: 1466 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1467 case NeonTypeFlags::Int64: 1468 if (IsInt64Long) 1469 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1470 else 1471 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1472 : Context.LongLongTy; 1473 case NeonTypeFlags::Poly8: 1474 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1475 case NeonTypeFlags::Poly16: 1476 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1477 case NeonTypeFlags::Poly64: 1478 if (IsInt64Long) 1479 return Context.UnsignedLongTy; 1480 else 1481 return Context.UnsignedLongLongTy; 1482 case NeonTypeFlags::Poly128: 1483 break; 1484 case NeonTypeFlags::Float16: 1485 return Context.HalfTy; 1486 case NeonTypeFlags::Float32: 1487 return Context.FloatTy; 1488 case NeonTypeFlags::Float64: 1489 return Context.DoubleTy; 1490 } 1491 llvm_unreachable("Invalid NeonTypeFlag!"); 1492 } 1493 1494 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1495 llvm::APSInt Result; 1496 uint64_t mask = 0; 1497 unsigned TV = 0; 1498 int PtrArgNum = -1; 1499 bool HasConstPtr = false; 1500 switch (BuiltinID) { 1501 #define GET_NEON_OVERLOAD_CHECK 1502 #include "clang/Basic/arm_neon.inc" 1503 #include "clang/Basic/arm_fp16.inc" 1504 #undef GET_NEON_OVERLOAD_CHECK 1505 } 1506 1507 // For NEON intrinsics which are overloaded on vector element type, validate 1508 // the immediate which specifies which variant to emit. 1509 unsigned ImmArg = TheCall->getNumArgs()-1; 1510 if (mask) { 1511 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1512 return true; 1513 1514 TV = Result.getLimitedValue(64); 1515 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1516 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 1517 << TheCall->getArg(ImmArg)->getSourceRange(); 1518 } 1519 1520 if (PtrArgNum >= 0) { 1521 // Check that pointer arguments have the specified type. 1522 Expr *Arg = TheCall->getArg(PtrArgNum); 1523 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1524 Arg = ICE->getSubExpr(); 1525 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1526 QualType RHSTy = RHS.get()->getType(); 1527 1528 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1529 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1530 Arch == llvm::Triple::aarch64_be; 1531 bool IsInt64Long = 1532 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1533 QualType EltTy = 1534 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1535 if (HasConstPtr) 1536 EltTy = EltTy.withConst(); 1537 QualType LHSTy = Context.getPointerType(EltTy); 1538 AssignConvertType ConvTy; 1539 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1540 if (RHS.isInvalid()) 1541 return true; 1542 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 1543 RHS.get(), AA_Assigning)) 1544 return true; 1545 } 1546 1547 // For NEON intrinsics which take an immediate value as part of the 1548 // instruction, range check them here. 1549 unsigned i = 0, l = 0, u = 0; 1550 switch (BuiltinID) { 1551 default: 1552 return false; 1553 #define GET_NEON_IMMEDIATE_CHECK 1554 #include "clang/Basic/arm_neon.inc" 1555 #include "clang/Basic/arm_fp16.inc" 1556 #undef GET_NEON_IMMEDIATE_CHECK 1557 } 1558 1559 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1560 } 1561 1562 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1563 unsigned MaxWidth) { 1564 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1565 BuiltinID == ARM::BI__builtin_arm_ldaex || 1566 BuiltinID == ARM::BI__builtin_arm_strex || 1567 BuiltinID == ARM::BI__builtin_arm_stlex || 1568 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1569 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1570 BuiltinID == AArch64::BI__builtin_arm_strex || 1571 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1572 "unexpected ARM builtin"); 1573 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1574 BuiltinID == ARM::BI__builtin_arm_ldaex || 1575 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1576 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1577 1578 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1579 1580 // Ensure that we have the proper number of arguments. 1581 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1582 return true; 1583 1584 // Inspect the pointer argument of the atomic builtin. This should always be 1585 // a pointer type, whose element is an integral scalar or pointer type. 1586 // Because it is a pointer type, we don't have to worry about any implicit 1587 // casts here. 1588 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1589 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1590 if (PointerArgRes.isInvalid()) 1591 return true; 1592 PointerArg = PointerArgRes.get(); 1593 1594 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1595 if (!pointerType) { 1596 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 1597 << PointerArg->getType() << PointerArg->getSourceRange(); 1598 return true; 1599 } 1600 1601 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1602 // task is to insert the appropriate casts into the AST. First work out just 1603 // what the appropriate type is. 1604 QualType ValType = pointerType->getPointeeType(); 1605 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1606 if (IsLdrex) 1607 AddrType.addConst(); 1608 1609 // Issue a warning if the cast is dodgy. 1610 CastKind CastNeeded = CK_NoOp; 1611 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1612 CastNeeded = CK_BitCast; 1613 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 1614 << PointerArg->getType() << Context.getPointerType(AddrType) 1615 << AA_Passing << PointerArg->getSourceRange(); 1616 } 1617 1618 // Finally, do the cast and replace the argument with the corrected version. 1619 AddrType = Context.getPointerType(AddrType); 1620 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1621 if (PointerArgRes.isInvalid()) 1622 return true; 1623 PointerArg = PointerArgRes.get(); 1624 1625 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1626 1627 // In general, we allow ints, floats and pointers to be loaded and stored. 1628 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1629 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1630 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1631 << PointerArg->getType() << PointerArg->getSourceRange(); 1632 return true; 1633 } 1634 1635 // But ARM doesn't have instructions to deal with 128-bit versions. 1636 if (Context.getTypeSize(ValType) > MaxWidth) { 1637 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1638 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 1639 << PointerArg->getType() << PointerArg->getSourceRange(); 1640 return true; 1641 } 1642 1643 switch (ValType.getObjCLifetime()) { 1644 case Qualifiers::OCL_None: 1645 case Qualifiers::OCL_ExplicitNone: 1646 // okay 1647 break; 1648 1649 case Qualifiers::OCL_Weak: 1650 case Qualifiers::OCL_Strong: 1651 case Qualifiers::OCL_Autoreleasing: 1652 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 1653 << ValType << PointerArg->getSourceRange(); 1654 return true; 1655 } 1656 1657 if (IsLdrex) { 1658 TheCall->setType(ValType); 1659 return false; 1660 } 1661 1662 // Initialize the argument to be stored. 1663 ExprResult ValArg = TheCall->getArg(0); 1664 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1665 Context, ValType, /*consume*/ false); 1666 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1667 if (ValArg.isInvalid()) 1668 return true; 1669 TheCall->setArg(0, ValArg.get()); 1670 1671 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1672 // but the custom checker bypasses all default analysis. 1673 TheCall->setType(Context.IntTy); 1674 return false; 1675 } 1676 1677 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1678 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1679 BuiltinID == ARM::BI__builtin_arm_ldaex || 1680 BuiltinID == ARM::BI__builtin_arm_strex || 1681 BuiltinID == ARM::BI__builtin_arm_stlex) { 1682 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1683 } 1684 1685 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1686 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1687 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1688 } 1689 1690 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1691 BuiltinID == ARM::BI__builtin_arm_wsr64) 1692 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1693 1694 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1695 BuiltinID == ARM::BI__builtin_arm_rsrp || 1696 BuiltinID == ARM::BI__builtin_arm_wsr || 1697 BuiltinID == ARM::BI__builtin_arm_wsrp) 1698 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1699 1700 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1701 return true; 1702 1703 // For intrinsics which take an immediate value as part of the instruction, 1704 // range check them here. 1705 // FIXME: VFP Intrinsics should error if VFP not present. 1706 switch (BuiltinID) { 1707 default: return false; 1708 case ARM::BI__builtin_arm_ssat: 1709 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1710 case ARM::BI__builtin_arm_usat: 1711 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1712 case ARM::BI__builtin_arm_ssat16: 1713 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1714 case ARM::BI__builtin_arm_usat16: 1715 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1716 case ARM::BI__builtin_arm_vcvtr_f: 1717 case ARM::BI__builtin_arm_vcvtr_d: 1718 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1719 case ARM::BI__builtin_arm_dmb: 1720 case ARM::BI__builtin_arm_dsb: 1721 case ARM::BI__builtin_arm_isb: 1722 case ARM::BI__builtin_arm_dbg: 1723 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1724 } 1725 } 1726 1727 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1728 CallExpr *TheCall) { 1729 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1730 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1731 BuiltinID == AArch64::BI__builtin_arm_strex || 1732 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1733 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1734 } 1735 1736 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1737 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1738 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1739 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1740 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1741 } 1742 1743 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1744 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1745 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1746 1747 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1748 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1749 BuiltinID == AArch64::BI__builtin_arm_wsr || 1750 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1751 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1752 1753 // Only check the valid encoding range. Any constant in this range would be 1754 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 1755 // an exception for incorrect registers. This matches MSVC behavior. 1756 if (BuiltinID == AArch64::BI_ReadStatusReg || 1757 BuiltinID == AArch64::BI_WriteStatusReg) 1758 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 1759 1760 if (BuiltinID == AArch64::BI__getReg) 1761 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 1762 1763 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1764 return true; 1765 1766 // For intrinsics which take an immediate value as part of the instruction, 1767 // range check them here. 1768 unsigned i = 0, l = 0, u = 0; 1769 switch (BuiltinID) { 1770 default: return false; 1771 case AArch64::BI__builtin_arm_dmb: 1772 case AArch64::BI__builtin_arm_dsb: 1773 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1774 } 1775 1776 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1777 } 1778 1779 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 1780 struct BuiltinAndString { 1781 unsigned BuiltinID; 1782 const char *Str; 1783 }; 1784 1785 static BuiltinAndString ValidCPU[] = { 1786 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" }, 1787 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" }, 1788 { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" }, 1789 { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" }, 1790 { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" }, 1791 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" }, 1792 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" }, 1793 { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" }, 1794 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" }, 1795 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" }, 1796 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" }, 1797 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" }, 1798 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" }, 1799 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" }, 1800 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" }, 1801 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" }, 1802 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" }, 1803 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" }, 1804 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" }, 1805 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" }, 1806 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" }, 1807 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" }, 1808 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" }, 1809 }; 1810 1811 static BuiltinAndString ValidHVX[] = { 1812 { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" }, 1813 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" }, 1814 { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" }, 1815 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" }, 1816 { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" }, 1817 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" }, 1818 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" }, 1819 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" }, 1820 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" }, 1821 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" }, 1822 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" }, 1823 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" }, 1824 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" }, 1825 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" }, 1826 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" }, 1827 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" }, 1828 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" }, 1829 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" }, 1830 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" }, 1831 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" }, 1832 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" }, 1833 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" }, 1834 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" }, 1835 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" }, 1836 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" }, 1837 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" }, 1838 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" }, 1839 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" }, 1840 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" }, 1841 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" }, 1842 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" }, 1843 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" }, 1844 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" }, 1845 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" }, 1846 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" }, 1847 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" }, 1848 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" }, 1849 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" }, 1850 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" }, 1851 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" }, 1852 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" }, 1853 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" }, 1854 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" }, 1855 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" }, 1856 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" }, 1857 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" }, 1858 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" }, 1859 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" }, 1860 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" }, 1861 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" }, 1862 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" }, 1863 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" }, 1864 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" }, 1865 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" }, 1866 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" }, 1867 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" }, 1868 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" }, 1869 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" }, 1870 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" }, 1871 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" }, 1872 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" }, 1873 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" }, 1874 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" }, 1875 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" }, 1876 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" }, 1877 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" }, 1878 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" }, 1879 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" }, 1880 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" }, 1881 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" }, 1882 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" }, 1883 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" }, 1884 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" }, 1885 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" }, 1886 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" }, 1887 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" }, 1888 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" }, 1889 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" }, 1890 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" }, 1891 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" }, 1892 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" }, 1893 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" }, 1894 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" }, 1895 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" }, 1896 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" }, 1897 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" }, 1898 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" }, 1899 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" }, 1900 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" }, 1901 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" }, 1902 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" }, 1903 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" }, 1904 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" }, 1905 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" }, 1906 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" }, 1907 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" }, 1908 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" }, 1909 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" }, 1910 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" }, 1911 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" }, 1912 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" }, 1913 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" }, 1914 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" }, 1915 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" }, 1916 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" }, 1917 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" }, 1918 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" }, 1919 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" }, 1920 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" }, 1921 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" }, 1922 { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" }, 1923 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" }, 1924 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" }, 1925 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" }, 1926 { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" }, 1927 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" }, 1928 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" }, 1929 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" }, 1930 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" }, 1931 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" }, 1932 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" }, 1933 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" }, 1934 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" }, 1935 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" }, 1936 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" }, 1937 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" }, 1938 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" }, 1939 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" }, 1940 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" }, 1941 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" }, 1942 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" }, 1943 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" }, 1944 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" }, 1945 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" }, 1946 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" }, 1947 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" }, 1948 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" }, 1949 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" }, 1950 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" }, 1951 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" }, 1952 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" }, 1953 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" }, 1954 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" }, 1955 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" }, 1956 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" }, 1957 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" }, 1958 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" }, 1959 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" }, 1960 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" }, 1961 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" }, 1962 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" }, 1963 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" }, 1964 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" }, 1965 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" }, 1966 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" }, 1967 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" }, 1968 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" }, 1969 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" }, 1970 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" }, 1971 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" }, 1972 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" }, 1973 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" }, 1974 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" }, 1975 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" }, 1976 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" }, 1977 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" }, 1978 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" }, 1979 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" }, 1980 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" }, 1981 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" }, 1982 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" }, 1983 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" }, 1984 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" }, 1985 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" }, 1986 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" }, 1987 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" }, 1988 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" }, 1989 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" }, 1990 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" }, 1991 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" }, 1992 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" }, 1993 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" }, 1994 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" }, 1995 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" }, 1996 { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" }, 1997 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" }, 1998 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" }, 1999 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" }, 2000 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" }, 2001 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" }, 2002 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" }, 2003 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" }, 2004 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" }, 2005 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" }, 2006 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" }, 2007 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" }, 2008 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" }, 2009 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" }, 2010 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" }, 2011 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" }, 2012 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" }, 2013 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" }, 2014 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" }, 2015 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" }, 2016 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" }, 2017 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" }, 2018 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" }, 2019 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" }, 2020 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" }, 2021 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" }, 2022 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" }, 2023 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" }, 2024 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" }, 2025 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" }, 2026 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" }, 2027 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" }, 2028 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" }, 2029 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" }, 2030 { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" }, 2031 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" }, 2032 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" }, 2033 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" }, 2034 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" }, 2035 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" }, 2036 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" }, 2037 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" }, 2038 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" }, 2039 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" }, 2040 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" }, 2041 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" }, 2042 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" }, 2043 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" }, 2044 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" }, 2045 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" }, 2046 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" }, 2047 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" }, 2048 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" }, 2049 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" }, 2050 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" }, 2051 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" }, 2052 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" }, 2053 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" }, 2054 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" }, 2055 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" }, 2056 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" }, 2057 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" }, 2058 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" }, 2059 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" }, 2060 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" }, 2061 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" }, 2062 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" }, 2063 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" }, 2064 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" }, 2065 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" }, 2066 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" }, 2067 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2068 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" }, 2069 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" }, 2070 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" }, 2071 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" }, 2072 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" }, 2073 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" }, 2074 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" }, 2075 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" }, 2076 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" }, 2077 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" }, 2078 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" }, 2079 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" }, 2080 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" }, 2081 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" }, 2082 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" }, 2083 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" }, 2084 { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" }, 2085 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" }, 2086 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" }, 2087 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" }, 2088 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" }, 2089 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" }, 2090 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" }, 2091 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" }, 2092 { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" }, 2093 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" }, 2094 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" }, 2095 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" }, 2096 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" }, 2097 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" }, 2098 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" }, 2099 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" }, 2100 { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" }, 2101 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" }, 2102 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" }, 2103 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" }, 2104 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" }, 2105 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" }, 2106 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" }, 2107 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" }, 2108 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" }, 2109 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" }, 2110 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" }, 2111 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" }, 2112 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" }, 2113 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" }, 2114 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" }, 2115 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" }, 2116 { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" }, 2117 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" }, 2118 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" }, 2119 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" }, 2120 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" }, 2121 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" }, 2122 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" }, 2123 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" }, 2124 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" }, 2125 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" }, 2126 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" }, 2127 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" }, 2128 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" }, 2129 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" }, 2130 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" }, 2131 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" }, 2132 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" }, 2133 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" }, 2134 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" }, 2135 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" }, 2136 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" }, 2137 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" }, 2138 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" }, 2139 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" }, 2140 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" }, 2141 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" }, 2142 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" }, 2143 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" }, 2144 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" }, 2145 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" }, 2146 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" }, 2147 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" }, 2148 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" }, 2149 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" }, 2150 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" }, 2151 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" }, 2152 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" }, 2153 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" }, 2154 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" }, 2155 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" }, 2156 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" }, 2157 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" }, 2158 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" }, 2159 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" }, 2160 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" }, 2161 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" }, 2162 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" }, 2163 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" }, 2164 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" }, 2165 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" }, 2166 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" }, 2167 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" }, 2168 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" }, 2169 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" }, 2170 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" }, 2171 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" }, 2172 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" }, 2173 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" }, 2174 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" }, 2175 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" }, 2176 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" }, 2177 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" }, 2178 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" }, 2179 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" }, 2180 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" }, 2181 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" }, 2182 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" }, 2183 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" }, 2184 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" }, 2185 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" }, 2186 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" }, 2187 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" }, 2188 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" }, 2189 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" }, 2190 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" }, 2191 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" }, 2192 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" }, 2193 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" }, 2194 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" }, 2195 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" }, 2196 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" }, 2197 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" }, 2198 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" }, 2199 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" }, 2200 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" }, 2201 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" }, 2202 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" }, 2203 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" }, 2204 { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" }, 2205 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" }, 2206 { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" }, 2207 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" }, 2208 { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" }, 2209 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" }, 2210 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" }, 2211 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" }, 2212 { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" }, 2213 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" }, 2214 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" }, 2215 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" }, 2216 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" }, 2217 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" }, 2218 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" }, 2219 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" }, 2220 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" }, 2221 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" }, 2222 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" }, 2223 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" }, 2224 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" }, 2225 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" }, 2226 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" }, 2227 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" }, 2228 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" }, 2229 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" }, 2230 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" }, 2231 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" }, 2232 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" }, 2233 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" }, 2234 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" }, 2235 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" }, 2236 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" }, 2237 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" }, 2238 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" }, 2239 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" }, 2240 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" }, 2241 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" }, 2242 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" }, 2243 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" }, 2244 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" }, 2245 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" }, 2246 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" }, 2247 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" }, 2248 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" }, 2249 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" }, 2250 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" }, 2251 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" }, 2252 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" }, 2253 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" }, 2254 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" }, 2255 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" }, 2256 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" }, 2257 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" }, 2258 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" }, 2259 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" }, 2260 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" }, 2261 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2262 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" }, 2263 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" }, 2264 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" }, 2265 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" }, 2266 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" }, 2267 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" }, 2268 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" }, 2269 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" }, 2270 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" }, 2271 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" }, 2272 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" }, 2273 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" }, 2274 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" }, 2275 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" }, 2276 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" }, 2277 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" }, 2278 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" }, 2279 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" }, 2280 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" }, 2281 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" }, 2282 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" }, 2283 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" }, 2284 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" }, 2285 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" }, 2286 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" }, 2287 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" }, 2288 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" }, 2289 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" }, 2290 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" }, 2291 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" }, 2292 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" }, 2293 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" }, 2294 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" }, 2295 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" }, 2296 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" }, 2297 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" }, 2298 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" }, 2299 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" }, 2300 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" }, 2301 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" }, 2302 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" }, 2303 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" }, 2304 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" }, 2305 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" }, 2306 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" }, 2307 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" }, 2308 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" }, 2309 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" }, 2310 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" }, 2311 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" }, 2312 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" }, 2313 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" }, 2314 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" }, 2315 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" }, 2316 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" }, 2317 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" }, 2318 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" }, 2319 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" }, 2320 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" }, 2321 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" }, 2322 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" }, 2323 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" }, 2324 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" }, 2325 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" }, 2326 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" }, 2327 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" }, 2328 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" }, 2329 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" }, 2330 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" }, 2331 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" }, 2332 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" }, 2333 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" }, 2334 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" }, 2335 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" }, 2336 { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" }, 2337 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" }, 2338 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" }, 2339 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" }, 2340 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" }, 2341 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" }, 2342 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" }, 2343 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" }, 2344 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" }, 2345 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" }, 2346 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" }, 2347 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" }, 2348 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" }, 2349 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" }, 2350 { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" }, 2351 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" }, 2352 { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" }, 2353 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" }, 2354 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" }, 2355 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" }, 2356 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" }, 2357 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" }, 2358 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" }, 2359 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" }, 2360 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" }, 2361 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" }, 2362 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" }, 2363 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" }, 2364 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" }, 2365 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" }, 2366 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" }, 2367 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" }, 2368 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" }, 2369 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" }, 2370 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" }, 2371 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" }, 2372 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" }, 2373 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" }, 2374 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" }, 2375 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" }, 2376 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" }, 2377 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" }, 2378 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" }, 2379 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" }, 2380 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" }, 2381 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" }, 2382 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" }, 2383 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" }, 2384 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" }, 2385 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" }, 2386 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" }, 2387 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" }, 2388 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" }, 2389 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" }, 2390 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" }, 2391 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" }, 2392 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" }, 2393 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" }, 2394 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" }, 2395 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" }, 2396 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" }, 2397 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" }, 2398 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" }, 2399 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" }, 2400 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" }, 2401 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" }, 2402 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" }, 2403 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" }, 2404 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" }, 2405 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" }, 2406 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" }, 2407 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" }, 2408 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" }, 2409 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" }, 2410 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" }, 2411 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" }, 2412 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" }, 2413 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" }, 2414 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" }, 2415 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" }, 2416 { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" }, 2417 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" }, 2418 { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" }, 2419 { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" }, 2420 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" }, 2421 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" }, 2422 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" }, 2423 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" }, 2424 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" }, 2425 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" }, 2426 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" }, 2427 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" }, 2428 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" }, 2429 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" }, 2430 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" }, 2431 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" }, 2432 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" }, 2433 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" }, 2434 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" }, 2435 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" }, 2436 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" }, 2437 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" }, 2438 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" }, 2439 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" }, 2440 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" }, 2441 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" }, 2442 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" }, 2443 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" }, 2444 { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" }, 2445 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" }, 2446 { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" }, 2447 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" }, 2448 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" }, 2449 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" }, 2450 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" }, 2451 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" }, 2452 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" }, 2453 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" }, 2454 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" }, 2455 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" }, 2456 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" }, 2457 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" }, 2458 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" }, 2459 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" }, 2460 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" }, 2461 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" }, 2462 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" }, 2463 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" }, 2464 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" }, 2465 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" }, 2466 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" }, 2467 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" }, 2468 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" }, 2469 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" }, 2470 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" }, 2471 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" }, 2472 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" }, 2473 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" }, 2474 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" }, 2475 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" }, 2476 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" }, 2477 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" }, 2478 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" }, 2479 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" }, 2480 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" }, 2481 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" }, 2482 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" }, 2483 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" }, 2484 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" }, 2485 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" }, 2486 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" }, 2487 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" }, 2488 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" }, 2489 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" }, 2490 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" }, 2491 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" }, 2492 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" }, 2493 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" }, 2494 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" }, 2495 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" }, 2496 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" }, 2497 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" }, 2498 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" }, 2499 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" }, 2500 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" }, 2501 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" }, 2502 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" }, 2503 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" }, 2504 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" }, 2505 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" }, 2506 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" }, 2507 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" }, 2508 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" }, 2509 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" }, 2510 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" }, 2511 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" }, 2512 { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" }, 2513 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" }, 2514 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" }, 2515 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" }, 2516 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" }, 2517 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" }, 2518 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" }, 2519 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" }, 2520 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" }, 2521 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" }, 2522 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" }, 2523 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" }, 2524 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" }, 2525 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" }, 2526 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" }, 2527 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" }, 2528 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" }, 2529 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" }, 2530 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" }, 2531 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" }, 2532 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" }, 2533 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" }, 2534 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" }, 2535 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" }, 2536 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" }, 2537 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" }, 2538 { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" }, 2539 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" }, 2540 { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" }, 2541 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" }, 2542 { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" }, 2543 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" }, 2544 }; 2545 2546 // Sort the tables on first execution so we can binary search them. 2547 auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) { 2548 return LHS.BuiltinID < RHS.BuiltinID; 2549 }; 2550 static const bool SortOnce = 2551 (std::sort(std::begin(ValidCPU), std::end(ValidCPU), SortCmp), 2552 std::sort(std::begin(ValidHVX), std::end(ValidHVX), SortCmp), true); 2553 (void)SortOnce; 2554 auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) { 2555 return BI.BuiltinID < BuiltinID; 2556 }; 2557 2558 const TargetInfo &TI = Context.getTargetInfo(); 2559 2560 const BuiltinAndString *FC = 2561 std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID, 2562 LowerBoundCmp); 2563 if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) { 2564 const TargetOptions &Opts = TI.getTargetOpts(); 2565 StringRef CPU = Opts.CPU; 2566 if (!CPU.empty()) { 2567 assert(CPU.startswith("hexagon") && "Unexpected CPU name"); 2568 CPU.consume_front("hexagon"); 2569 SmallVector<StringRef, 3> CPUs; 2570 StringRef(FC->Str).split(CPUs, ','); 2571 if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; })) 2572 return Diag(TheCall->getBeginLoc(), 2573 diag::err_hexagon_builtin_unsupported_cpu); 2574 } 2575 } 2576 2577 const BuiltinAndString *FH = 2578 std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID, 2579 LowerBoundCmp); 2580 if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) { 2581 if (!TI.hasFeature("hvx")) 2582 return Diag(TheCall->getBeginLoc(), 2583 diag::err_hexagon_builtin_requires_hvx); 2584 2585 SmallVector<StringRef, 3> HVXs; 2586 StringRef(FH->Str).split(HVXs, ','); 2587 bool IsValid = llvm::any_of(HVXs, 2588 [&TI] (StringRef V) { 2589 std::string F = "hvx" + V.str(); 2590 return TI.hasFeature(F); 2591 }); 2592 if (!IsValid) 2593 return Diag(TheCall->getBeginLoc(), 2594 diag::err_hexagon_builtin_unsupported_hvx); 2595 } 2596 2597 return false; 2598 } 2599 2600 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2601 struct ArgInfo { 2602 uint8_t OpNum; 2603 bool IsSigned; 2604 uint8_t BitWidth; 2605 uint8_t Align; 2606 }; 2607 struct BuiltinInfo { 2608 unsigned BuiltinID; 2609 ArgInfo Infos[2]; 2610 }; 2611 2612 static BuiltinInfo Infos[] = { 2613 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2614 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2615 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2616 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, 2617 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2618 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2619 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2620 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2621 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2622 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2623 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2624 2625 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2626 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2627 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2628 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2629 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2630 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2631 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2632 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2633 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2634 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2635 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2636 2637 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2638 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2639 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2640 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2641 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2642 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2643 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2644 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2645 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2646 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2647 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2648 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2649 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2650 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2651 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2652 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2653 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2654 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2655 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2656 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2657 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2658 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2659 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2660 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2661 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2662 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2663 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2664 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2665 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2666 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2667 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2668 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2669 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2670 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2671 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2672 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2673 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2674 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2675 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2676 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2677 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2678 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2679 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2680 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2681 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2682 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2683 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2684 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2685 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2686 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2687 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2688 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2689 {{ 1, false, 6, 0 }} }, 2690 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2691 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2692 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2693 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2694 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2695 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2696 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2697 {{ 1, false, 5, 0 }} }, 2698 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2699 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2700 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2701 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2702 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2703 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2704 { 2, false, 5, 0 }} }, 2705 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2706 { 2, false, 6, 0 }} }, 2707 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2708 { 3, false, 5, 0 }} }, 2709 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2710 { 3, false, 6, 0 }} }, 2711 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2712 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2713 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2714 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2715 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2716 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2717 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2718 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2719 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2720 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2721 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2722 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2723 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2724 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2725 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2726 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2727 {{ 2, false, 4, 0 }, 2728 { 3, false, 5, 0 }} }, 2729 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2730 {{ 2, false, 4, 0 }, 2731 { 3, false, 5, 0 }} }, 2732 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2733 {{ 2, false, 4, 0 }, 2734 { 3, false, 5, 0 }} }, 2735 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2736 {{ 2, false, 4, 0 }, 2737 { 3, false, 5, 0 }} }, 2738 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2739 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2740 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2741 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2742 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2743 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2744 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2745 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2746 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2747 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2748 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2749 { 2, false, 5, 0 }} }, 2750 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2751 { 2, false, 6, 0 }} }, 2752 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2753 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2754 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2755 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2756 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2757 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2758 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2759 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2760 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2761 {{ 1, false, 4, 0 }} }, 2762 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2763 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2764 {{ 1, false, 4, 0 }} }, 2765 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2766 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2767 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2768 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2769 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2770 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2771 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2773 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2785 {{ 3, false, 1, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2790 {{ 3, false, 1, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2795 {{ 3, false, 1, 0 }} }, 2796 }; 2797 2798 // Use a dynamically initialized static to sort the table exactly once on 2799 // first run. 2800 static const bool SortOnce = 2801 (std::sort(std::begin(Infos), std::end(Infos), 2802 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2803 return LHS.BuiltinID < RHS.BuiltinID; 2804 }), 2805 true); 2806 (void)SortOnce; 2807 2808 const BuiltinInfo *F = 2809 std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID, 2810 [](const BuiltinInfo &BI, unsigned BuiltinID) { 2811 return BI.BuiltinID < BuiltinID; 2812 }); 2813 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2814 return false; 2815 2816 bool Error = false; 2817 2818 for (const ArgInfo &A : F->Infos) { 2819 // Ignore empty ArgInfo elements. 2820 if (A.BitWidth == 0) 2821 continue; 2822 2823 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2824 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2825 if (!A.Align) { 2826 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2827 } else { 2828 unsigned M = 1 << A.Align; 2829 Min *= M; 2830 Max *= M; 2831 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2832 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2833 } 2834 } 2835 return Error; 2836 } 2837 2838 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2839 CallExpr *TheCall) { 2840 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) || 2841 CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2842 } 2843 2844 2845 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 2846 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2847 // ordering for DSP is unspecified. MSA is ordered by the data format used 2848 // by the underlying instruction i.e., df/m, df/n and then by size. 2849 // 2850 // FIXME: The size tests here should instead be tablegen'd along with the 2851 // definitions from include/clang/Basic/BuiltinsMips.def. 2852 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2853 // be too. 2854 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2855 unsigned i = 0, l = 0, u = 0, m = 0; 2856 switch (BuiltinID) { 2857 default: return false; 2858 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2859 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2860 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2861 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2862 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2863 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2864 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2865 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 2866 // df/m field. 2867 // These intrinsics take an unsigned 3 bit immediate. 2868 case Mips::BI__builtin_msa_bclri_b: 2869 case Mips::BI__builtin_msa_bnegi_b: 2870 case Mips::BI__builtin_msa_bseti_b: 2871 case Mips::BI__builtin_msa_sat_s_b: 2872 case Mips::BI__builtin_msa_sat_u_b: 2873 case Mips::BI__builtin_msa_slli_b: 2874 case Mips::BI__builtin_msa_srai_b: 2875 case Mips::BI__builtin_msa_srari_b: 2876 case Mips::BI__builtin_msa_srli_b: 2877 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 2878 case Mips::BI__builtin_msa_binsli_b: 2879 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 2880 // These intrinsics take an unsigned 4 bit immediate. 2881 case Mips::BI__builtin_msa_bclri_h: 2882 case Mips::BI__builtin_msa_bnegi_h: 2883 case Mips::BI__builtin_msa_bseti_h: 2884 case Mips::BI__builtin_msa_sat_s_h: 2885 case Mips::BI__builtin_msa_sat_u_h: 2886 case Mips::BI__builtin_msa_slli_h: 2887 case Mips::BI__builtin_msa_srai_h: 2888 case Mips::BI__builtin_msa_srari_h: 2889 case Mips::BI__builtin_msa_srli_h: 2890 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 2891 case Mips::BI__builtin_msa_binsli_h: 2892 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2893 // These intrinsics take an unsigned 5 bit immediate. 2894 // The first block of intrinsics actually have an unsigned 5 bit field, 2895 // not a df/n field. 2896 case Mips::BI__builtin_msa_clei_u_b: 2897 case Mips::BI__builtin_msa_clei_u_h: 2898 case Mips::BI__builtin_msa_clei_u_w: 2899 case Mips::BI__builtin_msa_clei_u_d: 2900 case Mips::BI__builtin_msa_clti_u_b: 2901 case Mips::BI__builtin_msa_clti_u_h: 2902 case Mips::BI__builtin_msa_clti_u_w: 2903 case Mips::BI__builtin_msa_clti_u_d: 2904 case Mips::BI__builtin_msa_maxi_u_b: 2905 case Mips::BI__builtin_msa_maxi_u_h: 2906 case Mips::BI__builtin_msa_maxi_u_w: 2907 case Mips::BI__builtin_msa_maxi_u_d: 2908 case Mips::BI__builtin_msa_mini_u_b: 2909 case Mips::BI__builtin_msa_mini_u_h: 2910 case Mips::BI__builtin_msa_mini_u_w: 2911 case Mips::BI__builtin_msa_mini_u_d: 2912 case Mips::BI__builtin_msa_addvi_b: 2913 case Mips::BI__builtin_msa_addvi_h: 2914 case Mips::BI__builtin_msa_addvi_w: 2915 case Mips::BI__builtin_msa_addvi_d: 2916 case Mips::BI__builtin_msa_bclri_w: 2917 case Mips::BI__builtin_msa_bnegi_w: 2918 case Mips::BI__builtin_msa_bseti_w: 2919 case Mips::BI__builtin_msa_sat_s_w: 2920 case Mips::BI__builtin_msa_sat_u_w: 2921 case Mips::BI__builtin_msa_slli_w: 2922 case Mips::BI__builtin_msa_srai_w: 2923 case Mips::BI__builtin_msa_srari_w: 2924 case Mips::BI__builtin_msa_srli_w: 2925 case Mips::BI__builtin_msa_srlri_w: 2926 case Mips::BI__builtin_msa_subvi_b: 2927 case Mips::BI__builtin_msa_subvi_h: 2928 case Mips::BI__builtin_msa_subvi_w: 2929 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2930 case Mips::BI__builtin_msa_binsli_w: 2931 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2932 // These intrinsics take an unsigned 6 bit immediate. 2933 case Mips::BI__builtin_msa_bclri_d: 2934 case Mips::BI__builtin_msa_bnegi_d: 2935 case Mips::BI__builtin_msa_bseti_d: 2936 case Mips::BI__builtin_msa_sat_s_d: 2937 case Mips::BI__builtin_msa_sat_u_d: 2938 case Mips::BI__builtin_msa_slli_d: 2939 case Mips::BI__builtin_msa_srai_d: 2940 case Mips::BI__builtin_msa_srari_d: 2941 case Mips::BI__builtin_msa_srli_d: 2942 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2943 case Mips::BI__builtin_msa_binsli_d: 2944 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2945 // These intrinsics take a signed 5 bit immediate. 2946 case Mips::BI__builtin_msa_ceqi_b: 2947 case Mips::BI__builtin_msa_ceqi_h: 2948 case Mips::BI__builtin_msa_ceqi_w: 2949 case Mips::BI__builtin_msa_ceqi_d: 2950 case Mips::BI__builtin_msa_clti_s_b: 2951 case Mips::BI__builtin_msa_clti_s_h: 2952 case Mips::BI__builtin_msa_clti_s_w: 2953 case Mips::BI__builtin_msa_clti_s_d: 2954 case Mips::BI__builtin_msa_clei_s_b: 2955 case Mips::BI__builtin_msa_clei_s_h: 2956 case Mips::BI__builtin_msa_clei_s_w: 2957 case Mips::BI__builtin_msa_clei_s_d: 2958 case Mips::BI__builtin_msa_maxi_s_b: 2959 case Mips::BI__builtin_msa_maxi_s_h: 2960 case Mips::BI__builtin_msa_maxi_s_w: 2961 case Mips::BI__builtin_msa_maxi_s_d: 2962 case Mips::BI__builtin_msa_mini_s_b: 2963 case Mips::BI__builtin_msa_mini_s_h: 2964 case Mips::BI__builtin_msa_mini_s_w: 2965 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 2966 // These intrinsics take an unsigned 8 bit immediate. 2967 case Mips::BI__builtin_msa_andi_b: 2968 case Mips::BI__builtin_msa_nori_b: 2969 case Mips::BI__builtin_msa_ori_b: 2970 case Mips::BI__builtin_msa_shf_b: 2971 case Mips::BI__builtin_msa_shf_h: 2972 case Mips::BI__builtin_msa_shf_w: 2973 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 2974 case Mips::BI__builtin_msa_bseli_b: 2975 case Mips::BI__builtin_msa_bmnzi_b: 2976 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 2977 // df/n format 2978 // These intrinsics take an unsigned 4 bit immediate. 2979 case Mips::BI__builtin_msa_copy_s_b: 2980 case Mips::BI__builtin_msa_copy_u_b: 2981 case Mips::BI__builtin_msa_insve_b: 2982 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 2983 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 2984 // These intrinsics take an unsigned 3 bit immediate. 2985 case Mips::BI__builtin_msa_copy_s_h: 2986 case Mips::BI__builtin_msa_copy_u_h: 2987 case Mips::BI__builtin_msa_insve_h: 2988 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 2989 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 2990 // These intrinsics take an unsigned 2 bit immediate. 2991 case Mips::BI__builtin_msa_copy_s_w: 2992 case Mips::BI__builtin_msa_copy_u_w: 2993 case Mips::BI__builtin_msa_insve_w: 2994 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 2995 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 2996 // These intrinsics take an unsigned 1 bit immediate. 2997 case Mips::BI__builtin_msa_copy_s_d: 2998 case Mips::BI__builtin_msa_copy_u_d: 2999 case Mips::BI__builtin_msa_insve_d: 3000 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3001 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3002 // Memory offsets and immediate loads. 3003 // These intrinsics take a signed 10 bit immediate. 3004 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3005 case Mips::BI__builtin_msa_ldi_h: 3006 case Mips::BI__builtin_msa_ldi_w: 3007 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3008 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3009 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3010 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3011 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3012 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3013 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3014 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3015 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3016 } 3017 3018 if (!m) 3019 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3020 3021 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3022 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3023 } 3024 3025 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3026 unsigned i = 0, l = 0, u = 0; 3027 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3028 BuiltinID == PPC::BI__builtin_divdeu || 3029 BuiltinID == PPC::BI__builtin_bpermd; 3030 bool IsTarget64Bit = Context.getTargetInfo() 3031 .getTypeWidth(Context 3032 .getTargetInfo() 3033 .getIntPtrType()) == 64; 3034 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3035 BuiltinID == PPC::BI__builtin_divweu || 3036 BuiltinID == PPC::BI__builtin_divde || 3037 BuiltinID == PPC::BI__builtin_divdeu; 3038 3039 if (Is64BitBltin && !IsTarget64Bit) 3040 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3041 << TheCall->getSourceRange(); 3042 3043 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 3044 (BuiltinID == PPC::BI__builtin_bpermd && 3045 !Context.getTargetInfo().hasFeature("bpermd"))) 3046 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3047 << TheCall->getSourceRange(); 3048 3049 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3050 if (!Context.getTargetInfo().hasFeature("vsx")) 3051 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3052 << TheCall->getSourceRange(); 3053 return false; 3054 }; 3055 3056 switch (BuiltinID) { 3057 default: return false; 3058 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3059 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3060 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3061 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3062 case PPC::BI__builtin_tbegin: 3063 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3064 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3065 case PPC::BI__builtin_tabortwc: 3066 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3067 case PPC::BI__builtin_tabortwci: 3068 case PPC::BI__builtin_tabortdci: 3069 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3070 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3071 case PPC::BI__builtin_vsx_xxpermdi: 3072 case PPC::BI__builtin_vsx_xxsldwi: 3073 return SemaBuiltinVSX(TheCall); 3074 case PPC::BI__builtin_unpack_vector_int128: 3075 return SemaVSXCheck(TheCall) || 3076 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3077 case PPC::BI__builtin_pack_vector_int128: 3078 return SemaVSXCheck(TheCall); 3079 } 3080 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3081 } 3082 3083 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3084 CallExpr *TheCall) { 3085 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3086 Expr *Arg = TheCall->getArg(0); 3087 llvm::APSInt AbortCode(32); 3088 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3089 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3090 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3091 << Arg->getSourceRange(); 3092 } 3093 3094 // For intrinsics which take an immediate value as part of the instruction, 3095 // range check them here. 3096 unsigned i = 0, l = 0, u = 0; 3097 switch (BuiltinID) { 3098 default: return false; 3099 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3100 case SystemZ::BI__builtin_s390_verimb: 3101 case SystemZ::BI__builtin_s390_verimh: 3102 case SystemZ::BI__builtin_s390_verimf: 3103 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3104 case SystemZ::BI__builtin_s390_vfaeb: 3105 case SystemZ::BI__builtin_s390_vfaeh: 3106 case SystemZ::BI__builtin_s390_vfaef: 3107 case SystemZ::BI__builtin_s390_vfaebs: 3108 case SystemZ::BI__builtin_s390_vfaehs: 3109 case SystemZ::BI__builtin_s390_vfaefs: 3110 case SystemZ::BI__builtin_s390_vfaezb: 3111 case SystemZ::BI__builtin_s390_vfaezh: 3112 case SystemZ::BI__builtin_s390_vfaezf: 3113 case SystemZ::BI__builtin_s390_vfaezbs: 3114 case SystemZ::BI__builtin_s390_vfaezhs: 3115 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3116 case SystemZ::BI__builtin_s390_vfisb: 3117 case SystemZ::BI__builtin_s390_vfidb: 3118 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3119 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3120 case SystemZ::BI__builtin_s390_vftcisb: 3121 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3122 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3123 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3124 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3125 case SystemZ::BI__builtin_s390_vstrcb: 3126 case SystemZ::BI__builtin_s390_vstrch: 3127 case SystemZ::BI__builtin_s390_vstrcf: 3128 case SystemZ::BI__builtin_s390_vstrczb: 3129 case SystemZ::BI__builtin_s390_vstrczh: 3130 case SystemZ::BI__builtin_s390_vstrczf: 3131 case SystemZ::BI__builtin_s390_vstrcbs: 3132 case SystemZ::BI__builtin_s390_vstrchs: 3133 case SystemZ::BI__builtin_s390_vstrcfs: 3134 case SystemZ::BI__builtin_s390_vstrczbs: 3135 case SystemZ::BI__builtin_s390_vstrczhs: 3136 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3137 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3138 case SystemZ::BI__builtin_s390_vfminsb: 3139 case SystemZ::BI__builtin_s390_vfmaxsb: 3140 case SystemZ::BI__builtin_s390_vfmindb: 3141 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3142 } 3143 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3144 } 3145 3146 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3147 /// This checks that the target supports __builtin_cpu_supports and 3148 /// that the string argument is constant and valid. 3149 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 3150 Expr *Arg = TheCall->getArg(0); 3151 3152 // Check if the argument is a string literal. 3153 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3154 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3155 << Arg->getSourceRange(); 3156 3157 // Check the contents of the string. 3158 StringRef Feature = 3159 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3160 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 3161 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3162 << Arg->getSourceRange(); 3163 return false; 3164 } 3165 3166 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3167 /// This checks that the target supports __builtin_cpu_is and 3168 /// that the string argument is constant and valid. 3169 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 3170 Expr *Arg = TheCall->getArg(0); 3171 3172 // Check if the argument is a string literal. 3173 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3174 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3175 << Arg->getSourceRange(); 3176 3177 // Check the contents of the string. 3178 StringRef Feature = 3179 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3180 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 3181 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3182 << Arg->getSourceRange(); 3183 return false; 3184 } 3185 3186 // Check if the rounding mode is legal. 3187 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3188 // Indicates if this instruction has rounding control or just SAE. 3189 bool HasRC = false; 3190 3191 unsigned ArgNum = 0; 3192 switch (BuiltinID) { 3193 default: 3194 return false; 3195 case X86::BI__builtin_ia32_vcvttsd2si32: 3196 case X86::BI__builtin_ia32_vcvttsd2si64: 3197 case X86::BI__builtin_ia32_vcvttsd2usi32: 3198 case X86::BI__builtin_ia32_vcvttsd2usi64: 3199 case X86::BI__builtin_ia32_vcvttss2si32: 3200 case X86::BI__builtin_ia32_vcvttss2si64: 3201 case X86::BI__builtin_ia32_vcvttss2usi32: 3202 case X86::BI__builtin_ia32_vcvttss2usi64: 3203 ArgNum = 1; 3204 break; 3205 case X86::BI__builtin_ia32_maxpd512: 3206 case X86::BI__builtin_ia32_maxps512: 3207 case X86::BI__builtin_ia32_minpd512: 3208 case X86::BI__builtin_ia32_minps512: 3209 ArgNum = 2; 3210 break; 3211 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3212 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3213 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3214 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3215 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3216 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3217 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3218 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3219 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3220 case X86::BI__builtin_ia32_exp2pd_mask: 3221 case X86::BI__builtin_ia32_exp2ps_mask: 3222 case X86::BI__builtin_ia32_getexppd512_mask: 3223 case X86::BI__builtin_ia32_getexpps512_mask: 3224 case X86::BI__builtin_ia32_rcp28pd_mask: 3225 case X86::BI__builtin_ia32_rcp28ps_mask: 3226 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3227 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3228 case X86::BI__builtin_ia32_vcomisd: 3229 case X86::BI__builtin_ia32_vcomiss: 3230 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3231 ArgNum = 3; 3232 break; 3233 case X86::BI__builtin_ia32_cmppd512_mask: 3234 case X86::BI__builtin_ia32_cmpps512_mask: 3235 case X86::BI__builtin_ia32_cmpsd_mask: 3236 case X86::BI__builtin_ia32_cmpss_mask: 3237 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3238 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3239 case X86::BI__builtin_ia32_getexpss128_round_mask: 3240 case X86::BI__builtin_ia32_maxsd_round_mask: 3241 case X86::BI__builtin_ia32_maxss_round_mask: 3242 case X86::BI__builtin_ia32_minsd_round_mask: 3243 case X86::BI__builtin_ia32_minss_round_mask: 3244 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3245 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3246 case X86::BI__builtin_ia32_reducepd512_mask: 3247 case X86::BI__builtin_ia32_reduceps512_mask: 3248 case X86::BI__builtin_ia32_rndscalepd_mask: 3249 case X86::BI__builtin_ia32_rndscaleps_mask: 3250 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3251 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3252 ArgNum = 4; 3253 break; 3254 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3255 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3256 case X86::BI__builtin_ia32_fixupimmps512_mask: 3257 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3258 case X86::BI__builtin_ia32_fixupimmsd_mask: 3259 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3260 case X86::BI__builtin_ia32_fixupimmss_mask: 3261 case X86::BI__builtin_ia32_fixupimmss_maskz: 3262 case X86::BI__builtin_ia32_rangepd512_mask: 3263 case X86::BI__builtin_ia32_rangeps512_mask: 3264 case X86::BI__builtin_ia32_rangesd128_round_mask: 3265 case X86::BI__builtin_ia32_rangess128_round_mask: 3266 case X86::BI__builtin_ia32_reducesd_mask: 3267 case X86::BI__builtin_ia32_reducess_mask: 3268 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3269 case X86::BI__builtin_ia32_rndscaless_round_mask: 3270 ArgNum = 5; 3271 break; 3272 case X86::BI__builtin_ia32_vcvtsd2si64: 3273 case X86::BI__builtin_ia32_vcvtsd2si32: 3274 case X86::BI__builtin_ia32_vcvtsd2usi32: 3275 case X86::BI__builtin_ia32_vcvtsd2usi64: 3276 case X86::BI__builtin_ia32_vcvtss2si32: 3277 case X86::BI__builtin_ia32_vcvtss2si64: 3278 case X86::BI__builtin_ia32_vcvtss2usi32: 3279 case X86::BI__builtin_ia32_vcvtss2usi64: 3280 case X86::BI__builtin_ia32_sqrtpd512: 3281 case X86::BI__builtin_ia32_sqrtps512: 3282 ArgNum = 1; 3283 HasRC = true; 3284 break; 3285 case X86::BI__builtin_ia32_addpd512: 3286 case X86::BI__builtin_ia32_addps512: 3287 case X86::BI__builtin_ia32_divpd512: 3288 case X86::BI__builtin_ia32_divps512: 3289 case X86::BI__builtin_ia32_mulpd512: 3290 case X86::BI__builtin_ia32_mulps512: 3291 case X86::BI__builtin_ia32_subpd512: 3292 case X86::BI__builtin_ia32_subps512: 3293 case X86::BI__builtin_ia32_cvtsi2sd64: 3294 case X86::BI__builtin_ia32_cvtsi2ss32: 3295 case X86::BI__builtin_ia32_cvtsi2ss64: 3296 case X86::BI__builtin_ia32_cvtusi2sd64: 3297 case X86::BI__builtin_ia32_cvtusi2ss32: 3298 case X86::BI__builtin_ia32_cvtusi2ss64: 3299 ArgNum = 2; 3300 HasRC = true; 3301 break; 3302 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3303 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3304 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3305 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3306 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3307 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3308 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3309 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3310 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3311 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3312 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3313 ArgNum = 3; 3314 HasRC = true; 3315 break; 3316 case X86::BI__builtin_ia32_addss_round_mask: 3317 case X86::BI__builtin_ia32_addsd_round_mask: 3318 case X86::BI__builtin_ia32_divss_round_mask: 3319 case X86::BI__builtin_ia32_divsd_round_mask: 3320 case X86::BI__builtin_ia32_mulss_round_mask: 3321 case X86::BI__builtin_ia32_mulsd_round_mask: 3322 case X86::BI__builtin_ia32_subss_round_mask: 3323 case X86::BI__builtin_ia32_subsd_round_mask: 3324 case X86::BI__builtin_ia32_scalefpd512_mask: 3325 case X86::BI__builtin_ia32_scalefps512_mask: 3326 case X86::BI__builtin_ia32_scalefsd_round_mask: 3327 case X86::BI__builtin_ia32_scalefss_round_mask: 3328 case X86::BI__builtin_ia32_getmantpd512_mask: 3329 case X86::BI__builtin_ia32_getmantps512_mask: 3330 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3331 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3332 case X86::BI__builtin_ia32_sqrtss_round_mask: 3333 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3334 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3335 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3336 case X86::BI__builtin_ia32_vfmaddss3_mask: 3337 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3338 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3339 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3340 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3341 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3342 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3343 case X86::BI__builtin_ia32_vfmaddps512_mask: 3344 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3345 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3346 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3347 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3348 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3349 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3350 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3351 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3352 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3353 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3354 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3355 ArgNum = 4; 3356 HasRC = true; 3357 break; 3358 case X86::BI__builtin_ia32_getmantsd_round_mask: 3359 case X86::BI__builtin_ia32_getmantss_round_mask: 3360 ArgNum = 5; 3361 HasRC = true; 3362 break; 3363 } 3364 3365 llvm::APSInt Result; 3366 3367 // We can't check the value of a dependent argument. 3368 Expr *Arg = TheCall->getArg(ArgNum); 3369 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3370 return false; 3371 3372 // Check constant-ness first. 3373 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3374 return true; 3375 3376 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3377 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3378 // combined with ROUND_NO_EXC. 3379 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3380 Result == 8/*ROUND_NO_EXC*/ || 3381 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3382 return false; 3383 3384 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3385 << Arg->getSourceRange(); 3386 } 3387 3388 // Check if the gather/scatter scale is legal. 3389 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3390 CallExpr *TheCall) { 3391 unsigned ArgNum = 0; 3392 switch (BuiltinID) { 3393 default: 3394 return false; 3395 case X86::BI__builtin_ia32_gatherpfdpd: 3396 case X86::BI__builtin_ia32_gatherpfdps: 3397 case X86::BI__builtin_ia32_gatherpfqpd: 3398 case X86::BI__builtin_ia32_gatherpfqps: 3399 case X86::BI__builtin_ia32_scatterpfdpd: 3400 case X86::BI__builtin_ia32_scatterpfdps: 3401 case X86::BI__builtin_ia32_scatterpfqpd: 3402 case X86::BI__builtin_ia32_scatterpfqps: 3403 ArgNum = 3; 3404 break; 3405 case X86::BI__builtin_ia32_gatherd_pd: 3406 case X86::BI__builtin_ia32_gatherd_pd256: 3407 case X86::BI__builtin_ia32_gatherq_pd: 3408 case X86::BI__builtin_ia32_gatherq_pd256: 3409 case X86::BI__builtin_ia32_gatherd_ps: 3410 case X86::BI__builtin_ia32_gatherd_ps256: 3411 case X86::BI__builtin_ia32_gatherq_ps: 3412 case X86::BI__builtin_ia32_gatherq_ps256: 3413 case X86::BI__builtin_ia32_gatherd_q: 3414 case X86::BI__builtin_ia32_gatherd_q256: 3415 case X86::BI__builtin_ia32_gatherq_q: 3416 case X86::BI__builtin_ia32_gatherq_q256: 3417 case X86::BI__builtin_ia32_gatherd_d: 3418 case X86::BI__builtin_ia32_gatherd_d256: 3419 case X86::BI__builtin_ia32_gatherq_d: 3420 case X86::BI__builtin_ia32_gatherq_d256: 3421 case X86::BI__builtin_ia32_gather3div2df: 3422 case X86::BI__builtin_ia32_gather3div2di: 3423 case X86::BI__builtin_ia32_gather3div4df: 3424 case X86::BI__builtin_ia32_gather3div4di: 3425 case X86::BI__builtin_ia32_gather3div4sf: 3426 case X86::BI__builtin_ia32_gather3div4si: 3427 case X86::BI__builtin_ia32_gather3div8sf: 3428 case X86::BI__builtin_ia32_gather3div8si: 3429 case X86::BI__builtin_ia32_gather3siv2df: 3430 case X86::BI__builtin_ia32_gather3siv2di: 3431 case X86::BI__builtin_ia32_gather3siv4df: 3432 case X86::BI__builtin_ia32_gather3siv4di: 3433 case X86::BI__builtin_ia32_gather3siv4sf: 3434 case X86::BI__builtin_ia32_gather3siv4si: 3435 case X86::BI__builtin_ia32_gather3siv8sf: 3436 case X86::BI__builtin_ia32_gather3siv8si: 3437 case X86::BI__builtin_ia32_gathersiv8df: 3438 case X86::BI__builtin_ia32_gathersiv16sf: 3439 case X86::BI__builtin_ia32_gatherdiv8df: 3440 case X86::BI__builtin_ia32_gatherdiv16sf: 3441 case X86::BI__builtin_ia32_gathersiv8di: 3442 case X86::BI__builtin_ia32_gathersiv16si: 3443 case X86::BI__builtin_ia32_gatherdiv8di: 3444 case X86::BI__builtin_ia32_gatherdiv16si: 3445 case X86::BI__builtin_ia32_scatterdiv2df: 3446 case X86::BI__builtin_ia32_scatterdiv2di: 3447 case X86::BI__builtin_ia32_scatterdiv4df: 3448 case X86::BI__builtin_ia32_scatterdiv4di: 3449 case X86::BI__builtin_ia32_scatterdiv4sf: 3450 case X86::BI__builtin_ia32_scatterdiv4si: 3451 case X86::BI__builtin_ia32_scatterdiv8sf: 3452 case X86::BI__builtin_ia32_scatterdiv8si: 3453 case X86::BI__builtin_ia32_scattersiv2df: 3454 case X86::BI__builtin_ia32_scattersiv2di: 3455 case X86::BI__builtin_ia32_scattersiv4df: 3456 case X86::BI__builtin_ia32_scattersiv4di: 3457 case X86::BI__builtin_ia32_scattersiv4sf: 3458 case X86::BI__builtin_ia32_scattersiv4si: 3459 case X86::BI__builtin_ia32_scattersiv8sf: 3460 case X86::BI__builtin_ia32_scattersiv8si: 3461 case X86::BI__builtin_ia32_scattersiv8df: 3462 case X86::BI__builtin_ia32_scattersiv16sf: 3463 case X86::BI__builtin_ia32_scatterdiv8df: 3464 case X86::BI__builtin_ia32_scatterdiv16sf: 3465 case X86::BI__builtin_ia32_scattersiv8di: 3466 case X86::BI__builtin_ia32_scattersiv16si: 3467 case X86::BI__builtin_ia32_scatterdiv8di: 3468 case X86::BI__builtin_ia32_scatterdiv16si: 3469 ArgNum = 4; 3470 break; 3471 } 3472 3473 llvm::APSInt Result; 3474 3475 // We can't check the value of a dependent argument. 3476 Expr *Arg = TheCall->getArg(ArgNum); 3477 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3478 return false; 3479 3480 // Check constant-ness first. 3481 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3482 return true; 3483 3484 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3485 return false; 3486 3487 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3488 << Arg->getSourceRange(); 3489 } 3490 3491 static bool isX86_32Builtin(unsigned BuiltinID) { 3492 // These builtins only work on x86-32 targets. 3493 switch (BuiltinID) { 3494 case X86::BI__builtin_ia32_readeflags_u32: 3495 case X86::BI__builtin_ia32_writeeflags_u32: 3496 return true; 3497 } 3498 3499 return false; 3500 } 3501 3502 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3503 if (BuiltinID == X86::BI__builtin_cpu_supports) 3504 return SemaBuiltinCpuSupports(*this, TheCall); 3505 3506 if (BuiltinID == X86::BI__builtin_cpu_is) 3507 return SemaBuiltinCpuIs(*this, TheCall); 3508 3509 // Check for 32-bit only builtins on a 64-bit target. 3510 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3511 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3512 return Diag(TheCall->getCallee()->getBeginLoc(), 3513 diag::err_32_bit_builtin_64_bit_tgt); 3514 3515 // If the intrinsic has rounding or SAE make sure its valid. 3516 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3517 return true; 3518 3519 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3520 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3521 return true; 3522 3523 // For intrinsics which take an immediate value as part of the instruction, 3524 // range check them here. 3525 int i = 0, l = 0, u = 0; 3526 switch (BuiltinID) { 3527 default: 3528 return false; 3529 case X86::BI__builtin_ia32_vec_ext_v2si: 3530 case X86::BI__builtin_ia32_vec_ext_v2di: 3531 case X86::BI__builtin_ia32_vextractf128_pd256: 3532 case X86::BI__builtin_ia32_vextractf128_ps256: 3533 case X86::BI__builtin_ia32_vextractf128_si256: 3534 case X86::BI__builtin_ia32_extract128i256: 3535 case X86::BI__builtin_ia32_extractf64x4_mask: 3536 case X86::BI__builtin_ia32_extracti64x4_mask: 3537 case X86::BI__builtin_ia32_extractf32x8_mask: 3538 case X86::BI__builtin_ia32_extracti32x8_mask: 3539 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3540 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3541 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3542 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3543 i = 1; l = 0; u = 1; 3544 break; 3545 case X86::BI__builtin_ia32_vec_set_v2di: 3546 case X86::BI__builtin_ia32_vinsertf128_pd256: 3547 case X86::BI__builtin_ia32_vinsertf128_ps256: 3548 case X86::BI__builtin_ia32_vinsertf128_si256: 3549 case X86::BI__builtin_ia32_insert128i256: 3550 case X86::BI__builtin_ia32_insertf32x8: 3551 case X86::BI__builtin_ia32_inserti32x8: 3552 case X86::BI__builtin_ia32_insertf64x4: 3553 case X86::BI__builtin_ia32_inserti64x4: 3554 case X86::BI__builtin_ia32_insertf64x2_256: 3555 case X86::BI__builtin_ia32_inserti64x2_256: 3556 case X86::BI__builtin_ia32_insertf32x4_256: 3557 case X86::BI__builtin_ia32_inserti32x4_256: 3558 i = 2; l = 0; u = 1; 3559 break; 3560 case X86::BI__builtin_ia32_vpermilpd: 3561 case X86::BI__builtin_ia32_vec_ext_v4hi: 3562 case X86::BI__builtin_ia32_vec_ext_v4si: 3563 case X86::BI__builtin_ia32_vec_ext_v4sf: 3564 case X86::BI__builtin_ia32_vec_ext_v4di: 3565 case X86::BI__builtin_ia32_extractf32x4_mask: 3566 case X86::BI__builtin_ia32_extracti32x4_mask: 3567 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3568 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3569 i = 1; l = 0; u = 3; 3570 break; 3571 case X86::BI_mm_prefetch: 3572 case X86::BI__builtin_ia32_vec_ext_v8hi: 3573 case X86::BI__builtin_ia32_vec_ext_v8si: 3574 i = 1; l = 0; u = 7; 3575 break; 3576 case X86::BI__builtin_ia32_sha1rnds4: 3577 case X86::BI__builtin_ia32_blendpd: 3578 case X86::BI__builtin_ia32_shufpd: 3579 case X86::BI__builtin_ia32_vec_set_v4hi: 3580 case X86::BI__builtin_ia32_vec_set_v4si: 3581 case X86::BI__builtin_ia32_vec_set_v4di: 3582 case X86::BI__builtin_ia32_shuf_f32x4_256: 3583 case X86::BI__builtin_ia32_shuf_f64x2_256: 3584 case X86::BI__builtin_ia32_shuf_i32x4_256: 3585 case X86::BI__builtin_ia32_shuf_i64x2_256: 3586 case X86::BI__builtin_ia32_insertf64x2_512: 3587 case X86::BI__builtin_ia32_inserti64x2_512: 3588 case X86::BI__builtin_ia32_insertf32x4: 3589 case X86::BI__builtin_ia32_inserti32x4: 3590 i = 2; l = 0; u = 3; 3591 break; 3592 case X86::BI__builtin_ia32_vpermil2pd: 3593 case X86::BI__builtin_ia32_vpermil2pd256: 3594 case X86::BI__builtin_ia32_vpermil2ps: 3595 case X86::BI__builtin_ia32_vpermil2ps256: 3596 i = 3; l = 0; u = 3; 3597 break; 3598 case X86::BI__builtin_ia32_cmpb128_mask: 3599 case X86::BI__builtin_ia32_cmpw128_mask: 3600 case X86::BI__builtin_ia32_cmpd128_mask: 3601 case X86::BI__builtin_ia32_cmpq128_mask: 3602 case X86::BI__builtin_ia32_cmpb256_mask: 3603 case X86::BI__builtin_ia32_cmpw256_mask: 3604 case X86::BI__builtin_ia32_cmpd256_mask: 3605 case X86::BI__builtin_ia32_cmpq256_mask: 3606 case X86::BI__builtin_ia32_cmpb512_mask: 3607 case X86::BI__builtin_ia32_cmpw512_mask: 3608 case X86::BI__builtin_ia32_cmpd512_mask: 3609 case X86::BI__builtin_ia32_cmpq512_mask: 3610 case X86::BI__builtin_ia32_ucmpb128_mask: 3611 case X86::BI__builtin_ia32_ucmpw128_mask: 3612 case X86::BI__builtin_ia32_ucmpd128_mask: 3613 case X86::BI__builtin_ia32_ucmpq128_mask: 3614 case X86::BI__builtin_ia32_ucmpb256_mask: 3615 case X86::BI__builtin_ia32_ucmpw256_mask: 3616 case X86::BI__builtin_ia32_ucmpd256_mask: 3617 case X86::BI__builtin_ia32_ucmpq256_mask: 3618 case X86::BI__builtin_ia32_ucmpb512_mask: 3619 case X86::BI__builtin_ia32_ucmpw512_mask: 3620 case X86::BI__builtin_ia32_ucmpd512_mask: 3621 case X86::BI__builtin_ia32_ucmpq512_mask: 3622 case X86::BI__builtin_ia32_vpcomub: 3623 case X86::BI__builtin_ia32_vpcomuw: 3624 case X86::BI__builtin_ia32_vpcomud: 3625 case X86::BI__builtin_ia32_vpcomuq: 3626 case X86::BI__builtin_ia32_vpcomb: 3627 case X86::BI__builtin_ia32_vpcomw: 3628 case X86::BI__builtin_ia32_vpcomd: 3629 case X86::BI__builtin_ia32_vpcomq: 3630 case X86::BI__builtin_ia32_vec_set_v8hi: 3631 case X86::BI__builtin_ia32_vec_set_v8si: 3632 i = 2; l = 0; u = 7; 3633 break; 3634 case X86::BI__builtin_ia32_vpermilpd256: 3635 case X86::BI__builtin_ia32_roundps: 3636 case X86::BI__builtin_ia32_roundpd: 3637 case X86::BI__builtin_ia32_roundps256: 3638 case X86::BI__builtin_ia32_roundpd256: 3639 case X86::BI__builtin_ia32_getmantpd128_mask: 3640 case X86::BI__builtin_ia32_getmantpd256_mask: 3641 case X86::BI__builtin_ia32_getmantps128_mask: 3642 case X86::BI__builtin_ia32_getmantps256_mask: 3643 case X86::BI__builtin_ia32_getmantpd512_mask: 3644 case X86::BI__builtin_ia32_getmantps512_mask: 3645 case X86::BI__builtin_ia32_vec_ext_v16qi: 3646 case X86::BI__builtin_ia32_vec_ext_v16hi: 3647 i = 1; l = 0; u = 15; 3648 break; 3649 case X86::BI__builtin_ia32_pblendd128: 3650 case X86::BI__builtin_ia32_blendps: 3651 case X86::BI__builtin_ia32_blendpd256: 3652 case X86::BI__builtin_ia32_shufpd256: 3653 case X86::BI__builtin_ia32_roundss: 3654 case X86::BI__builtin_ia32_roundsd: 3655 case X86::BI__builtin_ia32_rangepd128_mask: 3656 case X86::BI__builtin_ia32_rangepd256_mask: 3657 case X86::BI__builtin_ia32_rangepd512_mask: 3658 case X86::BI__builtin_ia32_rangeps128_mask: 3659 case X86::BI__builtin_ia32_rangeps256_mask: 3660 case X86::BI__builtin_ia32_rangeps512_mask: 3661 case X86::BI__builtin_ia32_getmantsd_round_mask: 3662 case X86::BI__builtin_ia32_getmantss_round_mask: 3663 case X86::BI__builtin_ia32_vec_set_v16qi: 3664 case X86::BI__builtin_ia32_vec_set_v16hi: 3665 i = 2; l = 0; u = 15; 3666 break; 3667 case X86::BI__builtin_ia32_vec_ext_v32qi: 3668 i = 1; l = 0; u = 31; 3669 break; 3670 case X86::BI__builtin_ia32_cmpps: 3671 case X86::BI__builtin_ia32_cmpss: 3672 case X86::BI__builtin_ia32_cmppd: 3673 case X86::BI__builtin_ia32_cmpsd: 3674 case X86::BI__builtin_ia32_cmpps256: 3675 case X86::BI__builtin_ia32_cmppd256: 3676 case X86::BI__builtin_ia32_cmpps128_mask: 3677 case X86::BI__builtin_ia32_cmppd128_mask: 3678 case X86::BI__builtin_ia32_cmpps256_mask: 3679 case X86::BI__builtin_ia32_cmppd256_mask: 3680 case X86::BI__builtin_ia32_cmpps512_mask: 3681 case X86::BI__builtin_ia32_cmppd512_mask: 3682 case X86::BI__builtin_ia32_cmpsd_mask: 3683 case X86::BI__builtin_ia32_cmpss_mask: 3684 case X86::BI__builtin_ia32_vec_set_v32qi: 3685 i = 2; l = 0; u = 31; 3686 break; 3687 case X86::BI__builtin_ia32_permdf256: 3688 case X86::BI__builtin_ia32_permdi256: 3689 case X86::BI__builtin_ia32_permdf512: 3690 case X86::BI__builtin_ia32_permdi512: 3691 case X86::BI__builtin_ia32_vpermilps: 3692 case X86::BI__builtin_ia32_vpermilps256: 3693 case X86::BI__builtin_ia32_vpermilpd512: 3694 case X86::BI__builtin_ia32_vpermilps512: 3695 case X86::BI__builtin_ia32_pshufd: 3696 case X86::BI__builtin_ia32_pshufd256: 3697 case X86::BI__builtin_ia32_pshufd512: 3698 case X86::BI__builtin_ia32_pshufhw: 3699 case X86::BI__builtin_ia32_pshufhw256: 3700 case X86::BI__builtin_ia32_pshufhw512: 3701 case X86::BI__builtin_ia32_pshuflw: 3702 case X86::BI__builtin_ia32_pshuflw256: 3703 case X86::BI__builtin_ia32_pshuflw512: 3704 case X86::BI__builtin_ia32_vcvtps2ph: 3705 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3706 case X86::BI__builtin_ia32_vcvtps2ph256: 3707 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3708 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3709 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3710 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3711 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3712 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3713 case X86::BI__builtin_ia32_rndscaleps_mask: 3714 case X86::BI__builtin_ia32_rndscalepd_mask: 3715 case X86::BI__builtin_ia32_reducepd128_mask: 3716 case X86::BI__builtin_ia32_reducepd256_mask: 3717 case X86::BI__builtin_ia32_reducepd512_mask: 3718 case X86::BI__builtin_ia32_reduceps128_mask: 3719 case X86::BI__builtin_ia32_reduceps256_mask: 3720 case X86::BI__builtin_ia32_reduceps512_mask: 3721 case X86::BI__builtin_ia32_prold512: 3722 case X86::BI__builtin_ia32_prolq512: 3723 case X86::BI__builtin_ia32_prold128: 3724 case X86::BI__builtin_ia32_prold256: 3725 case X86::BI__builtin_ia32_prolq128: 3726 case X86::BI__builtin_ia32_prolq256: 3727 case X86::BI__builtin_ia32_prord512: 3728 case X86::BI__builtin_ia32_prorq512: 3729 case X86::BI__builtin_ia32_prord128: 3730 case X86::BI__builtin_ia32_prord256: 3731 case X86::BI__builtin_ia32_prorq128: 3732 case X86::BI__builtin_ia32_prorq256: 3733 case X86::BI__builtin_ia32_fpclasspd128_mask: 3734 case X86::BI__builtin_ia32_fpclasspd256_mask: 3735 case X86::BI__builtin_ia32_fpclassps128_mask: 3736 case X86::BI__builtin_ia32_fpclassps256_mask: 3737 case X86::BI__builtin_ia32_fpclassps512_mask: 3738 case X86::BI__builtin_ia32_fpclasspd512_mask: 3739 case X86::BI__builtin_ia32_fpclasssd_mask: 3740 case X86::BI__builtin_ia32_fpclassss_mask: 3741 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3742 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3743 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3744 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3745 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3746 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3747 case X86::BI__builtin_ia32_kshiftliqi: 3748 case X86::BI__builtin_ia32_kshiftlihi: 3749 case X86::BI__builtin_ia32_kshiftlisi: 3750 case X86::BI__builtin_ia32_kshiftlidi: 3751 case X86::BI__builtin_ia32_kshiftriqi: 3752 case X86::BI__builtin_ia32_kshiftrihi: 3753 case X86::BI__builtin_ia32_kshiftrisi: 3754 case X86::BI__builtin_ia32_kshiftridi: 3755 i = 1; l = 0; u = 255; 3756 break; 3757 case X86::BI__builtin_ia32_vperm2f128_pd256: 3758 case X86::BI__builtin_ia32_vperm2f128_ps256: 3759 case X86::BI__builtin_ia32_vperm2f128_si256: 3760 case X86::BI__builtin_ia32_permti256: 3761 case X86::BI__builtin_ia32_pblendw128: 3762 case X86::BI__builtin_ia32_pblendw256: 3763 case X86::BI__builtin_ia32_blendps256: 3764 case X86::BI__builtin_ia32_pblendd256: 3765 case X86::BI__builtin_ia32_palignr128: 3766 case X86::BI__builtin_ia32_palignr256: 3767 case X86::BI__builtin_ia32_palignr512: 3768 case X86::BI__builtin_ia32_alignq512: 3769 case X86::BI__builtin_ia32_alignd512: 3770 case X86::BI__builtin_ia32_alignd128: 3771 case X86::BI__builtin_ia32_alignd256: 3772 case X86::BI__builtin_ia32_alignq128: 3773 case X86::BI__builtin_ia32_alignq256: 3774 case X86::BI__builtin_ia32_vcomisd: 3775 case X86::BI__builtin_ia32_vcomiss: 3776 case X86::BI__builtin_ia32_shuf_f32x4: 3777 case X86::BI__builtin_ia32_shuf_f64x2: 3778 case X86::BI__builtin_ia32_shuf_i32x4: 3779 case X86::BI__builtin_ia32_shuf_i64x2: 3780 case X86::BI__builtin_ia32_shufpd512: 3781 case X86::BI__builtin_ia32_shufps: 3782 case X86::BI__builtin_ia32_shufps256: 3783 case X86::BI__builtin_ia32_shufps512: 3784 case X86::BI__builtin_ia32_dbpsadbw128: 3785 case X86::BI__builtin_ia32_dbpsadbw256: 3786 case X86::BI__builtin_ia32_dbpsadbw512: 3787 case X86::BI__builtin_ia32_vpshldd128: 3788 case X86::BI__builtin_ia32_vpshldd256: 3789 case X86::BI__builtin_ia32_vpshldd512: 3790 case X86::BI__builtin_ia32_vpshldq128: 3791 case X86::BI__builtin_ia32_vpshldq256: 3792 case X86::BI__builtin_ia32_vpshldq512: 3793 case X86::BI__builtin_ia32_vpshldw128: 3794 case X86::BI__builtin_ia32_vpshldw256: 3795 case X86::BI__builtin_ia32_vpshldw512: 3796 case X86::BI__builtin_ia32_vpshrdd128: 3797 case X86::BI__builtin_ia32_vpshrdd256: 3798 case X86::BI__builtin_ia32_vpshrdd512: 3799 case X86::BI__builtin_ia32_vpshrdq128: 3800 case X86::BI__builtin_ia32_vpshrdq256: 3801 case X86::BI__builtin_ia32_vpshrdq512: 3802 case X86::BI__builtin_ia32_vpshrdw128: 3803 case X86::BI__builtin_ia32_vpshrdw256: 3804 case X86::BI__builtin_ia32_vpshrdw512: 3805 i = 2; l = 0; u = 255; 3806 break; 3807 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3808 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3809 case X86::BI__builtin_ia32_fixupimmps512_mask: 3810 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3811 case X86::BI__builtin_ia32_fixupimmsd_mask: 3812 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3813 case X86::BI__builtin_ia32_fixupimmss_mask: 3814 case X86::BI__builtin_ia32_fixupimmss_maskz: 3815 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3816 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3817 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3818 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3819 case X86::BI__builtin_ia32_fixupimmps128_mask: 3820 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3821 case X86::BI__builtin_ia32_fixupimmps256_mask: 3822 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3823 case X86::BI__builtin_ia32_pternlogd512_mask: 3824 case X86::BI__builtin_ia32_pternlogd512_maskz: 3825 case X86::BI__builtin_ia32_pternlogq512_mask: 3826 case X86::BI__builtin_ia32_pternlogq512_maskz: 3827 case X86::BI__builtin_ia32_pternlogd128_mask: 3828 case X86::BI__builtin_ia32_pternlogd128_maskz: 3829 case X86::BI__builtin_ia32_pternlogd256_mask: 3830 case X86::BI__builtin_ia32_pternlogd256_maskz: 3831 case X86::BI__builtin_ia32_pternlogq128_mask: 3832 case X86::BI__builtin_ia32_pternlogq128_maskz: 3833 case X86::BI__builtin_ia32_pternlogq256_mask: 3834 case X86::BI__builtin_ia32_pternlogq256_maskz: 3835 i = 3; l = 0; u = 255; 3836 break; 3837 case X86::BI__builtin_ia32_gatherpfdpd: 3838 case X86::BI__builtin_ia32_gatherpfdps: 3839 case X86::BI__builtin_ia32_gatherpfqpd: 3840 case X86::BI__builtin_ia32_gatherpfqps: 3841 case X86::BI__builtin_ia32_scatterpfdpd: 3842 case X86::BI__builtin_ia32_scatterpfdps: 3843 case X86::BI__builtin_ia32_scatterpfqpd: 3844 case X86::BI__builtin_ia32_scatterpfqps: 3845 i = 4; l = 2; u = 3; 3846 break; 3847 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3848 case X86::BI__builtin_ia32_rndscaless_round_mask: 3849 i = 4; l = 0; u = 255; 3850 break; 3851 } 3852 3853 // Note that we don't force a hard error on the range check here, allowing 3854 // template-generated or macro-generated dead code to potentially have out-of- 3855 // range values. These need to code generate, but don't need to necessarily 3856 // make any sense. We use a warning that defaults to an error. 3857 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 3858 } 3859 3860 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 3861 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 3862 /// Returns true when the format fits the function and the FormatStringInfo has 3863 /// been populated. 3864 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 3865 FormatStringInfo *FSI) { 3866 FSI->HasVAListArg = Format->getFirstArg() == 0; 3867 FSI->FormatIdx = Format->getFormatIdx() - 1; 3868 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 3869 3870 // The way the format attribute works in GCC, the implicit this argument 3871 // of member functions is counted. However, it doesn't appear in our own 3872 // lists, so decrement format_idx in that case. 3873 if (IsCXXMember) { 3874 if(FSI->FormatIdx == 0) 3875 return false; 3876 --FSI->FormatIdx; 3877 if (FSI->FirstDataArg != 0) 3878 --FSI->FirstDataArg; 3879 } 3880 return true; 3881 } 3882 3883 /// Checks if a the given expression evaluates to null. 3884 /// 3885 /// Returns true if the value evaluates to null. 3886 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 3887 // If the expression has non-null type, it doesn't evaluate to null. 3888 if (auto nullability 3889 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 3890 if (*nullability == NullabilityKind::NonNull) 3891 return false; 3892 } 3893 3894 // As a special case, transparent unions initialized with zero are 3895 // considered null for the purposes of the nonnull attribute. 3896 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 3897 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3898 if (const CompoundLiteralExpr *CLE = 3899 dyn_cast<CompoundLiteralExpr>(Expr)) 3900 if (const InitListExpr *ILE = 3901 dyn_cast<InitListExpr>(CLE->getInitializer())) 3902 Expr = ILE->getInit(0); 3903 } 3904 3905 bool Result; 3906 return (!Expr->isValueDependent() && 3907 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 3908 !Result); 3909 } 3910 3911 static void CheckNonNullArgument(Sema &S, 3912 const Expr *ArgExpr, 3913 SourceLocation CallSiteLoc) { 3914 if (CheckNonNullExpr(S, ArgExpr)) 3915 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 3916 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 3917 } 3918 3919 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 3920 FormatStringInfo FSI; 3921 if ((GetFormatStringType(Format) == FST_NSString) && 3922 getFormatStringInfo(Format, false, &FSI)) { 3923 Idx = FSI.FormatIdx; 3924 return true; 3925 } 3926 return false; 3927 } 3928 3929 /// Diagnose use of %s directive in an NSString which is being passed 3930 /// as formatting string to formatting method. 3931 static void 3932 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 3933 const NamedDecl *FDecl, 3934 Expr **Args, 3935 unsigned NumArgs) { 3936 unsigned Idx = 0; 3937 bool Format = false; 3938 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 3939 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 3940 Idx = 2; 3941 Format = true; 3942 } 3943 else 3944 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3945 if (S.GetFormatNSStringIdx(I, Idx)) { 3946 Format = true; 3947 break; 3948 } 3949 } 3950 if (!Format || NumArgs <= Idx) 3951 return; 3952 const Expr *FormatExpr = Args[Idx]; 3953 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 3954 FormatExpr = CSCE->getSubExpr(); 3955 const StringLiteral *FormatString; 3956 if (const ObjCStringLiteral *OSL = 3957 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 3958 FormatString = OSL->getString(); 3959 else 3960 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 3961 if (!FormatString) 3962 return; 3963 if (S.FormatStringHasSArg(FormatString)) { 3964 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 3965 << "%s" << 1 << 1; 3966 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 3967 << FDecl->getDeclName(); 3968 } 3969 } 3970 3971 /// Determine whether the given type has a non-null nullability annotation. 3972 static bool isNonNullType(ASTContext &ctx, QualType type) { 3973 if (auto nullability = type->getNullability(ctx)) 3974 return *nullability == NullabilityKind::NonNull; 3975 3976 return false; 3977 } 3978 3979 static void CheckNonNullArguments(Sema &S, 3980 const NamedDecl *FDecl, 3981 const FunctionProtoType *Proto, 3982 ArrayRef<const Expr *> Args, 3983 SourceLocation CallSiteLoc) { 3984 assert((FDecl || Proto) && "Need a function declaration or prototype"); 3985 3986 // Check the attributes attached to the method/function itself. 3987 llvm::SmallBitVector NonNullArgs; 3988 if (FDecl) { 3989 // Handle the nonnull attribute on the function/method declaration itself. 3990 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 3991 if (!NonNull->args_size()) { 3992 // Easy case: all pointer arguments are nonnull. 3993 for (const auto *Arg : Args) 3994 if (S.isValidPointerAttrType(Arg->getType())) 3995 CheckNonNullArgument(S, Arg, CallSiteLoc); 3996 return; 3997 } 3998 3999 for (const ParamIdx &Idx : NonNull->args()) { 4000 unsigned IdxAST = Idx.getASTIndex(); 4001 if (IdxAST >= Args.size()) 4002 continue; 4003 if (NonNullArgs.empty()) 4004 NonNullArgs.resize(Args.size()); 4005 NonNullArgs.set(IdxAST); 4006 } 4007 } 4008 } 4009 4010 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4011 // Handle the nonnull attribute on the parameters of the 4012 // function/method. 4013 ArrayRef<ParmVarDecl*> parms; 4014 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4015 parms = FD->parameters(); 4016 else 4017 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4018 4019 unsigned ParamIndex = 0; 4020 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4021 I != E; ++I, ++ParamIndex) { 4022 const ParmVarDecl *PVD = *I; 4023 if (PVD->hasAttr<NonNullAttr>() || 4024 isNonNullType(S.Context, PVD->getType())) { 4025 if (NonNullArgs.empty()) 4026 NonNullArgs.resize(Args.size()); 4027 4028 NonNullArgs.set(ParamIndex); 4029 } 4030 } 4031 } else { 4032 // If we have a non-function, non-method declaration but no 4033 // function prototype, try to dig out the function prototype. 4034 if (!Proto) { 4035 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4036 QualType type = VD->getType().getNonReferenceType(); 4037 if (auto pointerType = type->getAs<PointerType>()) 4038 type = pointerType->getPointeeType(); 4039 else if (auto blockType = type->getAs<BlockPointerType>()) 4040 type = blockType->getPointeeType(); 4041 // FIXME: data member pointers? 4042 4043 // Dig out the function prototype, if there is one. 4044 Proto = type->getAs<FunctionProtoType>(); 4045 } 4046 } 4047 4048 // Fill in non-null argument information from the nullability 4049 // information on the parameter types (if we have them). 4050 if (Proto) { 4051 unsigned Index = 0; 4052 for (auto paramType : Proto->getParamTypes()) { 4053 if (isNonNullType(S.Context, paramType)) { 4054 if (NonNullArgs.empty()) 4055 NonNullArgs.resize(Args.size()); 4056 4057 NonNullArgs.set(Index); 4058 } 4059 4060 ++Index; 4061 } 4062 } 4063 } 4064 4065 // Check for non-null arguments. 4066 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4067 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4068 if (NonNullArgs[ArgIndex]) 4069 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4070 } 4071 } 4072 4073 /// Handles the checks for format strings, non-POD arguments to vararg 4074 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4075 /// attributes. 4076 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4077 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4078 bool IsMemberFunction, SourceLocation Loc, 4079 SourceRange Range, VariadicCallType CallType) { 4080 // FIXME: We should check as much as we can in the template definition. 4081 if (CurContext->isDependentContext()) 4082 return; 4083 4084 // Printf and scanf checking. 4085 llvm::SmallBitVector CheckedVarArgs; 4086 if (FDecl) { 4087 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4088 // Only create vector if there are format attributes. 4089 CheckedVarArgs.resize(Args.size()); 4090 4091 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4092 CheckedVarArgs); 4093 } 4094 } 4095 4096 // Refuse POD arguments that weren't caught by the format string 4097 // checks above. 4098 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4099 if (CallType != VariadicDoesNotApply && 4100 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4101 unsigned NumParams = Proto ? Proto->getNumParams() 4102 : FDecl && isa<FunctionDecl>(FDecl) 4103 ? cast<FunctionDecl>(FDecl)->getNumParams() 4104 : FDecl && isa<ObjCMethodDecl>(FDecl) 4105 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4106 : 0; 4107 4108 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4109 // Args[ArgIdx] can be null in malformed code. 4110 if (const Expr *Arg = Args[ArgIdx]) { 4111 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4112 checkVariadicArgument(Arg, CallType); 4113 } 4114 } 4115 } 4116 4117 if (FDecl || Proto) { 4118 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4119 4120 // Type safety checking. 4121 if (FDecl) { 4122 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4123 CheckArgumentWithTypeTag(I, Args, Loc); 4124 } 4125 } 4126 4127 if (FD) 4128 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4129 } 4130 4131 /// CheckConstructorCall - Check a constructor call for correctness and safety 4132 /// properties not enforced by the C type system. 4133 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4134 ArrayRef<const Expr *> Args, 4135 const FunctionProtoType *Proto, 4136 SourceLocation Loc) { 4137 VariadicCallType CallType = 4138 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4139 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4140 Loc, SourceRange(), CallType); 4141 } 4142 4143 /// CheckFunctionCall - Check a direct function call for various correctness 4144 /// and safety properties not strictly enforced by the C type system. 4145 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4146 const FunctionProtoType *Proto) { 4147 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4148 isa<CXXMethodDecl>(FDecl); 4149 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4150 IsMemberOperatorCall; 4151 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4152 TheCall->getCallee()); 4153 Expr** Args = TheCall->getArgs(); 4154 unsigned NumArgs = TheCall->getNumArgs(); 4155 4156 Expr *ImplicitThis = nullptr; 4157 if (IsMemberOperatorCall) { 4158 // If this is a call to a member operator, hide the first argument 4159 // from checkCall. 4160 // FIXME: Our choice of AST representation here is less than ideal. 4161 ImplicitThis = Args[0]; 4162 ++Args; 4163 --NumArgs; 4164 } else if (IsMemberFunction) 4165 ImplicitThis = 4166 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4167 4168 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4169 IsMemberFunction, TheCall->getRParenLoc(), 4170 TheCall->getCallee()->getSourceRange(), CallType); 4171 4172 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4173 // None of the checks below are needed for functions that don't have 4174 // simple names (e.g., C++ conversion functions). 4175 if (!FnInfo) 4176 return false; 4177 4178 CheckAbsoluteValueFunction(TheCall, FDecl); 4179 CheckMaxUnsignedZero(TheCall, FDecl); 4180 4181 if (getLangOpts().ObjC) 4182 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4183 4184 unsigned CMId = FDecl->getMemoryFunctionKind(); 4185 if (CMId == 0) 4186 return false; 4187 4188 // Handle memory setting and copying functions. 4189 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4190 CheckStrlcpycatArguments(TheCall, FnInfo); 4191 else if (CMId == Builtin::BIstrncat) 4192 CheckStrncatArguments(TheCall, FnInfo); 4193 else 4194 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4195 4196 return false; 4197 } 4198 4199 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4200 ArrayRef<const Expr *> Args) { 4201 VariadicCallType CallType = 4202 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4203 4204 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4205 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4206 CallType); 4207 4208 return false; 4209 } 4210 4211 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4212 const FunctionProtoType *Proto) { 4213 QualType Ty; 4214 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4215 Ty = V->getType().getNonReferenceType(); 4216 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4217 Ty = F->getType().getNonReferenceType(); 4218 else 4219 return false; 4220 4221 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4222 !Ty->isFunctionProtoType()) 4223 return false; 4224 4225 VariadicCallType CallType; 4226 if (!Proto || !Proto->isVariadic()) { 4227 CallType = VariadicDoesNotApply; 4228 } else if (Ty->isBlockPointerType()) { 4229 CallType = VariadicBlock; 4230 } else { // Ty->isFunctionPointerType() 4231 CallType = VariadicFunction; 4232 } 4233 4234 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4235 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4236 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4237 TheCall->getCallee()->getSourceRange(), CallType); 4238 4239 return false; 4240 } 4241 4242 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4243 /// such as function pointers returned from functions. 4244 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4245 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4246 TheCall->getCallee()); 4247 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4248 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4249 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4250 TheCall->getCallee()->getSourceRange(), CallType); 4251 4252 return false; 4253 } 4254 4255 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4256 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4257 return false; 4258 4259 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4260 switch (Op) { 4261 case AtomicExpr::AO__c11_atomic_init: 4262 case AtomicExpr::AO__opencl_atomic_init: 4263 llvm_unreachable("There is no ordering argument for an init"); 4264 4265 case AtomicExpr::AO__c11_atomic_load: 4266 case AtomicExpr::AO__opencl_atomic_load: 4267 case AtomicExpr::AO__atomic_load_n: 4268 case AtomicExpr::AO__atomic_load: 4269 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4270 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4271 4272 case AtomicExpr::AO__c11_atomic_store: 4273 case AtomicExpr::AO__opencl_atomic_store: 4274 case AtomicExpr::AO__atomic_store: 4275 case AtomicExpr::AO__atomic_store_n: 4276 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4277 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4278 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4279 4280 default: 4281 return true; 4282 } 4283 } 4284 4285 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4286 AtomicExpr::AtomicOp Op) { 4287 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4288 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4289 4290 // All the non-OpenCL operations take one of the following forms. 4291 // The OpenCL operations take the __c11 forms with one extra argument for 4292 // synchronization scope. 4293 enum { 4294 // C __c11_atomic_init(A *, C) 4295 Init, 4296 4297 // C __c11_atomic_load(A *, int) 4298 Load, 4299 4300 // void __atomic_load(A *, CP, int) 4301 LoadCopy, 4302 4303 // void __atomic_store(A *, CP, int) 4304 Copy, 4305 4306 // C __c11_atomic_add(A *, M, int) 4307 Arithmetic, 4308 4309 // C __atomic_exchange_n(A *, CP, int) 4310 Xchg, 4311 4312 // void __atomic_exchange(A *, C *, CP, int) 4313 GNUXchg, 4314 4315 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4316 C11CmpXchg, 4317 4318 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4319 GNUCmpXchg 4320 } Form = Init; 4321 4322 const unsigned NumForm = GNUCmpXchg + 1; 4323 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4324 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4325 // where: 4326 // C is an appropriate type, 4327 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4328 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4329 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4330 // the int parameters are for orderings. 4331 4332 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4333 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4334 "need to update code for modified forms"); 4335 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4336 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 4337 AtomicExpr::AO__atomic_load, 4338 "need to update code for modified C11 atomics"); 4339 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4340 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4341 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4342 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 4343 IsOpenCL; 4344 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4345 Op == AtomicExpr::AO__atomic_store_n || 4346 Op == AtomicExpr::AO__atomic_exchange_n || 4347 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4348 bool IsAddSub = false; 4349 bool IsMinMax = false; 4350 4351 switch (Op) { 4352 case AtomicExpr::AO__c11_atomic_init: 4353 case AtomicExpr::AO__opencl_atomic_init: 4354 Form = Init; 4355 break; 4356 4357 case AtomicExpr::AO__c11_atomic_load: 4358 case AtomicExpr::AO__opencl_atomic_load: 4359 case AtomicExpr::AO__atomic_load_n: 4360 Form = Load; 4361 break; 4362 4363 case AtomicExpr::AO__atomic_load: 4364 Form = LoadCopy; 4365 break; 4366 4367 case AtomicExpr::AO__c11_atomic_store: 4368 case AtomicExpr::AO__opencl_atomic_store: 4369 case AtomicExpr::AO__atomic_store: 4370 case AtomicExpr::AO__atomic_store_n: 4371 Form = Copy; 4372 break; 4373 4374 case AtomicExpr::AO__c11_atomic_fetch_add: 4375 case AtomicExpr::AO__c11_atomic_fetch_sub: 4376 case AtomicExpr::AO__opencl_atomic_fetch_add: 4377 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4378 case AtomicExpr::AO__opencl_atomic_fetch_min: 4379 case AtomicExpr::AO__opencl_atomic_fetch_max: 4380 case AtomicExpr::AO__atomic_fetch_add: 4381 case AtomicExpr::AO__atomic_fetch_sub: 4382 case AtomicExpr::AO__atomic_add_fetch: 4383 case AtomicExpr::AO__atomic_sub_fetch: 4384 IsAddSub = true; 4385 LLVM_FALLTHROUGH; 4386 case AtomicExpr::AO__c11_atomic_fetch_and: 4387 case AtomicExpr::AO__c11_atomic_fetch_or: 4388 case AtomicExpr::AO__c11_atomic_fetch_xor: 4389 case AtomicExpr::AO__opencl_atomic_fetch_and: 4390 case AtomicExpr::AO__opencl_atomic_fetch_or: 4391 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4392 case AtomicExpr::AO__atomic_fetch_and: 4393 case AtomicExpr::AO__atomic_fetch_or: 4394 case AtomicExpr::AO__atomic_fetch_xor: 4395 case AtomicExpr::AO__atomic_fetch_nand: 4396 case AtomicExpr::AO__atomic_and_fetch: 4397 case AtomicExpr::AO__atomic_or_fetch: 4398 case AtomicExpr::AO__atomic_xor_fetch: 4399 case AtomicExpr::AO__atomic_nand_fetch: 4400 Form = Arithmetic; 4401 break; 4402 4403 case AtomicExpr::AO__atomic_fetch_min: 4404 case AtomicExpr::AO__atomic_fetch_max: 4405 IsMinMax = true; 4406 Form = Arithmetic; 4407 break; 4408 4409 case AtomicExpr::AO__c11_atomic_exchange: 4410 case AtomicExpr::AO__opencl_atomic_exchange: 4411 case AtomicExpr::AO__atomic_exchange_n: 4412 Form = Xchg; 4413 break; 4414 4415 case AtomicExpr::AO__atomic_exchange: 4416 Form = GNUXchg; 4417 break; 4418 4419 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4420 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4421 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4422 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4423 Form = C11CmpXchg; 4424 break; 4425 4426 case AtomicExpr::AO__atomic_compare_exchange: 4427 case AtomicExpr::AO__atomic_compare_exchange_n: 4428 Form = GNUCmpXchg; 4429 break; 4430 } 4431 4432 unsigned AdjustedNumArgs = NumArgs[Form]; 4433 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4434 ++AdjustedNumArgs; 4435 // Check we have the right number of arguments. 4436 if (TheCall->getNumArgs() < AdjustedNumArgs) { 4437 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 4438 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4439 << TheCall->getCallee()->getSourceRange(); 4440 return ExprError(); 4441 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 4442 Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(), 4443 diag::err_typecheck_call_too_many_args) 4444 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4445 << TheCall->getCallee()->getSourceRange(); 4446 return ExprError(); 4447 } 4448 4449 // Inspect the first argument of the atomic operation. 4450 Expr *Ptr = TheCall->getArg(0); 4451 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4452 if (ConvertedPtr.isInvalid()) 4453 return ExprError(); 4454 4455 Ptr = ConvertedPtr.get(); 4456 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4457 if (!pointerType) { 4458 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4459 << Ptr->getType() << Ptr->getSourceRange(); 4460 return ExprError(); 4461 } 4462 4463 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4464 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4465 QualType ValType = AtomTy; // 'C' 4466 if (IsC11) { 4467 if (!AtomTy->isAtomicType()) { 4468 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic) 4469 << Ptr->getType() << Ptr->getSourceRange(); 4470 return ExprError(); 4471 } 4472 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4473 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4474 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic) 4475 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4476 << Ptr->getSourceRange(); 4477 return ExprError(); 4478 } 4479 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 4480 } else if (Form != Load && Form != LoadCopy) { 4481 if (ValType.isConstQualified()) { 4482 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer) 4483 << Ptr->getType() << Ptr->getSourceRange(); 4484 return ExprError(); 4485 } 4486 } 4487 4488 // For an arithmetic operation, the implied arithmetic must be well-formed. 4489 if (Form == Arithmetic) { 4490 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4491 if (IsAddSub && !ValType->isIntegerType() 4492 && !ValType->isPointerType()) { 4493 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4494 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4495 return ExprError(); 4496 } 4497 if (IsMinMax) { 4498 const BuiltinType *BT = ValType->getAs<BuiltinType>(); 4499 if (!BT || (BT->getKind() != BuiltinType::Int && 4500 BT->getKind() != BuiltinType::UInt)) { 4501 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr); 4502 return ExprError(); 4503 } 4504 } 4505 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) { 4506 Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int) 4507 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4508 return ExprError(); 4509 } 4510 if (IsC11 && ValType->isPointerType() && 4511 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4512 diag::err_incomplete_type)) { 4513 return ExprError(); 4514 } 4515 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4516 // For __atomic_*_n operations, the value type must be a scalar integral or 4517 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4518 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4519 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4520 return ExprError(); 4521 } 4522 4523 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4524 !AtomTy->isScalarType()) { 4525 // For GNU atomics, require a trivially-copyable type. This is not part of 4526 // the GNU atomics specification, but we enforce it for sanity. 4527 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy) 4528 << Ptr->getType() << Ptr->getSourceRange(); 4529 return ExprError(); 4530 } 4531 4532 switch (ValType.getObjCLifetime()) { 4533 case Qualifiers::OCL_None: 4534 case Qualifiers::OCL_ExplicitNone: 4535 // okay 4536 break; 4537 4538 case Qualifiers::OCL_Weak: 4539 case Qualifiers::OCL_Strong: 4540 case Qualifiers::OCL_Autoreleasing: 4541 // FIXME: Can this happen? By this point, ValType should be known 4542 // to be trivially copyable. 4543 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4544 << ValType << Ptr->getSourceRange(); 4545 return ExprError(); 4546 } 4547 4548 // All atomic operations have an overload which takes a pointer to a volatile 4549 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4550 // into the result or the other operands. Similarly atomic_load takes a 4551 // pointer to a const 'A'. 4552 ValType.removeLocalVolatile(); 4553 ValType.removeLocalConst(); 4554 QualType ResultType = ValType; 4555 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4556 Form == Init) 4557 ResultType = Context.VoidTy; 4558 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4559 ResultType = Context.BoolTy; 4560 4561 // The type of a parameter passed 'by value'. In the GNU atomics, such 4562 // arguments are actually passed as pointers. 4563 QualType ByValType = ValType; // 'CP' 4564 bool IsPassedByAddress = false; 4565 if (!IsC11 && !IsN) { 4566 ByValType = Ptr->getType(); 4567 IsPassedByAddress = true; 4568 } 4569 4570 // The first argument's non-CV pointer type is used to deduce the type of 4571 // subsequent arguments, except for: 4572 // - weak flag (always converted to bool) 4573 // - memory order (always converted to int) 4574 // - scope (always converted to int) 4575 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 4576 QualType Ty; 4577 if (i < NumVals[Form] + 1) { 4578 switch (i) { 4579 case 0: 4580 // The first argument is always a pointer. It has a fixed type. 4581 // It is always dereferenced, a nullptr is undefined. 4582 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4583 // Nothing else to do: we already know all we want about this pointer. 4584 continue; 4585 case 1: 4586 // The second argument is the non-atomic operand. For arithmetic, this 4587 // is always passed by value, and for a compare_exchange it is always 4588 // passed by address. For the rest, GNU uses by-address and C11 uses 4589 // by-value. 4590 assert(Form != Load); 4591 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4592 Ty = ValType; 4593 else if (Form == Copy || Form == Xchg) { 4594 if (IsPassedByAddress) 4595 // The value pointer is always dereferenced, a nullptr is undefined. 4596 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4597 Ty = ByValType; 4598 } else if (Form == Arithmetic) 4599 Ty = Context.getPointerDiffType(); 4600 else { 4601 Expr *ValArg = TheCall->getArg(i); 4602 // The value pointer is always dereferenced, a nullptr is undefined. 4603 CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc()); 4604 LangAS AS = LangAS::Default; 4605 // Keep address space of non-atomic pointer type. 4606 if (const PointerType *PtrTy = 4607 ValArg->getType()->getAs<PointerType>()) { 4608 AS = PtrTy->getPointeeType().getAddressSpace(); 4609 } 4610 Ty = Context.getPointerType( 4611 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4612 } 4613 break; 4614 case 2: 4615 // The third argument to compare_exchange / GNU exchange is the desired 4616 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4617 if (IsPassedByAddress) 4618 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4619 Ty = ByValType; 4620 break; 4621 case 3: 4622 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4623 Ty = Context.BoolTy; 4624 break; 4625 } 4626 } else { 4627 // The order(s) and scope are always converted to int. 4628 Ty = Context.IntTy; 4629 } 4630 4631 InitializedEntity Entity = 4632 InitializedEntity::InitializeParameter(Context, Ty, false); 4633 ExprResult Arg = TheCall->getArg(i); 4634 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4635 if (Arg.isInvalid()) 4636 return true; 4637 TheCall->setArg(i, Arg.get()); 4638 } 4639 4640 // Permute the arguments into a 'consistent' order. 4641 SmallVector<Expr*, 5> SubExprs; 4642 SubExprs.push_back(Ptr); 4643 switch (Form) { 4644 case Init: 4645 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4646 SubExprs.push_back(TheCall->getArg(1)); // Val1 4647 break; 4648 case Load: 4649 SubExprs.push_back(TheCall->getArg(1)); // Order 4650 break; 4651 case LoadCopy: 4652 case Copy: 4653 case Arithmetic: 4654 case Xchg: 4655 SubExprs.push_back(TheCall->getArg(2)); // Order 4656 SubExprs.push_back(TheCall->getArg(1)); // Val1 4657 break; 4658 case GNUXchg: 4659 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4660 SubExprs.push_back(TheCall->getArg(3)); // Order 4661 SubExprs.push_back(TheCall->getArg(1)); // Val1 4662 SubExprs.push_back(TheCall->getArg(2)); // Val2 4663 break; 4664 case C11CmpXchg: 4665 SubExprs.push_back(TheCall->getArg(3)); // Order 4666 SubExprs.push_back(TheCall->getArg(1)); // Val1 4667 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 4668 SubExprs.push_back(TheCall->getArg(2)); // Val2 4669 break; 4670 case GNUCmpXchg: 4671 SubExprs.push_back(TheCall->getArg(4)); // Order 4672 SubExprs.push_back(TheCall->getArg(1)); // Val1 4673 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 4674 SubExprs.push_back(TheCall->getArg(2)); // Val2 4675 SubExprs.push_back(TheCall->getArg(3)); // Weak 4676 break; 4677 } 4678 4679 if (SubExprs.size() >= 2 && Form != Init) { 4680 llvm::APSInt Result(32); 4681 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4682 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4683 Diag(SubExprs[1]->getBeginLoc(), 4684 diag::warn_atomic_op_has_invalid_memory_order) 4685 << SubExprs[1]->getSourceRange(); 4686 } 4687 4688 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4689 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 4690 llvm::APSInt Result(32); 4691 if (Scope->isIntegerConstantExpr(Result, Context) && 4692 !ScopeModel->isValid(Result.getZExtValue())) { 4693 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4694 << Scope->getSourceRange(); 4695 } 4696 SubExprs.push_back(Scope); 4697 } 4698 4699 AtomicExpr *AE = 4700 new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs, 4701 ResultType, Op, TheCall->getRParenLoc()); 4702 4703 if ((Op == AtomicExpr::AO__c11_atomic_load || 4704 Op == AtomicExpr::AO__c11_atomic_store || 4705 Op == AtomicExpr::AO__opencl_atomic_load || 4706 Op == AtomicExpr::AO__opencl_atomic_store ) && 4707 Context.AtomicUsesUnsupportedLibcall(AE)) 4708 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4709 << ((Op == AtomicExpr::AO__c11_atomic_load || 4710 Op == AtomicExpr::AO__opencl_atomic_load) 4711 ? 0 4712 : 1); 4713 4714 return AE; 4715 } 4716 4717 /// checkBuiltinArgument - Given a call to a builtin function, perform 4718 /// normal type-checking on the given argument, updating the call in 4719 /// place. This is useful when a builtin function requires custom 4720 /// type-checking for some of its arguments but not necessarily all of 4721 /// them. 4722 /// 4723 /// Returns true on error. 4724 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4725 FunctionDecl *Fn = E->getDirectCallee(); 4726 assert(Fn && "builtin call without direct callee!"); 4727 4728 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4729 InitializedEntity Entity = 4730 InitializedEntity::InitializeParameter(S.Context, Param); 4731 4732 ExprResult Arg = E->getArg(0); 4733 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4734 if (Arg.isInvalid()) 4735 return true; 4736 4737 E->setArg(ArgIndex, Arg.get()); 4738 return false; 4739 } 4740 4741 /// We have a call to a function like __sync_fetch_and_add, which is an 4742 /// overloaded function based on the pointer type of its first argument. 4743 /// The main ActOnCallExpr routines have already promoted the types of 4744 /// arguments because all of these calls are prototyped as void(...). 4745 /// 4746 /// This function goes through and does final semantic checking for these 4747 /// builtins, as well as generating any warnings. 4748 ExprResult 4749 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4750 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4751 Expr *Callee = TheCall->getCallee(); 4752 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4753 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4754 4755 // Ensure that we have at least one argument to do type inference from. 4756 if (TheCall->getNumArgs() < 1) { 4757 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4758 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4759 return ExprError(); 4760 } 4761 4762 // Inspect the first argument of the atomic builtin. This should always be 4763 // a pointer type, whose element is an integral scalar or pointer type. 4764 // Because it is a pointer type, we don't have to worry about any implicit 4765 // casts here. 4766 // FIXME: We don't allow floating point scalars as input. 4767 Expr *FirstArg = TheCall->getArg(0); 4768 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4769 if (FirstArgResult.isInvalid()) 4770 return ExprError(); 4771 FirstArg = FirstArgResult.get(); 4772 TheCall->setArg(0, FirstArg); 4773 4774 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4775 if (!pointerType) { 4776 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4777 << FirstArg->getType() << FirstArg->getSourceRange(); 4778 return ExprError(); 4779 } 4780 4781 QualType ValType = pointerType->getPointeeType(); 4782 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4783 !ValType->isBlockPointerType()) { 4784 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4785 << FirstArg->getType() << FirstArg->getSourceRange(); 4786 return ExprError(); 4787 } 4788 4789 if (ValType.isConstQualified()) { 4790 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4791 << FirstArg->getType() << FirstArg->getSourceRange(); 4792 return ExprError(); 4793 } 4794 4795 switch (ValType.getObjCLifetime()) { 4796 case Qualifiers::OCL_None: 4797 case Qualifiers::OCL_ExplicitNone: 4798 // okay 4799 break; 4800 4801 case Qualifiers::OCL_Weak: 4802 case Qualifiers::OCL_Strong: 4803 case Qualifiers::OCL_Autoreleasing: 4804 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4805 << ValType << FirstArg->getSourceRange(); 4806 return ExprError(); 4807 } 4808 4809 // Strip any qualifiers off ValType. 4810 ValType = ValType.getUnqualifiedType(); 4811 4812 // The majority of builtins return a value, but a few have special return 4813 // types, so allow them to override appropriately below. 4814 QualType ResultType = ValType; 4815 4816 // We need to figure out which concrete builtin this maps onto. For example, 4817 // __sync_fetch_and_add with a 2 byte object turns into 4818 // __sync_fetch_and_add_2. 4819 #define BUILTIN_ROW(x) \ 4820 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4821 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4822 4823 static const unsigned BuiltinIndices[][5] = { 4824 BUILTIN_ROW(__sync_fetch_and_add), 4825 BUILTIN_ROW(__sync_fetch_and_sub), 4826 BUILTIN_ROW(__sync_fetch_and_or), 4827 BUILTIN_ROW(__sync_fetch_and_and), 4828 BUILTIN_ROW(__sync_fetch_and_xor), 4829 BUILTIN_ROW(__sync_fetch_and_nand), 4830 4831 BUILTIN_ROW(__sync_add_and_fetch), 4832 BUILTIN_ROW(__sync_sub_and_fetch), 4833 BUILTIN_ROW(__sync_and_and_fetch), 4834 BUILTIN_ROW(__sync_or_and_fetch), 4835 BUILTIN_ROW(__sync_xor_and_fetch), 4836 BUILTIN_ROW(__sync_nand_and_fetch), 4837 4838 BUILTIN_ROW(__sync_val_compare_and_swap), 4839 BUILTIN_ROW(__sync_bool_compare_and_swap), 4840 BUILTIN_ROW(__sync_lock_test_and_set), 4841 BUILTIN_ROW(__sync_lock_release), 4842 BUILTIN_ROW(__sync_swap) 4843 }; 4844 #undef BUILTIN_ROW 4845 4846 // Determine the index of the size. 4847 unsigned SizeIndex; 4848 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 4849 case 1: SizeIndex = 0; break; 4850 case 2: SizeIndex = 1; break; 4851 case 4: SizeIndex = 2; break; 4852 case 8: SizeIndex = 3; break; 4853 case 16: SizeIndex = 4; break; 4854 default: 4855 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 4856 << FirstArg->getType() << FirstArg->getSourceRange(); 4857 return ExprError(); 4858 } 4859 4860 // Each of these builtins has one pointer argument, followed by some number of 4861 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 4862 // that we ignore. Find out which row of BuiltinIndices to read from as well 4863 // as the number of fixed args. 4864 unsigned BuiltinID = FDecl->getBuiltinID(); 4865 unsigned BuiltinIndex, NumFixed = 1; 4866 bool WarnAboutSemanticsChange = false; 4867 switch (BuiltinID) { 4868 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 4869 case Builtin::BI__sync_fetch_and_add: 4870 case Builtin::BI__sync_fetch_and_add_1: 4871 case Builtin::BI__sync_fetch_and_add_2: 4872 case Builtin::BI__sync_fetch_and_add_4: 4873 case Builtin::BI__sync_fetch_and_add_8: 4874 case Builtin::BI__sync_fetch_and_add_16: 4875 BuiltinIndex = 0; 4876 break; 4877 4878 case Builtin::BI__sync_fetch_and_sub: 4879 case Builtin::BI__sync_fetch_and_sub_1: 4880 case Builtin::BI__sync_fetch_and_sub_2: 4881 case Builtin::BI__sync_fetch_and_sub_4: 4882 case Builtin::BI__sync_fetch_and_sub_8: 4883 case Builtin::BI__sync_fetch_and_sub_16: 4884 BuiltinIndex = 1; 4885 break; 4886 4887 case Builtin::BI__sync_fetch_and_or: 4888 case Builtin::BI__sync_fetch_and_or_1: 4889 case Builtin::BI__sync_fetch_and_or_2: 4890 case Builtin::BI__sync_fetch_and_or_4: 4891 case Builtin::BI__sync_fetch_and_or_8: 4892 case Builtin::BI__sync_fetch_and_or_16: 4893 BuiltinIndex = 2; 4894 break; 4895 4896 case Builtin::BI__sync_fetch_and_and: 4897 case Builtin::BI__sync_fetch_and_and_1: 4898 case Builtin::BI__sync_fetch_and_and_2: 4899 case Builtin::BI__sync_fetch_and_and_4: 4900 case Builtin::BI__sync_fetch_and_and_8: 4901 case Builtin::BI__sync_fetch_and_and_16: 4902 BuiltinIndex = 3; 4903 break; 4904 4905 case Builtin::BI__sync_fetch_and_xor: 4906 case Builtin::BI__sync_fetch_and_xor_1: 4907 case Builtin::BI__sync_fetch_and_xor_2: 4908 case Builtin::BI__sync_fetch_and_xor_4: 4909 case Builtin::BI__sync_fetch_and_xor_8: 4910 case Builtin::BI__sync_fetch_and_xor_16: 4911 BuiltinIndex = 4; 4912 break; 4913 4914 case Builtin::BI__sync_fetch_and_nand: 4915 case Builtin::BI__sync_fetch_and_nand_1: 4916 case Builtin::BI__sync_fetch_and_nand_2: 4917 case Builtin::BI__sync_fetch_and_nand_4: 4918 case Builtin::BI__sync_fetch_and_nand_8: 4919 case Builtin::BI__sync_fetch_and_nand_16: 4920 BuiltinIndex = 5; 4921 WarnAboutSemanticsChange = true; 4922 break; 4923 4924 case Builtin::BI__sync_add_and_fetch: 4925 case Builtin::BI__sync_add_and_fetch_1: 4926 case Builtin::BI__sync_add_and_fetch_2: 4927 case Builtin::BI__sync_add_and_fetch_4: 4928 case Builtin::BI__sync_add_and_fetch_8: 4929 case Builtin::BI__sync_add_and_fetch_16: 4930 BuiltinIndex = 6; 4931 break; 4932 4933 case Builtin::BI__sync_sub_and_fetch: 4934 case Builtin::BI__sync_sub_and_fetch_1: 4935 case Builtin::BI__sync_sub_and_fetch_2: 4936 case Builtin::BI__sync_sub_and_fetch_4: 4937 case Builtin::BI__sync_sub_and_fetch_8: 4938 case Builtin::BI__sync_sub_and_fetch_16: 4939 BuiltinIndex = 7; 4940 break; 4941 4942 case Builtin::BI__sync_and_and_fetch: 4943 case Builtin::BI__sync_and_and_fetch_1: 4944 case Builtin::BI__sync_and_and_fetch_2: 4945 case Builtin::BI__sync_and_and_fetch_4: 4946 case Builtin::BI__sync_and_and_fetch_8: 4947 case Builtin::BI__sync_and_and_fetch_16: 4948 BuiltinIndex = 8; 4949 break; 4950 4951 case Builtin::BI__sync_or_and_fetch: 4952 case Builtin::BI__sync_or_and_fetch_1: 4953 case Builtin::BI__sync_or_and_fetch_2: 4954 case Builtin::BI__sync_or_and_fetch_4: 4955 case Builtin::BI__sync_or_and_fetch_8: 4956 case Builtin::BI__sync_or_and_fetch_16: 4957 BuiltinIndex = 9; 4958 break; 4959 4960 case Builtin::BI__sync_xor_and_fetch: 4961 case Builtin::BI__sync_xor_and_fetch_1: 4962 case Builtin::BI__sync_xor_and_fetch_2: 4963 case Builtin::BI__sync_xor_and_fetch_4: 4964 case Builtin::BI__sync_xor_and_fetch_8: 4965 case Builtin::BI__sync_xor_and_fetch_16: 4966 BuiltinIndex = 10; 4967 break; 4968 4969 case Builtin::BI__sync_nand_and_fetch: 4970 case Builtin::BI__sync_nand_and_fetch_1: 4971 case Builtin::BI__sync_nand_and_fetch_2: 4972 case Builtin::BI__sync_nand_and_fetch_4: 4973 case Builtin::BI__sync_nand_and_fetch_8: 4974 case Builtin::BI__sync_nand_and_fetch_16: 4975 BuiltinIndex = 11; 4976 WarnAboutSemanticsChange = true; 4977 break; 4978 4979 case Builtin::BI__sync_val_compare_and_swap: 4980 case Builtin::BI__sync_val_compare_and_swap_1: 4981 case Builtin::BI__sync_val_compare_and_swap_2: 4982 case Builtin::BI__sync_val_compare_and_swap_4: 4983 case Builtin::BI__sync_val_compare_and_swap_8: 4984 case Builtin::BI__sync_val_compare_and_swap_16: 4985 BuiltinIndex = 12; 4986 NumFixed = 2; 4987 break; 4988 4989 case Builtin::BI__sync_bool_compare_and_swap: 4990 case Builtin::BI__sync_bool_compare_and_swap_1: 4991 case Builtin::BI__sync_bool_compare_and_swap_2: 4992 case Builtin::BI__sync_bool_compare_and_swap_4: 4993 case Builtin::BI__sync_bool_compare_and_swap_8: 4994 case Builtin::BI__sync_bool_compare_and_swap_16: 4995 BuiltinIndex = 13; 4996 NumFixed = 2; 4997 ResultType = Context.BoolTy; 4998 break; 4999 5000 case Builtin::BI__sync_lock_test_and_set: 5001 case Builtin::BI__sync_lock_test_and_set_1: 5002 case Builtin::BI__sync_lock_test_and_set_2: 5003 case Builtin::BI__sync_lock_test_and_set_4: 5004 case Builtin::BI__sync_lock_test_and_set_8: 5005 case Builtin::BI__sync_lock_test_and_set_16: 5006 BuiltinIndex = 14; 5007 break; 5008 5009 case Builtin::BI__sync_lock_release: 5010 case Builtin::BI__sync_lock_release_1: 5011 case Builtin::BI__sync_lock_release_2: 5012 case Builtin::BI__sync_lock_release_4: 5013 case Builtin::BI__sync_lock_release_8: 5014 case Builtin::BI__sync_lock_release_16: 5015 BuiltinIndex = 15; 5016 NumFixed = 0; 5017 ResultType = Context.VoidTy; 5018 break; 5019 5020 case Builtin::BI__sync_swap: 5021 case Builtin::BI__sync_swap_1: 5022 case Builtin::BI__sync_swap_2: 5023 case Builtin::BI__sync_swap_4: 5024 case Builtin::BI__sync_swap_8: 5025 case Builtin::BI__sync_swap_16: 5026 BuiltinIndex = 16; 5027 break; 5028 } 5029 5030 // Now that we know how many fixed arguments we expect, first check that we 5031 // have at least that many. 5032 if (TheCall->getNumArgs() < 1+NumFixed) { 5033 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5034 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5035 << Callee->getSourceRange(); 5036 return ExprError(); 5037 } 5038 5039 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5040 << Callee->getSourceRange(); 5041 5042 if (WarnAboutSemanticsChange) { 5043 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5044 << Callee->getSourceRange(); 5045 } 5046 5047 // Get the decl for the concrete builtin from this, we can tell what the 5048 // concrete integer type we should convert to is. 5049 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5050 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5051 FunctionDecl *NewBuiltinDecl; 5052 if (NewBuiltinID == BuiltinID) 5053 NewBuiltinDecl = FDecl; 5054 else { 5055 // Perform builtin lookup to avoid redeclaring it. 5056 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5057 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5058 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5059 assert(Res.getFoundDecl()); 5060 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5061 if (!NewBuiltinDecl) 5062 return ExprError(); 5063 } 5064 5065 // The first argument --- the pointer --- has a fixed type; we 5066 // deduce the types of the rest of the arguments accordingly. Walk 5067 // the remaining arguments, converting them to the deduced value type. 5068 for (unsigned i = 0; i != NumFixed; ++i) { 5069 ExprResult Arg = TheCall->getArg(i+1); 5070 5071 // GCC does an implicit conversion to the pointer or integer ValType. This 5072 // can fail in some cases (1i -> int**), check for this error case now. 5073 // Initialize the argument. 5074 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5075 ValType, /*consume*/ false); 5076 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5077 if (Arg.isInvalid()) 5078 return ExprError(); 5079 5080 // Okay, we have something that *can* be converted to the right type. Check 5081 // to see if there is a potentially weird extension going on here. This can 5082 // happen when you do an atomic operation on something like an char* and 5083 // pass in 42. The 42 gets converted to char. This is even more strange 5084 // for things like 45.123 -> char, etc. 5085 // FIXME: Do this check. 5086 TheCall->setArg(i+1, Arg.get()); 5087 } 5088 5089 ASTContext& Context = this->getASTContext(); 5090 5091 // Create a new DeclRefExpr to refer to the new decl. 5092 DeclRefExpr* NewDRE = DeclRefExpr::Create( 5093 Context, 5094 DRE->getQualifierLoc(), 5095 SourceLocation(), 5096 NewBuiltinDecl, 5097 /*enclosing*/ false, 5098 DRE->getLocation(), 5099 Context.BuiltinFnTy, 5100 DRE->getValueKind()); 5101 5102 // Set the callee in the CallExpr. 5103 // FIXME: This loses syntactic information. 5104 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5105 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5106 CK_BuiltinFnToFnPtr); 5107 TheCall->setCallee(PromotedCall.get()); 5108 5109 // Change the result type of the call to match the original value type. This 5110 // is arbitrary, but the codegen for these builtins ins design to handle it 5111 // gracefully. 5112 TheCall->setType(ResultType); 5113 5114 return TheCallResult; 5115 } 5116 5117 /// SemaBuiltinNontemporalOverloaded - We have a call to 5118 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5119 /// overloaded function based on the pointer type of its last argument. 5120 /// 5121 /// This function goes through and does final semantic checking for these 5122 /// builtins. 5123 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5124 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5125 DeclRefExpr *DRE = 5126 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5127 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5128 unsigned BuiltinID = FDecl->getBuiltinID(); 5129 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5130 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5131 "Unexpected nontemporal load/store builtin!"); 5132 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5133 unsigned numArgs = isStore ? 2 : 1; 5134 5135 // Ensure that we have the proper number of arguments. 5136 if (checkArgCount(*this, TheCall, numArgs)) 5137 return ExprError(); 5138 5139 // Inspect the last argument of the nontemporal builtin. This should always 5140 // be a pointer type, from which we imply the type of the memory access. 5141 // Because it is a pointer type, we don't have to worry about any implicit 5142 // casts here. 5143 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5144 ExprResult PointerArgResult = 5145 DefaultFunctionArrayLvalueConversion(PointerArg); 5146 5147 if (PointerArgResult.isInvalid()) 5148 return ExprError(); 5149 PointerArg = PointerArgResult.get(); 5150 TheCall->setArg(numArgs - 1, PointerArg); 5151 5152 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5153 if (!pointerType) { 5154 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5155 << PointerArg->getType() << PointerArg->getSourceRange(); 5156 return ExprError(); 5157 } 5158 5159 QualType ValType = pointerType->getPointeeType(); 5160 5161 // Strip any qualifiers off ValType. 5162 ValType = ValType.getUnqualifiedType(); 5163 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5164 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5165 !ValType->isVectorType()) { 5166 Diag(DRE->getBeginLoc(), 5167 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5168 << PointerArg->getType() << PointerArg->getSourceRange(); 5169 return ExprError(); 5170 } 5171 5172 if (!isStore) { 5173 TheCall->setType(ValType); 5174 return TheCallResult; 5175 } 5176 5177 ExprResult ValArg = TheCall->getArg(0); 5178 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5179 Context, ValType, /*consume*/ false); 5180 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5181 if (ValArg.isInvalid()) 5182 return ExprError(); 5183 5184 TheCall->setArg(0, ValArg.get()); 5185 TheCall->setType(Context.VoidTy); 5186 return TheCallResult; 5187 } 5188 5189 /// CheckObjCString - Checks that the argument to the builtin 5190 /// CFString constructor is correct 5191 /// Note: It might also make sense to do the UTF-16 conversion here (would 5192 /// simplify the backend). 5193 bool Sema::CheckObjCString(Expr *Arg) { 5194 Arg = Arg->IgnoreParenCasts(); 5195 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5196 5197 if (!Literal || !Literal->isAscii()) { 5198 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5199 << Arg->getSourceRange(); 5200 return true; 5201 } 5202 5203 if (Literal->containsNonAsciiOrNull()) { 5204 StringRef String = Literal->getString(); 5205 unsigned NumBytes = String.size(); 5206 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5207 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5208 llvm::UTF16 *ToPtr = &ToBuf[0]; 5209 5210 llvm::ConversionResult Result = 5211 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5212 ToPtr + NumBytes, llvm::strictConversion); 5213 // Check for conversion failure. 5214 if (Result != llvm::conversionOK) 5215 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5216 << Arg->getSourceRange(); 5217 } 5218 return false; 5219 } 5220 5221 /// CheckObjCString - Checks that the format string argument to the os_log() 5222 /// and os_trace() functions is correct, and converts it to const char *. 5223 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5224 Arg = Arg->IgnoreParenCasts(); 5225 auto *Literal = dyn_cast<StringLiteral>(Arg); 5226 if (!Literal) { 5227 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5228 Literal = ObjcLiteral->getString(); 5229 } 5230 } 5231 5232 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5233 return ExprError( 5234 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5235 << Arg->getSourceRange()); 5236 } 5237 5238 ExprResult Result(Literal); 5239 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5240 InitializedEntity Entity = 5241 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5242 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5243 return Result; 5244 } 5245 5246 /// Check that the user is calling the appropriate va_start builtin for the 5247 /// target and calling convention. 5248 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5249 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5250 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5251 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 5252 bool IsWindows = TT.isOSWindows(); 5253 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5254 if (IsX64 || IsAArch64) { 5255 CallingConv CC = CC_C; 5256 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5257 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 5258 if (IsMSVAStart) { 5259 // Don't allow this in System V ABI functions. 5260 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5261 return S.Diag(Fn->getBeginLoc(), 5262 diag::err_ms_va_start_used_in_sysv_function); 5263 } else { 5264 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5265 // On x64 Windows, don't allow this in System V ABI functions. 5266 // (Yes, that means there's no corresponding way to support variadic 5267 // System V ABI functions on Windows.) 5268 if ((IsWindows && CC == CC_X86_64SysV) || 5269 (!IsWindows && CC == CC_Win64)) 5270 return S.Diag(Fn->getBeginLoc(), 5271 diag::err_va_start_used_in_wrong_abi_function) 5272 << !IsWindows; 5273 } 5274 return false; 5275 } 5276 5277 if (IsMSVAStart) 5278 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5279 return false; 5280 } 5281 5282 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5283 ParmVarDecl **LastParam = nullptr) { 5284 // Determine whether the current function, block, or obj-c method is variadic 5285 // and get its parameter list. 5286 bool IsVariadic = false; 5287 ArrayRef<ParmVarDecl *> Params; 5288 DeclContext *Caller = S.CurContext; 5289 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5290 IsVariadic = Block->isVariadic(); 5291 Params = Block->parameters(); 5292 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5293 IsVariadic = FD->isVariadic(); 5294 Params = FD->parameters(); 5295 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5296 IsVariadic = MD->isVariadic(); 5297 // FIXME: This isn't correct for methods (results in bogus warning). 5298 Params = MD->parameters(); 5299 } else if (isa<CapturedDecl>(Caller)) { 5300 // We don't support va_start in a CapturedDecl. 5301 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5302 return true; 5303 } else { 5304 // This must be some other declcontext that parses exprs. 5305 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5306 return true; 5307 } 5308 5309 if (!IsVariadic) { 5310 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5311 return true; 5312 } 5313 5314 if (LastParam) 5315 *LastParam = Params.empty() ? nullptr : Params.back(); 5316 5317 return false; 5318 } 5319 5320 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5321 /// for validity. Emit an error and return true on failure; return false 5322 /// on success. 5323 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5324 Expr *Fn = TheCall->getCallee(); 5325 5326 if (checkVAStartABI(*this, BuiltinID, Fn)) 5327 return true; 5328 5329 if (TheCall->getNumArgs() > 2) { 5330 Diag(TheCall->getArg(2)->getBeginLoc(), 5331 diag::err_typecheck_call_too_many_args) 5332 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5333 << Fn->getSourceRange() 5334 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5335 (*(TheCall->arg_end() - 1))->getEndLoc()); 5336 return true; 5337 } 5338 5339 if (TheCall->getNumArgs() < 2) { 5340 return Diag(TheCall->getEndLoc(), 5341 diag::err_typecheck_call_too_few_args_at_least) 5342 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5343 } 5344 5345 // Type-check the first argument normally. 5346 if (checkBuiltinArgument(*this, TheCall, 0)) 5347 return true; 5348 5349 // Check that the current function is variadic, and get its last parameter. 5350 ParmVarDecl *LastParam; 5351 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5352 return true; 5353 5354 // Verify that the second argument to the builtin is the last argument of the 5355 // current function or method. 5356 bool SecondArgIsLastNamedArgument = false; 5357 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5358 5359 // These are valid if SecondArgIsLastNamedArgument is false after the next 5360 // block. 5361 QualType Type; 5362 SourceLocation ParamLoc; 5363 bool IsCRegister = false; 5364 5365 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5366 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5367 SecondArgIsLastNamedArgument = PV == LastParam; 5368 5369 Type = PV->getType(); 5370 ParamLoc = PV->getLocation(); 5371 IsCRegister = 5372 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5373 } 5374 } 5375 5376 if (!SecondArgIsLastNamedArgument) 5377 Diag(TheCall->getArg(1)->getBeginLoc(), 5378 diag::warn_second_arg_of_va_start_not_last_named_param); 5379 else if (IsCRegister || Type->isReferenceType() || 5380 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5381 // Promotable integers are UB, but enumerations need a bit of 5382 // extra checking to see what their promotable type actually is. 5383 if (!Type->isPromotableIntegerType()) 5384 return false; 5385 if (!Type->isEnumeralType()) 5386 return true; 5387 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 5388 return !(ED && 5389 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5390 }()) { 5391 unsigned Reason = 0; 5392 if (Type->isReferenceType()) Reason = 1; 5393 else if (IsCRegister) Reason = 2; 5394 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5395 Diag(ParamLoc, diag::note_parameter_type) << Type; 5396 } 5397 5398 TheCall->setType(Context.VoidTy); 5399 return false; 5400 } 5401 5402 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5403 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5404 // const char *named_addr); 5405 5406 Expr *Func = Call->getCallee(); 5407 5408 if (Call->getNumArgs() < 3) 5409 return Diag(Call->getEndLoc(), 5410 diag::err_typecheck_call_too_few_args_at_least) 5411 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5412 5413 // Type-check the first argument normally. 5414 if (checkBuiltinArgument(*this, Call, 0)) 5415 return true; 5416 5417 // Check that the current function is variadic. 5418 if (checkVAStartIsInVariadicFunction(*this, Func)) 5419 return true; 5420 5421 // __va_start on Windows does not validate the parameter qualifiers 5422 5423 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5424 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5425 5426 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5427 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5428 5429 const QualType &ConstCharPtrTy = 5430 Context.getPointerType(Context.CharTy.withConst()); 5431 if (!Arg1Ty->isPointerType() || 5432 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5433 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5434 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5435 << 0 /* qualifier difference */ 5436 << 3 /* parameter mismatch */ 5437 << 2 << Arg1->getType() << ConstCharPtrTy; 5438 5439 const QualType SizeTy = Context.getSizeType(); 5440 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5441 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5442 << Arg2->getType() << SizeTy << 1 /* different class */ 5443 << 0 /* qualifier difference */ 5444 << 3 /* parameter mismatch */ 5445 << 3 << Arg2->getType() << SizeTy; 5446 5447 return false; 5448 } 5449 5450 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5451 /// friends. This is declared to take (...), so we have to check everything. 5452 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5453 if (TheCall->getNumArgs() < 2) 5454 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5455 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5456 if (TheCall->getNumArgs() > 2) 5457 return Diag(TheCall->getArg(2)->getBeginLoc(), 5458 diag::err_typecheck_call_too_many_args) 5459 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5460 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5461 (*(TheCall->arg_end() - 1))->getEndLoc()); 5462 5463 ExprResult OrigArg0 = TheCall->getArg(0); 5464 ExprResult OrigArg1 = TheCall->getArg(1); 5465 5466 // Do standard promotions between the two arguments, returning their common 5467 // type. 5468 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 5469 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5470 return true; 5471 5472 // Make sure any conversions are pushed back into the call; this is 5473 // type safe since unordered compare builtins are declared as "_Bool 5474 // foo(...)". 5475 TheCall->setArg(0, OrigArg0.get()); 5476 TheCall->setArg(1, OrigArg1.get()); 5477 5478 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5479 return false; 5480 5481 // If the common type isn't a real floating type, then the arguments were 5482 // invalid for this operation. 5483 if (Res.isNull() || !Res->isRealFloatingType()) 5484 return Diag(OrigArg0.get()->getBeginLoc(), 5485 diag::err_typecheck_call_invalid_ordered_compare) 5486 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5487 << SourceRange(OrigArg0.get()->getBeginLoc(), 5488 OrigArg1.get()->getEndLoc()); 5489 5490 return false; 5491 } 5492 5493 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5494 /// __builtin_isnan and friends. This is declared to take (...), so we have 5495 /// to check everything. We expect the last argument to be a floating point 5496 /// value. 5497 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5498 if (TheCall->getNumArgs() < NumArgs) 5499 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5500 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5501 if (TheCall->getNumArgs() > NumArgs) 5502 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5503 diag::err_typecheck_call_too_many_args) 5504 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5505 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5506 (*(TheCall->arg_end() - 1))->getEndLoc()); 5507 5508 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5509 5510 if (OrigArg->isTypeDependent()) 5511 return false; 5512 5513 // This operation requires a non-_Complex floating-point number. 5514 if (!OrigArg->getType()->isRealFloatingType()) 5515 return Diag(OrigArg->getBeginLoc(), 5516 diag::err_typecheck_call_invalid_unary_fp) 5517 << OrigArg->getType() << OrigArg->getSourceRange(); 5518 5519 // If this is an implicit conversion from float -> float, double, or 5520 // long double, remove it. 5521 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 5522 // Only remove standard FloatCasts, leaving other casts inplace 5523 if (Cast->getCastKind() == CK_FloatingCast) { 5524 Expr *CastArg = Cast->getSubExpr(); 5525 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 5526 assert( 5527 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 5528 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || 5529 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && 5530 "promotion from float to either float, double, or long double is " 5531 "the only expected cast here"); 5532 Cast->setSubExpr(nullptr); 5533 TheCall->setArg(NumArgs-1, CastArg); 5534 } 5535 } 5536 } 5537 5538 return false; 5539 } 5540 5541 // Customized Sema Checking for VSX builtins that have the following signature: 5542 // vector [...] builtinName(vector [...], vector [...], const int); 5543 // Which takes the same type of vectors (any legal vector type) for the first 5544 // two arguments and takes compile time constant for the third argument. 5545 // Example builtins are : 5546 // vector double vec_xxpermdi(vector double, vector double, int); 5547 // vector short vec_xxsldwi(vector short, vector short, int); 5548 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5549 unsigned ExpectedNumArgs = 3; 5550 if (TheCall->getNumArgs() < ExpectedNumArgs) 5551 return Diag(TheCall->getEndLoc(), 5552 diag::err_typecheck_call_too_few_args_at_least) 5553 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5554 << TheCall->getSourceRange(); 5555 5556 if (TheCall->getNumArgs() > ExpectedNumArgs) 5557 return Diag(TheCall->getEndLoc(), 5558 diag::err_typecheck_call_too_many_args_at_most) 5559 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5560 << TheCall->getSourceRange(); 5561 5562 // Check the third argument is a compile time constant 5563 llvm::APSInt Value; 5564 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5565 return Diag(TheCall->getBeginLoc(), 5566 diag::err_vsx_builtin_nonconstant_argument) 5567 << 3 /* argument index */ << TheCall->getDirectCallee() 5568 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5569 TheCall->getArg(2)->getEndLoc()); 5570 5571 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5572 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5573 5574 // Check the type of argument 1 and argument 2 are vectors. 5575 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5576 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5577 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5578 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5579 << TheCall->getDirectCallee() 5580 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5581 TheCall->getArg(1)->getEndLoc()); 5582 } 5583 5584 // Check the first two arguments are the same type. 5585 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5586 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5587 << TheCall->getDirectCallee() 5588 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5589 TheCall->getArg(1)->getEndLoc()); 5590 } 5591 5592 // When default clang type checking is turned off and the customized type 5593 // checking is used, the returning type of the function must be explicitly 5594 // set. Otherwise it is _Bool by default. 5595 TheCall->setType(Arg1Ty); 5596 5597 return false; 5598 } 5599 5600 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5601 // This is declared to take (...), so we have to check everything. 5602 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5603 if (TheCall->getNumArgs() < 2) 5604 return ExprError(Diag(TheCall->getEndLoc(), 5605 diag::err_typecheck_call_too_few_args_at_least) 5606 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5607 << TheCall->getSourceRange()); 5608 5609 // Determine which of the following types of shufflevector we're checking: 5610 // 1) unary, vector mask: (lhs, mask) 5611 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5612 QualType resType = TheCall->getArg(0)->getType(); 5613 unsigned numElements = 0; 5614 5615 if (!TheCall->getArg(0)->isTypeDependent() && 5616 !TheCall->getArg(1)->isTypeDependent()) { 5617 QualType LHSType = TheCall->getArg(0)->getType(); 5618 QualType RHSType = TheCall->getArg(1)->getType(); 5619 5620 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5621 return ExprError( 5622 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5623 << TheCall->getDirectCallee() 5624 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5625 TheCall->getArg(1)->getEndLoc())); 5626 5627 numElements = LHSType->getAs<VectorType>()->getNumElements(); 5628 unsigned numResElements = TheCall->getNumArgs() - 2; 5629 5630 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5631 // with mask. If so, verify that RHS is an integer vector type with the 5632 // same number of elts as lhs. 5633 if (TheCall->getNumArgs() == 2) { 5634 if (!RHSType->hasIntegerRepresentation() || 5635 RHSType->getAs<VectorType>()->getNumElements() != numElements) 5636 return ExprError(Diag(TheCall->getBeginLoc(), 5637 diag::err_vec_builtin_incompatible_vector) 5638 << TheCall->getDirectCallee() 5639 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5640 TheCall->getArg(1)->getEndLoc())); 5641 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5642 return ExprError(Diag(TheCall->getBeginLoc(), 5643 diag::err_vec_builtin_incompatible_vector) 5644 << TheCall->getDirectCallee() 5645 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5646 TheCall->getArg(1)->getEndLoc())); 5647 } else if (numElements != numResElements) { 5648 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 5649 resType = Context.getVectorType(eltType, numResElements, 5650 VectorType::GenericVector); 5651 } 5652 } 5653 5654 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5655 if (TheCall->getArg(i)->isTypeDependent() || 5656 TheCall->getArg(i)->isValueDependent()) 5657 continue; 5658 5659 llvm::APSInt Result(32); 5660 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5661 return ExprError(Diag(TheCall->getBeginLoc(), 5662 diag::err_shufflevector_nonconstant_argument) 5663 << TheCall->getArg(i)->getSourceRange()); 5664 5665 // Allow -1 which will be translated to undef in the IR. 5666 if (Result.isSigned() && Result.isAllOnesValue()) 5667 continue; 5668 5669 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5670 return ExprError(Diag(TheCall->getBeginLoc(), 5671 diag::err_shufflevector_argument_too_large) 5672 << TheCall->getArg(i)->getSourceRange()); 5673 } 5674 5675 SmallVector<Expr*, 32> exprs; 5676 5677 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5678 exprs.push_back(TheCall->getArg(i)); 5679 TheCall->setArg(i, nullptr); 5680 } 5681 5682 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5683 TheCall->getCallee()->getBeginLoc(), 5684 TheCall->getRParenLoc()); 5685 } 5686 5687 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5688 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5689 SourceLocation BuiltinLoc, 5690 SourceLocation RParenLoc) { 5691 ExprValueKind VK = VK_RValue; 5692 ExprObjectKind OK = OK_Ordinary; 5693 QualType DstTy = TInfo->getType(); 5694 QualType SrcTy = E->getType(); 5695 5696 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5697 return ExprError(Diag(BuiltinLoc, 5698 diag::err_convertvector_non_vector) 5699 << E->getSourceRange()); 5700 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5701 return ExprError(Diag(BuiltinLoc, 5702 diag::err_convertvector_non_vector_type)); 5703 5704 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5705 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 5706 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 5707 if (SrcElts != DstElts) 5708 return ExprError(Diag(BuiltinLoc, 5709 diag::err_convertvector_incompatible_vector) 5710 << E->getSourceRange()); 5711 } 5712 5713 return new (Context) 5714 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5715 } 5716 5717 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5718 // This is declared to take (const void*, ...) and can take two 5719 // optional constant int args. 5720 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5721 unsigned NumArgs = TheCall->getNumArgs(); 5722 5723 if (NumArgs > 3) 5724 return Diag(TheCall->getEndLoc(), 5725 diag::err_typecheck_call_too_many_args_at_most) 5726 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5727 5728 // Argument 0 is checked for us and the remaining arguments must be 5729 // constant integers. 5730 for (unsigned i = 1; i != NumArgs; ++i) 5731 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5732 return true; 5733 5734 return false; 5735 } 5736 5737 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5738 // __assume does not evaluate its arguments, and should warn if its argument 5739 // has side effects. 5740 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5741 Expr *Arg = TheCall->getArg(0); 5742 if (Arg->isInstantiationDependent()) return false; 5743 5744 if (Arg->HasSideEffects(Context)) 5745 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5746 << Arg->getSourceRange() 5747 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5748 5749 return false; 5750 } 5751 5752 /// Handle __builtin_alloca_with_align. This is declared 5753 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5754 /// than 8. 5755 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5756 // The alignment must be a constant integer. 5757 Expr *Arg = TheCall->getArg(1); 5758 5759 // We can't check the value of a dependent argument. 5760 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5761 if (const auto *UE = 5762 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5763 if (UE->getKind() == UETT_AlignOf || 5764 UE->getKind() == UETT_PreferredAlignOf) 5765 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5766 << Arg->getSourceRange(); 5767 5768 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5769 5770 if (!Result.isPowerOf2()) 5771 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5772 << Arg->getSourceRange(); 5773 5774 if (Result < Context.getCharWidth()) 5775 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5776 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5777 5778 if (Result > std::numeric_limits<int32_t>::max()) 5779 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5780 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5781 } 5782 5783 return false; 5784 } 5785 5786 /// Handle __builtin_assume_aligned. This is declared 5787 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5788 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5789 unsigned NumArgs = TheCall->getNumArgs(); 5790 5791 if (NumArgs > 3) 5792 return Diag(TheCall->getEndLoc(), 5793 diag::err_typecheck_call_too_many_args_at_most) 5794 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5795 5796 // The alignment must be a constant integer. 5797 Expr *Arg = TheCall->getArg(1); 5798 5799 // We can't check the value of a dependent argument. 5800 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5801 llvm::APSInt Result; 5802 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5803 return true; 5804 5805 if (!Result.isPowerOf2()) 5806 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5807 << Arg->getSourceRange(); 5808 } 5809 5810 if (NumArgs > 2) { 5811 ExprResult Arg(TheCall->getArg(2)); 5812 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5813 Context.getSizeType(), false); 5814 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5815 if (Arg.isInvalid()) return true; 5816 TheCall->setArg(2, Arg.get()); 5817 } 5818 5819 return false; 5820 } 5821 5822 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5823 unsigned BuiltinID = 5824 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5825 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5826 5827 unsigned NumArgs = TheCall->getNumArgs(); 5828 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5829 if (NumArgs < NumRequiredArgs) { 5830 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5831 << 0 /* function call */ << NumRequiredArgs << NumArgs 5832 << TheCall->getSourceRange(); 5833 } 5834 if (NumArgs >= NumRequiredArgs + 0x100) { 5835 return Diag(TheCall->getEndLoc(), 5836 diag::err_typecheck_call_too_many_args_at_most) 5837 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5838 << TheCall->getSourceRange(); 5839 } 5840 unsigned i = 0; 5841 5842 // For formatting call, check buffer arg. 5843 if (!IsSizeCall) { 5844 ExprResult Arg(TheCall->getArg(i)); 5845 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5846 Context, Context.VoidPtrTy, false); 5847 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5848 if (Arg.isInvalid()) 5849 return true; 5850 TheCall->setArg(i, Arg.get()); 5851 i++; 5852 } 5853 5854 // Check string literal arg. 5855 unsigned FormatIdx = i; 5856 { 5857 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 5858 if (Arg.isInvalid()) 5859 return true; 5860 TheCall->setArg(i, Arg.get()); 5861 i++; 5862 } 5863 5864 // Make sure variadic args are scalar. 5865 unsigned FirstDataArg = i; 5866 while (i < NumArgs) { 5867 ExprResult Arg = DefaultVariadicArgumentPromotion( 5868 TheCall->getArg(i), VariadicFunction, nullptr); 5869 if (Arg.isInvalid()) 5870 return true; 5871 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 5872 if (ArgSize.getQuantity() >= 0x100) { 5873 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 5874 << i << (int)ArgSize.getQuantity() << 0xff 5875 << TheCall->getSourceRange(); 5876 } 5877 TheCall->setArg(i, Arg.get()); 5878 i++; 5879 } 5880 5881 // Check formatting specifiers. NOTE: We're only doing this for the non-size 5882 // call to avoid duplicate diagnostics. 5883 if (!IsSizeCall) { 5884 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 5885 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 5886 bool Success = CheckFormatArguments( 5887 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 5888 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 5889 CheckedVarArgs); 5890 if (!Success) 5891 return true; 5892 } 5893 5894 if (IsSizeCall) { 5895 TheCall->setType(Context.getSizeType()); 5896 } else { 5897 TheCall->setType(Context.VoidPtrTy); 5898 } 5899 return false; 5900 } 5901 5902 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 5903 /// TheCall is a constant expression. 5904 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 5905 llvm::APSInt &Result) { 5906 Expr *Arg = TheCall->getArg(ArgNum); 5907 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5908 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5909 5910 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 5911 5912 if (!Arg->isIntegerConstantExpr(Result, Context)) 5913 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 5914 << FDecl->getDeclName() << Arg->getSourceRange(); 5915 5916 return false; 5917 } 5918 5919 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 5920 /// TheCall is a constant expression in the range [Low, High]. 5921 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 5922 int Low, int High, bool RangeIsError) { 5923 llvm::APSInt Result; 5924 5925 // We can't check the value of a dependent argument. 5926 Expr *Arg = TheCall->getArg(ArgNum); 5927 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5928 return false; 5929 5930 // Check constant-ness first. 5931 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5932 return true; 5933 5934 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 5935 if (RangeIsError) 5936 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 5937 << Result.toString(10) << Low << High << Arg->getSourceRange(); 5938 else 5939 // Defer the warning until we know if the code will be emitted so that 5940 // dead code can ignore this. 5941 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 5942 PDiag(diag::warn_argument_invalid_range) 5943 << Result.toString(10) << Low << High 5944 << Arg->getSourceRange()); 5945 } 5946 5947 return false; 5948 } 5949 5950 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 5951 /// TheCall is a constant expression is a multiple of Num.. 5952 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 5953 unsigned Num) { 5954 llvm::APSInt Result; 5955 5956 // We can't check the value of a dependent argument. 5957 Expr *Arg = TheCall->getArg(ArgNum); 5958 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5959 return false; 5960 5961 // Check constant-ness first. 5962 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5963 return true; 5964 5965 if (Result.getSExtValue() % Num != 0) 5966 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 5967 << Num << Arg->getSourceRange(); 5968 5969 return false; 5970 } 5971 5972 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 5973 /// TheCall is an ARM/AArch64 special register string literal. 5974 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 5975 int ArgNum, unsigned ExpectedFieldNum, 5976 bool AllowName) { 5977 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 5978 BuiltinID == ARM::BI__builtin_arm_wsr64 || 5979 BuiltinID == ARM::BI__builtin_arm_rsr || 5980 BuiltinID == ARM::BI__builtin_arm_rsrp || 5981 BuiltinID == ARM::BI__builtin_arm_wsr || 5982 BuiltinID == ARM::BI__builtin_arm_wsrp; 5983 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 5984 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 5985 BuiltinID == AArch64::BI__builtin_arm_rsr || 5986 BuiltinID == AArch64::BI__builtin_arm_rsrp || 5987 BuiltinID == AArch64::BI__builtin_arm_wsr || 5988 BuiltinID == AArch64::BI__builtin_arm_wsrp; 5989 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 5990 5991 // We can't check the value of a dependent argument. 5992 Expr *Arg = TheCall->getArg(ArgNum); 5993 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5994 return false; 5995 5996 // Check if the argument is a string literal. 5997 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 5998 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 5999 << Arg->getSourceRange(); 6000 6001 // Check the type of special register given. 6002 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6003 SmallVector<StringRef, 6> Fields; 6004 Reg.split(Fields, ":"); 6005 6006 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6007 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6008 << Arg->getSourceRange(); 6009 6010 // If the string is the name of a register then we cannot check that it is 6011 // valid here but if the string is of one the forms described in ACLE then we 6012 // can check that the supplied fields are integers and within the valid 6013 // ranges. 6014 if (Fields.size() > 1) { 6015 bool FiveFields = Fields.size() == 5; 6016 6017 bool ValidString = true; 6018 if (IsARMBuiltin) { 6019 ValidString &= Fields[0].startswith_lower("cp") || 6020 Fields[0].startswith_lower("p"); 6021 if (ValidString) 6022 Fields[0] = 6023 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6024 6025 ValidString &= Fields[2].startswith_lower("c"); 6026 if (ValidString) 6027 Fields[2] = Fields[2].drop_front(1); 6028 6029 if (FiveFields) { 6030 ValidString &= Fields[3].startswith_lower("c"); 6031 if (ValidString) 6032 Fields[3] = Fields[3].drop_front(1); 6033 } 6034 } 6035 6036 SmallVector<int, 5> Ranges; 6037 if (FiveFields) 6038 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6039 else 6040 Ranges.append({15, 7, 15}); 6041 6042 for (unsigned i=0; i<Fields.size(); ++i) { 6043 int IntField; 6044 ValidString &= !Fields[i].getAsInteger(10, IntField); 6045 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6046 } 6047 6048 if (!ValidString) 6049 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6050 << Arg->getSourceRange(); 6051 } else if (IsAArch64Builtin && Fields.size() == 1) { 6052 // If the register name is one of those that appear in the condition below 6053 // and the special register builtin being used is one of the write builtins, 6054 // then we require that the argument provided for writing to the register 6055 // is an integer constant expression. This is because it will be lowered to 6056 // an MSR (immediate) instruction, so we need to know the immediate at 6057 // compile time. 6058 if (TheCall->getNumArgs() != 2) 6059 return false; 6060 6061 std::string RegLower = Reg.lower(); 6062 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6063 RegLower != "pan" && RegLower != "uao") 6064 return false; 6065 6066 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6067 } 6068 6069 return false; 6070 } 6071 6072 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6073 /// This checks that the target supports __builtin_longjmp and 6074 /// that val is a constant 1. 6075 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6076 if (!Context.getTargetInfo().hasSjLjLowering()) 6077 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6078 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6079 6080 Expr *Arg = TheCall->getArg(1); 6081 llvm::APSInt Result; 6082 6083 // TODO: This is less than ideal. Overload this to take a value. 6084 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6085 return true; 6086 6087 if (Result != 1) 6088 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6089 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6090 6091 return false; 6092 } 6093 6094 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6095 /// This checks that the target supports __builtin_setjmp. 6096 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6097 if (!Context.getTargetInfo().hasSjLjLowering()) 6098 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6099 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6100 return false; 6101 } 6102 6103 namespace { 6104 6105 class UncoveredArgHandler { 6106 enum { Unknown = -1, AllCovered = -2 }; 6107 6108 signed FirstUncoveredArg = Unknown; 6109 SmallVector<const Expr *, 4> DiagnosticExprs; 6110 6111 public: 6112 UncoveredArgHandler() = default; 6113 6114 bool hasUncoveredArg() const { 6115 return (FirstUncoveredArg >= 0); 6116 } 6117 6118 unsigned getUncoveredArg() const { 6119 assert(hasUncoveredArg() && "no uncovered argument"); 6120 return FirstUncoveredArg; 6121 } 6122 6123 void setAllCovered() { 6124 // A string has been found with all arguments covered, so clear out 6125 // the diagnostics. 6126 DiagnosticExprs.clear(); 6127 FirstUncoveredArg = AllCovered; 6128 } 6129 6130 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6131 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6132 6133 // Don't update if a previous string covers all arguments. 6134 if (FirstUncoveredArg == AllCovered) 6135 return; 6136 6137 // UncoveredArgHandler tracks the highest uncovered argument index 6138 // and with it all the strings that match this index. 6139 if (NewFirstUncoveredArg == FirstUncoveredArg) 6140 DiagnosticExprs.push_back(StrExpr); 6141 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6142 DiagnosticExprs.clear(); 6143 DiagnosticExprs.push_back(StrExpr); 6144 FirstUncoveredArg = NewFirstUncoveredArg; 6145 } 6146 } 6147 6148 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6149 }; 6150 6151 enum StringLiteralCheckType { 6152 SLCT_NotALiteral, 6153 SLCT_UncheckedLiteral, 6154 SLCT_CheckedLiteral 6155 }; 6156 6157 } // namespace 6158 6159 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6160 BinaryOperatorKind BinOpKind, 6161 bool AddendIsRight) { 6162 unsigned BitWidth = Offset.getBitWidth(); 6163 unsigned AddendBitWidth = Addend.getBitWidth(); 6164 // There might be negative interim results. 6165 if (Addend.isUnsigned()) { 6166 Addend = Addend.zext(++AddendBitWidth); 6167 Addend.setIsSigned(true); 6168 } 6169 // Adjust the bit width of the APSInts. 6170 if (AddendBitWidth > BitWidth) { 6171 Offset = Offset.sext(AddendBitWidth); 6172 BitWidth = AddendBitWidth; 6173 } else if (BitWidth > AddendBitWidth) { 6174 Addend = Addend.sext(BitWidth); 6175 } 6176 6177 bool Ov = false; 6178 llvm::APSInt ResOffset = Offset; 6179 if (BinOpKind == BO_Add) 6180 ResOffset = Offset.sadd_ov(Addend, Ov); 6181 else { 6182 assert(AddendIsRight && BinOpKind == BO_Sub && 6183 "operator must be add or sub with addend on the right"); 6184 ResOffset = Offset.ssub_ov(Addend, Ov); 6185 } 6186 6187 // We add an offset to a pointer here so we should support an offset as big as 6188 // possible. 6189 if (Ov) { 6190 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6191 "index (intermediate) result too big"); 6192 Offset = Offset.sext(2 * BitWidth); 6193 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6194 return; 6195 } 6196 6197 Offset = ResOffset; 6198 } 6199 6200 namespace { 6201 6202 // This is a wrapper class around StringLiteral to support offsetted string 6203 // literals as format strings. It takes the offset into account when returning 6204 // the string and its length or the source locations to display notes correctly. 6205 class FormatStringLiteral { 6206 const StringLiteral *FExpr; 6207 int64_t Offset; 6208 6209 public: 6210 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6211 : FExpr(fexpr), Offset(Offset) {} 6212 6213 StringRef getString() const { 6214 return FExpr->getString().drop_front(Offset); 6215 } 6216 6217 unsigned getByteLength() const { 6218 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6219 } 6220 6221 unsigned getLength() const { return FExpr->getLength() - Offset; } 6222 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6223 6224 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6225 6226 QualType getType() const { return FExpr->getType(); } 6227 6228 bool isAscii() const { return FExpr->isAscii(); } 6229 bool isWide() const { return FExpr->isWide(); } 6230 bool isUTF8() const { return FExpr->isUTF8(); } 6231 bool isUTF16() const { return FExpr->isUTF16(); } 6232 bool isUTF32() const { return FExpr->isUTF32(); } 6233 bool isPascal() const { return FExpr->isPascal(); } 6234 6235 SourceLocation getLocationOfByte( 6236 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6237 const TargetInfo &Target, unsigned *StartToken = nullptr, 6238 unsigned *StartTokenByteOffset = nullptr) const { 6239 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6240 StartToken, StartTokenByteOffset); 6241 } 6242 6243 SourceLocation getBeginLoc() const LLVM_READONLY { 6244 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6245 } 6246 6247 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6248 }; 6249 6250 } // namespace 6251 6252 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6253 const Expr *OrigFormatExpr, 6254 ArrayRef<const Expr *> Args, 6255 bool HasVAListArg, unsigned format_idx, 6256 unsigned firstDataArg, 6257 Sema::FormatStringType Type, 6258 bool inFunctionCall, 6259 Sema::VariadicCallType CallType, 6260 llvm::SmallBitVector &CheckedVarArgs, 6261 UncoveredArgHandler &UncoveredArg); 6262 6263 // Determine if an expression is a string literal or constant string. 6264 // If this function returns false on the arguments to a function expecting a 6265 // format string, we will usually need to emit a warning. 6266 // True string literals are then checked by CheckFormatString. 6267 static StringLiteralCheckType 6268 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6269 bool HasVAListArg, unsigned format_idx, 6270 unsigned firstDataArg, Sema::FormatStringType Type, 6271 Sema::VariadicCallType CallType, bool InFunctionCall, 6272 llvm::SmallBitVector &CheckedVarArgs, 6273 UncoveredArgHandler &UncoveredArg, 6274 llvm::APSInt Offset) { 6275 tryAgain: 6276 assert(Offset.isSigned() && "invalid offset"); 6277 6278 if (E->isTypeDependent() || E->isValueDependent()) 6279 return SLCT_NotALiteral; 6280 6281 E = E->IgnoreParenCasts(); 6282 6283 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6284 // Technically -Wformat-nonliteral does not warn about this case. 6285 // The behavior of printf and friends in this case is implementation 6286 // dependent. Ideally if the format string cannot be null then 6287 // it should have a 'nonnull' attribute in the function prototype. 6288 return SLCT_UncheckedLiteral; 6289 6290 switch (E->getStmtClass()) { 6291 case Stmt::BinaryConditionalOperatorClass: 6292 case Stmt::ConditionalOperatorClass: { 6293 // The expression is a literal if both sub-expressions were, and it was 6294 // completely checked only if both sub-expressions were checked. 6295 const AbstractConditionalOperator *C = 6296 cast<AbstractConditionalOperator>(E); 6297 6298 // Determine whether it is necessary to check both sub-expressions, for 6299 // example, because the condition expression is a constant that can be 6300 // evaluated at compile time. 6301 bool CheckLeft = true, CheckRight = true; 6302 6303 bool Cond; 6304 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 6305 if (Cond) 6306 CheckRight = false; 6307 else 6308 CheckLeft = false; 6309 } 6310 6311 // We need to maintain the offsets for the right and the left hand side 6312 // separately to check if every possible indexed expression is a valid 6313 // string literal. They might have different offsets for different string 6314 // literals in the end. 6315 StringLiteralCheckType Left; 6316 if (!CheckLeft) 6317 Left = SLCT_UncheckedLiteral; 6318 else { 6319 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6320 HasVAListArg, format_idx, firstDataArg, 6321 Type, CallType, InFunctionCall, 6322 CheckedVarArgs, UncoveredArg, Offset); 6323 if (Left == SLCT_NotALiteral || !CheckRight) { 6324 return Left; 6325 } 6326 } 6327 6328 StringLiteralCheckType Right = 6329 checkFormatStringExpr(S, C->getFalseExpr(), Args, 6330 HasVAListArg, format_idx, firstDataArg, 6331 Type, CallType, InFunctionCall, CheckedVarArgs, 6332 UncoveredArg, Offset); 6333 6334 return (CheckLeft && Left < Right) ? Left : Right; 6335 } 6336 6337 case Stmt::ImplicitCastExprClass: 6338 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6339 goto tryAgain; 6340 6341 case Stmt::OpaqueValueExprClass: 6342 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6343 E = src; 6344 goto tryAgain; 6345 } 6346 return SLCT_NotALiteral; 6347 6348 case Stmt::PredefinedExprClass: 6349 // While __func__, etc., are technically not string literals, they 6350 // cannot contain format specifiers and thus are not a security 6351 // liability. 6352 return SLCT_UncheckedLiteral; 6353 6354 case Stmt::DeclRefExprClass: { 6355 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6356 6357 // As an exception, do not flag errors for variables binding to 6358 // const string literals. 6359 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6360 bool isConstant = false; 6361 QualType T = DR->getType(); 6362 6363 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6364 isConstant = AT->getElementType().isConstant(S.Context); 6365 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6366 isConstant = T.isConstant(S.Context) && 6367 PT->getPointeeType().isConstant(S.Context); 6368 } else if (T->isObjCObjectPointerType()) { 6369 // In ObjC, there is usually no "const ObjectPointer" type, 6370 // so don't check if the pointee type is constant. 6371 isConstant = T.isConstant(S.Context); 6372 } 6373 6374 if (isConstant) { 6375 if (const Expr *Init = VD->getAnyInitializer()) { 6376 // Look through initializers like const char c[] = { "foo" } 6377 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6378 if (InitList->isStringLiteralInit()) 6379 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6380 } 6381 return checkFormatStringExpr(S, Init, Args, 6382 HasVAListArg, format_idx, 6383 firstDataArg, Type, CallType, 6384 /*InFunctionCall*/ false, CheckedVarArgs, 6385 UncoveredArg, Offset); 6386 } 6387 } 6388 6389 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6390 // special check to see if the format string is a function parameter 6391 // of the function calling the printf function. If the function 6392 // has an attribute indicating it is a printf-like function, then we 6393 // should suppress warnings concerning non-literals being used in a call 6394 // to a vprintf function. For example: 6395 // 6396 // void 6397 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6398 // va_list ap; 6399 // va_start(ap, fmt); 6400 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6401 // ... 6402 // } 6403 if (HasVAListArg) { 6404 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6405 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6406 int PVIndex = PV->getFunctionScopeIndex() + 1; 6407 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6408 // adjust for implicit parameter 6409 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6410 if (MD->isInstance()) 6411 ++PVIndex; 6412 // We also check if the formats are compatible. 6413 // We can't pass a 'scanf' string to a 'printf' function. 6414 if (PVIndex == PVFormat->getFormatIdx() && 6415 Type == S.GetFormatStringType(PVFormat)) 6416 return SLCT_UncheckedLiteral; 6417 } 6418 } 6419 } 6420 } 6421 } 6422 6423 return SLCT_NotALiteral; 6424 } 6425 6426 case Stmt::CallExprClass: 6427 case Stmt::CXXMemberCallExprClass: { 6428 const CallExpr *CE = cast<CallExpr>(E); 6429 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6430 bool IsFirst = true; 6431 StringLiteralCheckType CommonResult; 6432 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6433 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6434 StringLiteralCheckType Result = checkFormatStringExpr( 6435 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6436 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6437 if (IsFirst) { 6438 CommonResult = Result; 6439 IsFirst = false; 6440 } 6441 } 6442 if (!IsFirst) 6443 return CommonResult; 6444 6445 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6446 unsigned BuiltinID = FD->getBuiltinID(); 6447 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6448 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6449 const Expr *Arg = CE->getArg(0); 6450 return checkFormatStringExpr(S, Arg, Args, 6451 HasVAListArg, format_idx, 6452 firstDataArg, Type, CallType, 6453 InFunctionCall, CheckedVarArgs, 6454 UncoveredArg, Offset); 6455 } 6456 } 6457 } 6458 6459 return SLCT_NotALiteral; 6460 } 6461 case Stmt::ObjCMessageExprClass: { 6462 const auto *ME = cast<ObjCMessageExpr>(E); 6463 if (const auto *ND = ME->getMethodDecl()) { 6464 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 6465 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6466 return checkFormatStringExpr( 6467 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6468 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6469 } 6470 } 6471 6472 return SLCT_NotALiteral; 6473 } 6474 case Stmt::ObjCStringLiteralClass: 6475 case Stmt::StringLiteralClass: { 6476 const StringLiteral *StrE = nullptr; 6477 6478 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6479 StrE = ObjCFExpr->getString(); 6480 else 6481 StrE = cast<StringLiteral>(E); 6482 6483 if (StrE) { 6484 if (Offset.isNegative() || Offset > StrE->getLength()) { 6485 // TODO: It would be better to have an explicit warning for out of 6486 // bounds literals. 6487 return SLCT_NotALiteral; 6488 } 6489 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6490 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6491 firstDataArg, Type, InFunctionCall, CallType, 6492 CheckedVarArgs, UncoveredArg); 6493 return SLCT_CheckedLiteral; 6494 } 6495 6496 return SLCT_NotALiteral; 6497 } 6498 case Stmt::BinaryOperatorClass: { 6499 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6500 6501 // A string literal + an int offset is still a string literal. 6502 if (BinOp->isAdditiveOp()) { 6503 Expr::EvalResult LResult, RResult; 6504 6505 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 6506 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 6507 6508 if (LIsInt != RIsInt) { 6509 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6510 6511 if (LIsInt) { 6512 if (BinOpKind == BO_Add) { 6513 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 6514 E = BinOp->getRHS(); 6515 goto tryAgain; 6516 } 6517 } else { 6518 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 6519 E = BinOp->getLHS(); 6520 goto tryAgain; 6521 } 6522 } 6523 } 6524 6525 return SLCT_NotALiteral; 6526 } 6527 case Stmt::UnaryOperatorClass: { 6528 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6529 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6530 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6531 Expr::EvalResult IndexResult; 6532 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 6533 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 6534 /*RHS is int*/ true); 6535 E = ASE->getBase(); 6536 goto tryAgain; 6537 } 6538 } 6539 6540 return SLCT_NotALiteral; 6541 } 6542 6543 default: 6544 return SLCT_NotALiteral; 6545 } 6546 } 6547 6548 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6549 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6550 .Case("scanf", FST_Scanf) 6551 .Cases("printf", "printf0", FST_Printf) 6552 .Cases("NSString", "CFString", FST_NSString) 6553 .Case("strftime", FST_Strftime) 6554 .Case("strfmon", FST_Strfmon) 6555 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6556 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6557 .Case("os_trace", FST_OSLog) 6558 .Case("os_log", FST_OSLog) 6559 .Default(FST_Unknown); 6560 } 6561 6562 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6563 /// functions) for correct use of format strings. 6564 /// Returns true if a format string has been fully checked. 6565 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6566 ArrayRef<const Expr *> Args, 6567 bool IsCXXMember, 6568 VariadicCallType CallType, 6569 SourceLocation Loc, SourceRange Range, 6570 llvm::SmallBitVector &CheckedVarArgs) { 6571 FormatStringInfo FSI; 6572 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6573 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6574 FSI.FirstDataArg, GetFormatStringType(Format), 6575 CallType, Loc, Range, CheckedVarArgs); 6576 return false; 6577 } 6578 6579 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6580 bool HasVAListArg, unsigned format_idx, 6581 unsigned firstDataArg, FormatStringType Type, 6582 VariadicCallType CallType, 6583 SourceLocation Loc, SourceRange Range, 6584 llvm::SmallBitVector &CheckedVarArgs) { 6585 // CHECK: printf/scanf-like function is called with no format string. 6586 if (format_idx >= Args.size()) { 6587 Diag(Loc, diag::warn_missing_format_string) << Range; 6588 return false; 6589 } 6590 6591 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6592 6593 // CHECK: format string is not a string literal. 6594 // 6595 // Dynamically generated format strings are difficult to 6596 // automatically vet at compile time. Requiring that format strings 6597 // are string literals: (1) permits the checking of format strings by 6598 // the compiler and thereby (2) can practically remove the source of 6599 // many format string exploits. 6600 6601 // Format string can be either ObjC string (e.g. @"%d") or 6602 // C string (e.g. "%d") 6603 // ObjC string uses the same format specifiers as C string, so we can use 6604 // the same format string checking logic for both ObjC and C strings. 6605 UncoveredArgHandler UncoveredArg; 6606 StringLiteralCheckType CT = 6607 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 6608 format_idx, firstDataArg, Type, CallType, 6609 /*IsFunctionCall*/ true, CheckedVarArgs, 6610 UncoveredArg, 6611 /*no string offset*/ llvm::APSInt(64, false) = 0); 6612 6613 // Generate a diagnostic where an uncovered argument is detected. 6614 if (UncoveredArg.hasUncoveredArg()) { 6615 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 6616 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 6617 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 6618 } 6619 6620 if (CT != SLCT_NotALiteral) 6621 // Literal format string found, check done! 6622 return CT == SLCT_CheckedLiteral; 6623 6624 // Strftime is particular as it always uses a single 'time' argument, 6625 // so it is safe to pass a non-literal string. 6626 if (Type == FST_Strftime) 6627 return false; 6628 6629 // Do not emit diag when the string param is a macro expansion and the 6630 // format is either NSString or CFString. This is a hack to prevent 6631 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 6632 // which are usually used in place of NS and CF string literals. 6633 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 6634 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 6635 return false; 6636 6637 // If there are no arguments specified, warn with -Wformat-security, otherwise 6638 // warn only with -Wformat-nonliteral. 6639 if (Args.size() == firstDataArg) { 6640 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 6641 << OrigFormatExpr->getSourceRange(); 6642 switch (Type) { 6643 default: 6644 break; 6645 case FST_Kprintf: 6646 case FST_FreeBSDKPrintf: 6647 case FST_Printf: 6648 Diag(FormatLoc, diag::note_format_security_fixit) 6649 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 6650 break; 6651 case FST_NSString: 6652 Diag(FormatLoc, diag::note_format_security_fixit) 6653 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 6654 break; 6655 } 6656 } else { 6657 Diag(FormatLoc, diag::warn_format_nonliteral) 6658 << OrigFormatExpr->getSourceRange(); 6659 } 6660 return false; 6661 } 6662 6663 namespace { 6664 6665 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 6666 protected: 6667 Sema &S; 6668 const FormatStringLiteral *FExpr; 6669 const Expr *OrigFormatExpr; 6670 const Sema::FormatStringType FSType; 6671 const unsigned FirstDataArg; 6672 const unsigned NumDataArgs; 6673 const char *Beg; // Start of format string. 6674 const bool HasVAListArg; 6675 ArrayRef<const Expr *> Args; 6676 unsigned FormatIdx; 6677 llvm::SmallBitVector CoveredArgs; 6678 bool usesPositionalArgs = false; 6679 bool atFirstArg = true; 6680 bool inFunctionCall; 6681 Sema::VariadicCallType CallType; 6682 llvm::SmallBitVector &CheckedVarArgs; 6683 UncoveredArgHandler &UncoveredArg; 6684 6685 public: 6686 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 6687 const Expr *origFormatExpr, 6688 const Sema::FormatStringType type, unsigned firstDataArg, 6689 unsigned numDataArgs, const char *beg, bool hasVAListArg, 6690 ArrayRef<const Expr *> Args, unsigned formatIdx, 6691 bool inFunctionCall, Sema::VariadicCallType callType, 6692 llvm::SmallBitVector &CheckedVarArgs, 6693 UncoveredArgHandler &UncoveredArg) 6694 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 6695 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 6696 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 6697 inFunctionCall(inFunctionCall), CallType(callType), 6698 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 6699 CoveredArgs.resize(numDataArgs); 6700 CoveredArgs.reset(); 6701 } 6702 6703 void DoneProcessing(); 6704 6705 void HandleIncompleteSpecifier(const char *startSpecifier, 6706 unsigned specifierLen) override; 6707 6708 void HandleInvalidLengthModifier( 6709 const analyze_format_string::FormatSpecifier &FS, 6710 const analyze_format_string::ConversionSpecifier &CS, 6711 const char *startSpecifier, unsigned specifierLen, 6712 unsigned DiagID); 6713 6714 void HandleNonStandardLengthModifier( 6715 const analyze_format_string::FormatSpecifier &FS, 6716 const char *startSpecifier, unsigned specifierLen); 6717 6718 void HandleNonStandardConversionSpecifier( 6719 const analyze_format_string::ConversionSpecifier &CS, 6720 const char *startSpecifier, unsigned specifierLen); 6721 6722 void HandlePosition(const char *startPos, unsigned posLen) override; 6723 6724 void HandleInvalidPosition(const char *startSpecifier, 6725 unsigned specifierLen, 6726 analyze_format_string::PositionContext p) override; 6727 6728 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 6729 6730 void HandleNullChar(const char *nullCharacter) override; 6731 6732 template <typename Range> 6733 static void 6734 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 6735 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 6736 bool IsStringLocation, Range StringRange, 6737 ArrayRef<FixItHint> Fixit = None); 6738 6739 protected: 6740 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 6741 const char *startSpec, 6742 unsigned specifierLen, 6743 const char *csStart, unsigned csLen); 6744 6745 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 6746 const char *startSpec, 6747 unsigned specifierLen); 6748 6749 SourceRange getFormatStringRange(); 6750 CharSourceRange getSpecifierRange(const char *startSpecifier, 6751 unsigned specifierLen); 6752 SourceLocation getLocationOfByte(const char *x); 6753 6754 const Expr *getDataArg(unsigned i) const; 6755 6756 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 6757 const analyze_format_string::ConversionSpecifier &CS, 6758 const char *startSpecifier, unsigned specifierLen, 6759 unsigned argIndex); 6760 6761 template <typename Range> 6762 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 6763 bool IsStringLocation, Range StringRange, 6764 ArrayRef<FixItHint> Fixit = None); 6765 }; 6766 6767 } // namespace 6768 6769 SourceRange CheckFormatHandler::getFormatStringRange() { 6770 return OrigFormatExpr->getSourceRange(); 6771 } 6772 6773 CharSourceRange CheckFormatHandler:: 6774 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 6775 SourceLocation Start = getLocationOfByte(startSpecifier); 6776 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 6777 6778 // Advance the end SourceLocation by one due to half-open ranges. 6779 End = End.getLocWithOffset(1); 6780 6781 return CharSourceRange::getCharRange(Start, End); 6782 } 6783 6784 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 6785 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 6786 S.getLangOpts(), S.Context.getTargetInfo()); 6787 } 6788 6789 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 6790 unsigned specifierLen){ 6791 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 6792 getLocationOfByte(startSpecifier), 6793 /*IsStringLocation*/true, 6794 getSpecifierRange(startSpecifier, specifierLen)); 6795 } 6796 6797 void CheckFormatHandler::HandleInvalidLengthModifier( 6798 const analyze_format_string::FormatSpecifier &FS, 6799 const analyze_format_string::ConversionSpecifier &CS, 6800 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 6801 using namespace analyze_format_string; 6802 6803 const LengthModifier &LM = FS.getLengthModifier(); 6804 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6805 6806 // See if we know how to fix this length modifier. 6807 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6808 if (FixedLM) { 6809 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6810 getLocationOfByte(LM.getStart()), 6811 /*IsStringLocation*/true, 6812 getSpecifierRange(startSpecifier, specifierLen)); 6813 6814 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6815 << FixedLM->toString() 6816 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6817 6818 } else { 6819 FixItHint Hint; 6820 if (DiagID == diag::warn_format_nonsensical_length) 6821 Hint = FixItHint::CreateRemoval(LMRange); 6822 6823 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6824 getLocationOfByte(LM.getStart()), 6825 /*IsStringLocation*/true, 6826 getSpecifierRange(startSpecifier, specifierLen), 6827 Hint); 6828 } 6829 } 6830 6831 void CheckFormatHandler::HandleNonStandardLengthModifier( 6832 const analyze_format_string::FormatSpecifier &FS, 6833 const char *startSpecifier, unsigned specifierLen) { 6834 using namespace analyze_format_string; 6835 6836 const LengthModifier &LM = FS.getLengthModifier(); 6837 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6838 6839 // See if we know how to fix this length modifier. 6840 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6841 if (FixedLM) { 6842 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6843 << LM.toString() << 0, 6844 getLocationOfByte(LM.getStart()), 6845 /*IsStringLocation*/true, 6846 getSpecifierRange(startSpecifier, specifierLen)); 6847 6848 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6849 << FixedLM->toString() 6850 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6851 6852 } else { 6853 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6854 << LM.toString() << 0, 6855 getLocationOfByte(LM.getStart()), 6856 /*IsStringLocation*/true, 6857 getSpecifierRange(startSpecifier, specifierLen)); 6858 } 6859 } 6860 6861 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 6862 const analyze_format_string::ConversionSpecifier &CS, 6863 const char *startSpecifier, unsigned specifierLen) { 6864 using namespace analyze_format_string; 6865 6866 // See if we know how to fix this conversion specifier. 6867 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 6868 if (FixedCS) { 6869 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6870 << CS.toString() << /*conversion specifier*/1, 6871 getLocationOfByte(CS.getStart()), 6872 /*IsStringLocation*/true, 6873 getSpecifierRange(startSpecifier, specifierLen)); 6874 6875 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 6876 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 6877 << FixedCS->toString() 6878 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 6879 } else { 6880 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6881 << CS.toString() << /*conversion specifier*/1, 6882 getLocationOfByte(CS.getStart()), 6883 /*IsStringLocation*/true, 6884 getSpecifierRange(startSpecifier, specifierLen)); 6885 } 6886 } 6887 6888 void CheckFormatHandler::HandlePosition(const char *startPos, 6889 unsigned posLen) { 6890 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 6891 getLocationOfByte(startPos), 6892 /*IsStringLocation*/true, 6893 getSpecifierRange(startPos, posLen)); 6894 } 6895 6896 void 6897 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 6898 analyze_format_string::PositionContext p) { 6899 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 6900 << (unsigned) p, 6901 getLocationOfByte(startPos), /*IsStringLocation*/true, 6902 getSpecifierRange(startPos, posLen)); 6903 } 6904 6905 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 6906 unsigned posLen) { 6907 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 6908 getLocationOfByte(startPos), 6909 /*IsStringLocation*/true, 6910 getSpecifierRange(startPos, posLen)); 6911 } 6912 6913 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 6914 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 6915 // The presence of a null character is likely an error. 6916 EmitFormatDiagnostic( 6917 S.PDiag(diag::warn_printf_format_string_contains_null_char), 6918 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 6919 getFormatStringRange()); 6920 } 6921 } 6922 6923 // Note that this may return NULL if there was an error parsing or building 6924 // one of the argument expressions. 6925 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 6926 return Args[FirstDataArg + i]; 6927 } 6928 6929 void CheckFormatHandler::DoneProcessing() { 6930 // Does the number of data arguments exceed the number of 6931 // format conversions in the format string? 6932 if (!HasVAListArg) { 6933 // Find any arguments that weren't covered. 6934 CoveredArgs.flip(); 6935 signed notCoveredArg = CoveredArgs.find_first(); 6936 if (notCoveredArg >= 0) { 6937 assert((unsigned)notCoveredArg < NumDataArgs); 6938 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 6939 } else { 6940 UncoveredArg.setAllCovered(); 6941 } 6942 } 6943 } 6944 6945 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 6946 const Expr *ArgExpr) { 6947 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 6948 "Invalid state"); 6949 6950 if (!ArgExpr) 6951 return; 6952 6953 SourceLocation Loc = ArgExpr->getBeginLoc(); 6954 6955 if (S.getSourceManager().isInSystemMacro(Loc)) 6956 return; 6957 6958 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 6959 for (auto E : DiagnosticExprs) 6960 PDiag << E->getSourceRange(); 6961 6962 CheckFormatHandler::EmitFormatDiagnostic( 6963 S, IsFunctionCall, DiagnosticExprs[0], 6964 PDiag, Loc, /*IsStringLocation*/false, 6965 DiagnosticExprs[0]->getSourceRange()); 6966 } 6967 6968 bool 6969 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 6970 SourceLocation Loc, 6971 const char *startSpec, 6972 unsigned specifierLen, 6973 const char *csStart, 6974 unsigned csLen) { 6975 bool keepGoing = true; 6976 if (argIndex < NumDataArgs) { 6977 // Consider the argument coverered, even though the specifier doesn't 6978 // make sense. 6979 CoveredArgs.set(argIndex); 6980 } 6981 else { 6982 // If argIndex exceeds the number of data arguments we 6983 // don't issue a warning because that is just a cascade of warnings (and 6984 // they may have intended '%%' anyway). We don't want to continue processing 6985 // the format string after this point, however, as we will like just get 6986 // gibberish when trying to match arguments. 6987 keepGoing = false; 6988 } 6989 6990 StringRef Specifier(csStart, csLen); 6991 6992 // If the specifier in non-printable, it could be the first byte of a UTF-8 6993 // sequence. In that case, print the UTF-8 code point. If not, print the byte 6994 // hex value. 6995 std::string CodePointStr; 6996 if (!llvm::sys::locale::isPrint(*csStart)) { 6997 llvm::UTF32 CodePoint; 6998 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 6999 const llvm::UTF8 *E = 7000 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7001 llvm::ConversionResult Result = 7002 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7003 7004 if (Result != llvm::conversionOK) { 7005 unsigned char FirstChar = *csStart; 7006 CodePoint = (llvm::UTF32)FirstChar; 7007 } 7008 7009 llvm::raw_string_ostream OS(CodePointStr); 7010 if (CodePoint < 256) 7011 OS << "\\x" << llvm::format("%02x", CodePoint); 7012 else if (CodePoint <= 0xFFFF) 7013 OS << "\\u" << llvm::format("%04x", CodePoint); 7014 else 7015 OS << "\\U" << llvm::format("%08x", CodePoint); 7016 OS.flush(); 7017 Specifier = CodePointStr; 7018 } 7019 7020 EmitFormatDiagnostic( 7021 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7022 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7023 7024 return keepGoing; 7025 } 7026 7027 void 7028 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7029 const char *startSpec, 7030 unsigned specifierLen) { 7031 EmitFormatDiagnostic( 7032 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7033 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7034 } 7035 7036 bool 7037 CheckFormatHandler::CheckNumArgs( 7038 const analyze_format_string::FormatSpecifier &FS, 7039 const analyze_format_string::ConversionSpecifier &CS, 7040 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7041 7042 if (argIndex >= NumDataArgs) { 7043 PartialDiagnostic PDiag = FS.usesPositionalArg() 7044 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7045 << (argIndex+1) << NumDataArgs) 7046 : S.PDiag(diag::warn_printf_insufficient_data_args); 7047 EmitFormatDiagnostic( 7048 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7049 getSpecifierRange(startSpecifier, specifierLen)); 7050 7051 // Since more arguments than conversion tokens are given, by extension 7052 // all arguments are covered, so mark this as so. 7053 UncoveredArg.setAllCovered(); 7054 return false; 7055 } 7056 return true; 7057 } 7058 7059 template<typename Range> 7060 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7061 SourceLocation Loc, 7062 bool IsStringLocation, 7063 Range StringRange, 7064 ArrayRef<FixItHint> FixIt) { 7065 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7066 Loc, IsStringLocation, StringRange, FixIt); 7067 } 7068 7069 /// If the format string is not within the function call, emit a note 7070 /// so that the function call and string are in diagnostic messages. 7071 /// 7072 /// \param InFunctionCall if true, the format string is within the function 7073 /// call and only one diagnostic message will be produced. Otherwise, an 7074 /// extra note will be emitted pointing to location of the format string. 7075 /// 7076 /// \param ArgumentExpr the expression that is passed as the format string 7077 /// argument in the function call. Used for getting locations when two 7078 /// diagnostics are emitted. 7079 /// 7080 /// \param PDiag the callee should already have provided any strings for the 7081 /// diagnostic message. This function only adds locations and fixits 7082 /// to diagnostics. 7083 /// 7084 /// \param Loc primary location for diagnostic. If two diagnostics are 7085 /// required, one will be at Loc and a new SourceLocation will be created for 7086 /// the other one. 7087 /// 7088 /// \param IsStringLocation if true, Loc points to the format string should be 7089 /// used for the note. Otherwise, Loc points to the argument list and will 7090 /// be used with PDiag. 7091 /// 7092 /// \param StringRange some or all of the string to highlight. This is 7093 /// templated so it can accept either a CharSourceRange or a SourceRange. 7094 /// 7095 /// \param FixIt optional fix it hint for the format string. 7096 template <typename Range> 7097 void CheckFormatHandler::EmitFormatDiagnostic( 7098 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7099 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7100 Range StringRange, ArrayRef<FixItHint> FixIt) { 7101 if (InFunctionCall) { 7102 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7103 D << StringRange; 7104 D << FixIt; 7105 } else { 7106 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7107 << ArgumentExpr->getSourceRange(); 7108 7109 const Sema::SemaDiagnosticBuilder &Note = 7110 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7111 diag::note_format_string_defined); 7112 7113 Note << StringRange; 7114 Note << FixIt; 7115 } 7116 } 7117 7118 //===--- CHECK: Printf format string checking ------------------------------===// 7119 7120 namespace { 7121 7122 class CheckPrintfHandler : public CheckFormatHandler { 7123 public: 7124 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7125 const Expr *origFormatExpr, 7126 const Sema::FormatStringType type, unsigned firstDataArg, 7127 unsigned numDataArgs, bool isObjC, const char *beg, 7128 bool hasVAListArg, ArrayRef<const Expr *> Args, 7129 unsigned formatIdx, bool inFunctionCall, 7130 Sema::VariadicCallType CallType, 7131 llvm::SmallBitVector &CheckedVarArgs, 7132 UncoveredArgHandler &UncoveredArg) 7133 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7134 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7135 inFunctionCall, CallType, CheckedVarArgs, 7136 UncoveredArg) {} 7137 7138 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7139 7140 /// Returns true if '%@' specifiers are allowed in the format string. 7141 bool allowsObjCArg() const { 7142 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7143 FSType == Sema::FST_OSTrace; 7144 } 7145 7146 bool HandleInvalidPrintfConversionSpecifier( 7147 const analyze_printf::PrintfSpecifier &FS, 7148 const char *startSpecifier, 7149 unsigned specifierLen) override; 7150 7151 void handleInvalidMaskType(StringRef MaskType) override; 7152 7153 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7154 const char *startSpecifier, 7155 unsigned specifierLen) override; 7156 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7157 const char *StartSpecifier, 7158 unsigned SpecifierLen, 7159 const Expr *E); 7160 7161 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7162 const char *startSpecifier, unsigned specifierLen); 7163 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7164 const analyze_printf::OptionalAmount &Amt, 7165 unsigned type, 7166 const char *startSpecifier, unsigned specifierLen); 7167 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7168 const analyze_printf::OptionalFlag &flag, 7169 const char *startSpecifier, unsigned specifierLen); 7170 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7171 const analyze_printf::OptionalFlag &ignoredFlag, 7172 const analyze_printf::OptionalFlag &flag, 7173 const char *startSpecifier, unsigned specifierLen); 7174 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7175 const Expr *E); 7176 7177 void HandleEmptyObjCModifierFlag(const char *startFlag, 7178 unsigned flagLen) override; 7179 7180 void HandleInvalidObjCModifierFlag(const char *startFlag, 7181 unsigned flagLen) override; 7182 7183 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7184 const char *flagsEnd, 7185 const char *conversionPosition) 7186 override; 7187 }; 7188 7189 } // namespace 7190 7191 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7192 const analyze_printf::PrintfSpecifier &FS, 7193 const char *startSpecifier, 7194 unsigned specifierLen) { 7195 const analyze_printf::PrintfConversionSpecifier &CS = 7196 FS.getConversionSpecifier(); 7197 7198 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7199 getLocationOfByte(CS.getStart()), 7200 startSpecifier, specifierLen, 7201 CS.getStart(), CS.getLength()); 7202 } 7203 7204 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7205 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7206 } 7207 7208 bool CheckPrintfHandler::HandleAmount( 7209 const analyze_format_string::OptionalAmount &Amt, 7210 unsigned k, const char *startSpecifier, 7211 unsigned specifierLen) { 7212 if (Amt.hasDataArgument()) { 7213 if (!HasVAListArg) { 7214 unsigned argIndex = Amt.getArgIndex(); 7215 if (argIndex >= NumDataArgs) { 7216 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7217 << k, 7218 getLocationOfByte(Amt.getStart()), 7219 /*IsStringLocation*/true, 7220 getSpecifierRange(startSpecifier, specifierLen)); 7221 // Don't do any more checking. We will just emit 7222 // spurious errors. 7223 return false; 7224 } 7225 7226 // Type check the data argument. It should be an 'int'. 7227 // Although not in conformance with C99, we also allow the argument to be 7228 // an 'unsigned int' as that is a reasonably safe case. GCC also 7229 // doesn't emit a warning for that case. 7230 CoveredArgs.set(argIndex); 7231 const Expr *Arg = getDataArg(argIndex); 7232 if (!Arg) 7233 return false; 7234 7235 QualType T = Arg->getType(); 7236 7237 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7238 assert(AT.isValid()); 7239 7240 if (!AT.matchesType(S.Context, T)) { 7241 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7242 << k << AT.getRepresentativeTypeName(S.Context) 7243 << T << Arg->getSourceRange(), 7244 getLocationOfByte(Amt.getStart()), 7245 /*IsStringLocation*/true, 7246 getSpecifierRange(startSpecifier, specifierLen)); 7247 // Don't do any more checking. We will just emit 7248 // spurious errors. 7249 return false; 7250 } 7251 } 7252 } 7253 return true; 7254 } 7255 7256 void CheckPrintfHandler::HandleInvalidAmount( 7257 const analyze_printf::PrintfSpecifier &FS, 7258 const analyze_printf::OptionalAmount &Amt, 7259 unsigned type, 7260 const char *startSpecifier, 7261 unsigned specifierLen) { 7262 const analyze_printf::PrintfConversionSpecifier &CS = 7263 FS.getConversionSpecifier(); 7264 7265 FixItHint fixit = 7266 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7267 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7268 Amt.getConstantLength())) 7269 : FixItHint(); 7270 7271 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7272 << type << CS.toString(), 7273 getLocationOfByte(Amt.getStart()), 7274 /*IsStringLocation*/true, 7275 getSpecifierRange(startSpecifier, specifierLen), 7276 fixit); 7277 } 7278 7279 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7280 const analyze_printf::OptionalFlag &flag, 7281 const char *startSpecifier, 7282 unsigned specifierLen) { 7283 // Warn about pointless flag with a fixit removal. 7284 const analyze_printf::PrintfConversionSpecifier &CS = 7285 FS.getConversionSpecifier(); 7286 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7287 << flag.toString() << CS.toString(), 7288 getLocationOfByte(flag.getPosition()), 7289 /*IsStringLocation*/true, 7290 getSpecifierRange(startSpecifier, specifierLen), 7291 FixItHint::CreateRemoval( 7292 getSpecifierRange(flag.getPosition(), 1))); 7293 } 7294 7295 void CheckPrintfHandler::HandleIgnoredFlag( 7296 const analyze_printf::PrintfSpecifier &FS, 7297 const analyze_printf::OptionalFlag &ignoredFlag, 7298 const analyze_printf::OptionalFlag &flag, 7299 const char *startSpecifier, 7300 unsigned specifierLen) { 7301 // Warn about ignored flag with a fixit removal. 7302 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7303 << ignoredFlag.toString() << flag.toString(), 7304 getLocationOfByte(ignoredFlag.getPosition()), 7305 /*IsStringLocation*/true, 7306 getSpecifierRange(startSpecifier, specifierLen), 7307 FixItHint::CreateRemoval( 7308 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7309 } 7310 7311 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7312 unsigned flagLen) { 7313 // Warn about an empty flag. 7314 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7315 getLocationOfByte(startFlag), 7316 /*IsStringLocation*/true, 7317 getSpecifierRange(startFlag, flagLen)); 7318 } 7319 7320 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7321 unsigned flagLen) { 7322 // Warn about an invalid flag. 7323 auto Range = getSpecifierRange(startFlag, flagLen); 7324 StringRef flag(startFlag, flagLen); 7325 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7326 getLocationOfByte(startFlag), 7327 /*IsStringLocation*/true, 7328 Range, FixItHint::CreateRemoval(Range)); 7329 } 7330 7331 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7332 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7333 // Warn about using '[...]' without a '@' conversion. 7334 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7335 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7336 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7337 getLocationOfByte(conversionPosition), 7338 /*IsStringLocation*/true, 7339 Range, FixItHint::CreateRemoval(Range)); 7340 } 7341 7342 // Determines if the specified is a C++ class or struct containing 7343 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7344 // "c_str()"). 7345 template<typename MemberKind> 7346 static llvm::SmallPtrSet<MemberKind*, 1> 7347 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7348 const RecordType *RT = Ty->getAs<RecordType>(); 7349 llvm::SmallPtrSet<MemberKind*, 1> Results; 7350 7351 if (!RT) 7352 return Results; 7353 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7354 if (!RD || !RD->getDefinition()) 7355 return Results; 7356 7357 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7358 Sema::LookupMemberName); 7359 R.suppressDiagnostics(); 7360 7361 // We just need to include all members of the right kind turned up by the 7362 // filter, at this point. 7363 if (S.LookupQualifiedName(R, RT->getDecl())) 7364 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7365 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7366 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7367 Results.insert(FK); 7368 } 7369 return Results; 7370 } 7371 7372 /// Check if we could call '.c_str()' on an object. 7373 /// 7374 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7375 /// allow the call, or if it would be ambiguous). 7376 bool Sema::hasCStrMethod(const Expr *E) { 7377 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7378 7379 MethodSet Results = 7380 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7381 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7382 MI != ME; ++MI) 7383 if ((*MI)->getMinRequiredArguments() == 0) 7384 return true; 7385 return false; 7386 } 7387 7388 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7389 // better diagnostic if so. AT is assumed to be valid. 7390 // Returns true when a c_str() conversion method is found. 7391 bool CheckPrintfHandler::checkForCStrMembers( 7392 const analyze_printf::ArgType &AT, const Expr *E) { 7393 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7394 7395 MethodSet Results = 7396 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7397 7398 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7399 MI != ME; ++MI) { 7400 const CXXMethodDecl *Method = *MI; 7401 if (Method->getMinRequiredArguments() == 0 && 7402 AT.matchesType(S.Context, Method->getReturnType())) { 7403 // FIXME: Suggest parens if the expression needs them. 7404 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7405 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7406 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7407 return true; 7408 } 7409 } 7410 7411 return false; 7412 } 7413 7414 bool 7415 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7416 &FS, 7417 const char *startSpecifier, 7418 unsigned specifierLen) { 7419 using namespace analyze_format_string; 7420 using namespace analyze_printf; 7421 7422 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7423 7424 if (FS.consumesDataArgument()) { 7425 if (atFirstArg) { 7426 atFirstArg = false; 7427 usesPositionalArgs = FS.usesPositionalArg(); 7428 } 7429 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7430 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7431 startSpecifier, specifierLen); 7432 return false; 7433 } 7434 } 7435 7436 // First check if the field width, precision, and conversion specifier 7437 // have matching data arguments. 7438 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7439 startSpecifier, specifierLen)) { 7440 return false; 7441 } 7442 7443 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7444 startSpecifier, specifierLen)) { 7445 return false; 7446 } 7447 7448 if (!CS.consumesDataArgument()) { 7449 // FIXME: Technically specifying a precision or field width here 7450 // makes no sense. Worth issuing a warning at some point. 7451 return true; 7452 } 7453 7454 // Consume the argument. 7455 unsigned argIndex = FS.getArgIndex(); 7456 if (argIndex < NumDataArgs) { 7457 // The check to see if the argIndex is valid will come later. 7458 // We set the bit here because we may exit early from this 7459 // function if we encounter some other error. 7460 CoveredArgs.set(argIndex); 7461 } 7462 7463 // FreeBSD kernel extensions. 7464 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7465 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7466 // We need at least two arguments. 7467 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7468 return false; 7469 7470 // Claim the second argument. 7471 CoveredArgs.set(argIndex + 1); 7472 7473 // Type check the first argument (int for %b, pointer for %D) 7474 const Expr *Ex = getDataArg(argIndex); 7475 const analyze_printf::ArgType &AT = 7476 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7477 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7478 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7479 EmitFormatDiagnostic( 7480 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7481 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7482 << false << Ex->getSourceRange(), 7483 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7484 getSpecifierRange(startSpecifier, specifierLen)); 7485 7486 // Type check the second argument (char * for both %b and %D) 7487 Ex = getDataArg(argIndex + 1); 7488 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7489 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7490 EmitFormatDiagnostic( 7491 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7492 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7493 << false << Ex->getSourceRange(), 7494 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7495 getSpecifierRange(startSpecifier, specifierLen)); 7496 7497 return true; 7498 } 7499 7500 // Check for using an Objective-C specific conversion specifier 7501 // in a non-ObjC literal. 7502 if (!allowsObjCArg() && CS.isObjCArg()) { 7503 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7504 specifierLen); 7505 } 7506 7507 // %P can only be used with os_log. 7508 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7509 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7510 specifierLen); 7511 } 7512 7513 // %n is not allowed with os_log. 7514 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7515 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7516 getLocationOfByte(CS.getStart()), 7517 /*IsStringLocation*/ false, 7518 getSpecifierRange(startSpecifier, specifierLen)); 7519 7520 return true; 7521 } 7522 7523 // Only scalars are allowed for os_trace. 7524 if (FSType == Sema::FST_OSTrace && 7525 (CS.getKind() == ConversionSpecifier::PArg || 7526 CS.getKind() == ConversionSpecifier::sArg || 7527 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7528 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7529 specifierLen); 7530 } 7531 7532 // Check for use of public/private annotation outside of os_log(). 7533 if (FSType != Sema::FST_OSLog) { 7534 if (FS.isPublic().isSet()) { 7535 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7536 << "public", 7537 getLocationOfByte(FS.isPublic().getPosition()), 7538 /*IsStringLocation*/ false, 7539 getSpecifierRange(startSpecifier, specifierLen)); 7540 } 7541 if (FS.isPrivate().isSet()) { 7542 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7543 << "private", 7544 getLocationOfByte(FS.isPrivate().getPosition()), 7545 /*IsStringLocation*/ false, 7546 getSpecifierRange(startSpecifier, specifierLen)); 7547 } 7548 } 7549 7550 // Check for invalid use of field width 7551 if (!FS.hasValidFieldWidth()) { 7552 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7553 startSpecifier, specifierLen); 7554 } 7555 7556 // Check for invalid use of precision 7557 if (!FS.hasValidPrecision()) { 7558 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7559 startSpecifier, specifierLen); 7560 } 7561 7562 // Precision is mandatory for %P specifier. 7563 if (CS.getKind() == ConversionSpecifier::PArg && 7564 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7565 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7566 getLocationOfByte(startSpecifier), 7567 /*IsStringLocation*/ false, 7568 getSpecifierRange(startSpecifier, specifierLen)); 7569 } 7570 7571 // Check each flag does not conflict with any other component. 7572 if (!FS.hasValidThousandsGroupingPrefix()) 7573 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7574 if (!FS.hasValidLeadingZeros()) 7575 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7576 if (!FS.hasValidPlusPrefix()) 7577 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7578 if (!FS.hasValidSpacePrefix()) 7579 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7580 if (!FS.hasValidAlternativeForm()) 7581 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7582 if (!FS.hasValidLeftJustified()) 7583 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7584 7585 // Check that flags are not ignored by another flag 7586 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7587 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7588 startSpecifier, specifierLen); 7589 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7590 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7591 startSpecifier, specifierLen); 7592 7593 // Check the length modifier is valid with the given conversion specifier. 7594 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 7595 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7596 diag::warn_format_nonsensical_length); 7597 else if (!FS.hasStandardLengthModifier()) 7598 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7599 else if (!FS.hasStandardLengthConversionCombination()) 7600 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7601 diag::warn_format_non_standard_conversion_spec); 7602 7603 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7604 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7605 7606 // The remaining checks depend on the data arguments. 7607 if (HasVAListArg) 7608 return true; 7609 7610 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7611 return false; 7612 7613 const Expr *Arg = getDataArg(argIndex); 7614 if (!Arg) 7615 return true; 7616 7617 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 7618 } 7619 7620 static bool requiresParensToAddCast(const Expr *E) { 7621 // FIXME: We should have a general way to reason about operator 7622 // precedence and whether parens are actually needed here. 7623 // Take care of a few common cases where they aren't. 7624 const Expr *Inside = E->IgnoreImpCasts(); 7625 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 7626 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 7627 7628 switch (Inside->getStmtClass()) { 7629 case Stmt::ArraySubscriptExprClass: 7630 case Stmt::CallExprClass: 7631 case Stmt::CharacterLiteralClass: 7632 case Stmt::CXXBoolLiteralExprClass: 7633 case Stmt::DeclRefExprClass: 7634 case Stmt::FloatingLiteralClass: 7635 case Stmt::IntegerLiteralClass: 7636 case Stmt::MemberExprClass: 7637 case Stmt::ObjCArrayLiteralClass: 7638 case Stmt::ObjCBoolLiteralExprClass: 7639 case Stmt::ObjCBoxedExprClass: 7640 case Stmt::ObjCDictionaryLiteralClass: 7641 case Stmt::ObjCEncodeExprClass: 7642 case Stmt::ObjCIvarRefExprClass: 7643 case Stmt::ObjCMessageExprClass: 7644 case Stmt::ObjCPropertyRefExprClass: 7645 case Stmt::ObjCStringLiteralClass: 7646 case Stmt::ObjCSubscriptRefExprClass: 7647 case Stmt::ParenExprClass: 7648 case Stmt::StringLiteralClass: 7649 case Stmt::UnaryOperatorClass: 7650 return false; 7651 default: 7652 return true; 7653 } 7654 } 7655 7656 static std::pair<QualType, StringRef> 7657 shouldNotPrintDirectly(const ASTContext &Context, 7658 QualType IntendedTy, 7659 const Expr *E) { 7660 // Use a 'while' to peel off layers of typedefs. 7661 QualType TyTy = IntendedTy; 7662 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 7663 StringRef Name = UserTy->getDecl()->getName(); 7664 QualType CastTy = llvm::StringSwitch<QualType>(Name) 7665 .Case("CFIndex", Context.getNSIntegerType()) 7666 .Case("NSInteger", Context.getNSIntegerType()) 7667 .Case("NSUInteger", Context.getNSUIntegerType()) 7668 .Case("SInt32", Context.IntTy) 7669 .Case("UInt32", Context.UnsignedIntTy) 7670 .Default(QualType()); 7671 7672 if (!CastTy.isNull()) 7673 return std::make_pair(CastTy, Name); 7674 7675 TyTy = UserTy->desugar(); 7676 } 7677 7678 // Strip parens if necessary. 7679 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 7680 return shouldNotPrintDirectly(Context, 7681 PE->getSubExpr()->getType(), 7682 PE->getSubExpr()); 7683 7684 // If this is a conditional expression, then its result type is constructed 7685 // via usual arithmetic conversions and thus there might be no necessary 7686 // typedef sugar there. Recurse to operands to check for NSInteger & 7687 // Co. usage condition. 7688 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7689 QualType TrueTy, FalseTy; 7690 StringRef TrueName, FalseName; 7691 7692 std::tie(TrueTy, TrueName) = 7693 shouldNotPrintDirectly(Context, 7694 CO->getTrueExpr()->getType(), 7695 CO->getTrueExpr()); 7696 std::tie(FalseTy, FalseName) = 7697 shouldNotPrintDirectly(Context, 7698 CO->getFalseExpr()->getType(), 7699 CO->getFalseExpr()); 7700 7701 if (TrueTy == FalseTy) 7702 return std::make_pair(TrueTy, TrueName); 7703 else if (TrueTy.isNull()) 7704 return std::make_pair(FalseTy, FalseName); 7705 else if (FalseTy.isNull()) 7706 return std::make_pair(TrueTy, TrueName); 7707 } 7708 7709 return std::make_pair(QualType(), StringRef()); 7710 } 7711 7712 bool 7713 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7714 const char *StartSpecifier, 7715 unsigned SpecifierLen, 7716 const Expr *E) { 7717 using namespace analyze_format_string; 7718 using namespace analyze_printf; 7719 7720 // Now type check the data expression that matches the 7721 // format specifier. 7722 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 7723 if (!AT.isValid()) 7724 return true; 7725 7726 QualType ExprTy = E->getType(); 7727 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 7728 ExprTy = TET->getUnderlyingExpr()->getType(); 7729 } 7730 7731 const analyze_printf::ArgType::MatchKind Match = 7732 AT.matchesType(S.Context, ExprTy); 7733 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic; 7734 if (Match == analyze_printf::ArgType::Match) 7735 return true; 7736 7737 // Look through argument promotions for our error message's reported type. 7738 // This includes the integral and floating promotions, but excludes array 7739 // and function pointer decay; seeing that an argument intended to be a 7740 // string has type 'char [6]' is probably more confusing than 'char *'. 7741 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7742 if (ICE->getCastKind() == CK_IntegralCast || 7743 ICE->getCastKind() == CK_FloatingCast) { 7744 E = ICE->getSubExpr(); 7745 ExprTy = E->getType(); 7746 7747 // Check if we didn't match because of an implicit cast from a 'char' 7748 // or 'short' to an 'int'. This is done because printf is a varargs 7749 // function. 7750 if (ICE->getType() == S.Context.IntTy || 7751 ICE->getType() == S.Context.UnsignedIntTy) { 7752 // All further checking is done on the subexpression. 7753 if (AT.matchesType(S.Context, ExprTy)) 7754 return true; 7755 } 7756 } 7757 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 7758 // Special case for 'a', which has type 'int' in C. 7759 // Note, however, that we do /not/ want to treat multibyte constants like 7760 // 'MooV' as characters! This form is deprecated but still exists. 7761 if (ExprTy == S.Context.IntTy) 7762 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 7763 ExprTy = S.Context.CharTy; 7764 } 7765 7766 // Look through enums to their underlying type. 7767 bool IsEnum = false; 7768 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 7769 ExprTy = EnumTy->getDecl()->getIntegerType(); 7770 IsEnum = true; 7771 } 7772 7773 // %C in an Objective-C context prints a unichar, not a wchar_t. 7774 // If the argument is an integer of some kind, believe the %C and suggest 7775 // a cast instead of changing the conversion specifier. 7776 QualType IntendedTy = ExprTy; 7777 if (isObjCContext() && 7778 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 7779 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 7780 !ExprTy->isCharType()) { 7781 // 'unichar' is defined as a typedef of unsigned short, but we should 7782 // prefer using the typedef if it is visible. 7783 IntendedTy = S.Context.UnsignedShortTy; 7784 7785 // While we are here, check if the value is an IntegerLiteral that happens 7786 // to be within the valid range. 7787 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 7788 const llvm::APInt &V = IL->getValue(); 7789 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 7790 return true; 7791 } 7792 7793 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 7794 Sema::LookupOrdinaryName); 7795 if (S.LookupName(Result, S.getCurScope())) { 7796 NamedDecl *ND = Result.getFoundDecl(); 7797 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 7798 if (TD->getUnderlyingType() == IntendedTy) 7799 IntendedTy = S.Context.getTypedefType(TD); 7800 } 7801 } 7802 } 7803 7804 // Special-case some of Darwin's platform-independence types by suggesting 7805 // casts to primitive types that are known to be large enough. 7806 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 7807 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 7808 QualType CastTy; 7809 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 7810 if (!CastTy.isNull()) { 7811 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 7812 // (long in ASTContext). Only complain to pedants. 7813 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 7814 (AT.isSizeT() || AT.isPtrdiffT()) && 7815 AT.matchesType(S.Context, CastTy)) 7816 Pedantic = true; 7817 IntendedTy = CastTy; 7818 ShouldNotPrintDirectly = true; 7819 } 7820 } 7821 7822 // We may be able to offer a FixItHint if it is a supported type. 7823 PrintfSpecifier fixedFS = FS; 7824 bool Success = 7825 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 7826 7827 if (Success) { 7828 // Get the fix string from the fixed format specifier 7829 SmallString<16> buf; 7830 llvm::raw_svector_ostream os(buf); 7831 fixedFS.toString(os); 7832 7833 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 7834 7835 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 7836 unsigned Diag = 7837 Pedantic 7838 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 7839 : diag::warn_format_conversion_argument_type_mismatch; 7840 // In this case, the specifier is wrong and should be changed to match 7841 // the argument. 7842 EmitFormatDiagnostic(S.PDiag(Diag) 7843 << AT.getRepresentativeTypeName(S.Context) 7844 << IntendedTy << IsEnum << E->getSourceRange(), 7845 E->getBeginLoc(), 7846 /*IsStringLocation*/ false, SpecRange, 7847 FixItHint::CreateReplacement(SpecRange, os.str())); 7848 } else { 7849 // The canonical type for formatting this value is different from the 7850 // actual type of the expression. (This occurs, for example, with Darwin's 7851 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 7852 // should be printed as 'long' for 64-bit compatibility.) 7853 // Rather than emitting a normal format/argument mismatch, we want to 7854 // add a cast to the recommended type (and correct the format string 7855 // if necessary). 7856 SmallString<16> CastBuf; 7857 llvm::raw_svector_ostream CastFix(CastBuf); 7858 CastFix << "("; 7859 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 7860 CastFix << ")"; 7861 7862 SmallVector<FixItHint,4> Hints; 7863 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 7864 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 7865 7866 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 7867 // If there's already a cast present, just replace it. 7868 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 7869 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 7870 7871 } else if (!requiresParensToAddCast(E)) { 7872 // If the expression has high enough precedence, 7873 // just write the C-style cast. 7874 Hints.push_back( 7875 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 7876 } else { 7877 // Otherwise, add parens around the expression as well as the cast. 7878 CastFix << "("; 7879 Hints.push_back( 7880 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 7881 7882 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 7883 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 7884 } 7885 7886 if (ShouldNotPrintDirectly) { 7887 // The expression has a type that should not be printed directly. 7888 // We extract the name from the typedef because we don't want to show 7889 // the underlying type in the diagnostic. 7890 StringRef Name; 7891 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 7892 Name = TypedefTy->getDecl()->getName(); 7893 else 7894 Name = CastTyName; 7895 unsigned Diag = Pedantic 7896 ? diag::warn_format_argument_needs_cast_pedantic 7897 : diag::warn_format_argument_needs_cast; 7898 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 7899 << E->getSourceRange(), 7900 E->getBeginLoc(), /*IsStringLocation=*/false, 7901 SpecRange, Hints); 7902 } else { 7903 // In this case, the expression could be printed using a different 7904 // specifier, but we've decided that the specifier is probably correct 7905 // and we should cast instead. Just use the normal warning message. 7906 EmitFormatDiagnostic( 7907 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7908 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 7909 << E->getSourceRange(), 7910 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 7911 } 7912 } 7913 } else { 7914 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 7915 SpecifierLen); 7916 // Since the warning for passing non-POD types to variadic functions 7917 // was deferred until now, we emit a warning for non-POD 7918 // arguments here. 7919 switch (S.isValidVarArgType(ExprTy)) { 7920 case Sema::VAK_Valid: 7921 case Sema::VAK_ValidInCXX11: { 7922 unsigned Diag = 7923 Pedantic 7924 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 7925 : diag::warn_format_conversion_argument_type_mismatch; 7926 7927 EmitFormatDiagnostic( 7928 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 7929 << IsEnum << CSR << E->getSourceRange(), 7930 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7931 break; 7932 } 7933 case Sema::VAK_Undefined: 7934 case Sema::VAK_MSVCUndefined: 7935 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 7936 << S.getLangOpts().CPlusPlus11 << ExprTy 7937 << CallType 7938 << AT.getRepresentativeTypeName(S.Context) << CSR 7939 << E->getSourceRange(), 7940 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7941 checkForCStrMembers(AT, E); 7942 break; 7943 7944 case Sema::VAK_Invalid: 7945 if (ExprTy->isObjCObjectType()) 7946 EmitFormatDiagnostic( 7947 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 7948 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 7949 << AT.getRepresentativeTypeName(S.Context) << CSR 7950 << E->getSourceRange(), 7951 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7952 else 7953 // FIXME: If this is an initializer list, suggest removing the braces 7954 // or inserting a cast to the target type. 7955 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 7956 << isa<InitListExpr>(E) << ExprTy << CallType 7957 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 7958 break; 7959 } 7960 7961 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 7962 "format string specifier index out of range"); 7963 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 7964 } 7965 7966 return true; 7967 } 7968 7969 //===--- CHECK: Scanf format string checking ------------------------------===// 7970 7971 namespace { 7972 7973 class CheckScanfHandler : public CheckFormatHandler { 7974 public: 7975 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 7976 const Expr *origFormatExpr, Sema::FormatStringType type, 7977 unsigned firstDataArg, unsigned numDataArgs, 7978 const char *beg, bool hasVAListArg, 7979 ArrayRef<const Expr *> Args, unsigned formatIdx, 7980 bool inFunctionCall, Sema::VariadicCallType CallType, 7981 llvm::SmallBitVector &CheckedVarArgs, 7982 UncoveredArgHandler &UncoveredArg) 7983 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7984 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7985 inFunctionCall, CallType, CheckedVarArgs, 7986 UncoveredArg) {} 7987 7988 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 7989 const char *startSpecifier, 7990 unsigned specifierLen) override; 7991 7992 bool HandleInvalidScanfConversionSpecifier( 7993 const analyze_scanf::ScanfSpecifier &FS, 7994 const char *startSpecifier, 7995 unsigned specifierLen) override; 7996 7997 void HandleIncompleteScanList(const char *start, const char *end) override; 7998 }; 7999 8000 } // namespace 8001 8002 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8003 const char *end) { 8004 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8005 getLocationOfByte(end), /*IsStringLocation*/true, 8006 getSpecifierRange(start, end - start)); 8007 } 8008 8009 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8010 const analyze_scanf::ScanfSpecifier &FS, 8011 const char *startSpecifier, 8012 unsigned specifierLen) { 8013 const analyze_scanf::ScanfConversionSpecifier &CS = 8014 FS.getConversionSpecifier(); 8015 8016 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8017 getLocationOfByte(CS.getStart()), 8018 startSpecifier, specifierLen, 8019 CS.getStart(), CS.getLength()); 8020 } 8021 8022 bool CheckScanfHandler::HandleScanfSpecifier( 8023 const analyze_scanf::ScanfSpecifier &FS, 8024 const char *startSpecifier, 8025 unsigned specifierLen) { 8026 using namespace analyze_scanf; 8027 using namespace analyze_format_string; 8028 8029 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8030 8031 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8032 // be used to decide if we are using positional arguments consistently. 8033 if (FS.consumesDataArgument()) { 8034 if (atFirstArg) { 8035 atFirstArg = false; 8036 usesPositionalArgs = FS.usesPositionalArg(); 8037 } 8038 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8039 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8040 startSpecifier, specifierLen); 8041 return false; 8042 } 8043 } 8044 8045 // Check if the field with is non-zero. 8046 const OptionalAmount &Amt = FS.getFieldWidth(); 8047 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8048 if (Amt.getConstantAmount() == 0) { 8049 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8050 Amt.getConstantLength()); 8051 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8052 getLocationOfByte(Amt.getStart()), 8053 /*IsStringLocation*/true, R, 8054 FixItHint::CreateRemoval(R)); 8055 } 8056 } 8057 8058 if (!FS.consumesDataArgument()) { 8059 // FIXME: Technically specifying a precision or field width here 8060 // makes no sense. Worth issuing a warning at some point. 8061 return true; 8062 } 8063 8064 // Consume the argument. 8065 unsigned argIndex = FS.getArgIndex(); 8066 if (argIndex < NumDataArgs) { 8067 // The check to see if the argIndex is valid will come later. 8068 // We set the bit here because we may exit early from this 8069 // function if we encounter some other error. 8070 CoveredArgs.set(argIndex); 8071 } 8072 8073 // Check the length modifier is valid with the given conversion specifier. 8074 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 8075 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8076 diag::warn_format_nonsensical_length); 8077 else if (!FS.hasStandardLengthModifier()) 8078 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8079 else if (!FS.hasStandardLengthConversionCombination()) 8080 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8081 diag::warn_format_non_standard_conversion_spec); 8082 8083 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8084 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8085 8086 // The remaining checks depend on the data arguments. 8087 if (HasVAListArg) 8088 return true; 8089 8090 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8091 return false; 8092 8093 // Check that the argument type matches the format specifier. 8094 const Expr *Ex = getDataArg(argIndex); 8095 if (!Ex) 8096 return true; 8097 8098 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8099 8100 if (!AT.isValid()) { 8101 return true; 8102 } 8103 8104 analyze_format_string::ArgType::MatchKind Match = 8105 AT.matchesType(S.Context, Ex->getType()); 8106 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8107 if (Match == analyze_format_string::ArgType::Match) 8108 return true; 8109 8110 ScanfSpecifier fixedFS = FS; 8111 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8112 S.getLangOpts(), S.Context); 8113 8114 unsigned Diag = 8115 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8116 : diag::warn_format_conversion_argument_type_mismatch; 8117 8118 if (Success) { 8119 // Get the fix string from the fixed format specifier. 8120 SmallString<128> buf; 8121 llvm::raw_svector_ostream os(buf); 8122 fixedFS.toString(os); 8123 8124 EmitFormatDiagnostic( 8125 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8126 << Ex->getType() << false << Ex->getSourceRange(), 8127 Ex->getBeginLoc(), 8128 /*IsStringLocation*/ false, 8129 getSpecifierRange(startSpecifier, specifierLen), 8130 FixItHint::CreateReplacement( 8131 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8132 } else { 8133 EmitFormatDiagnostic(S.PDiag(Diag) 8134 << AT.getRepresentativeTypeName(S.Context) 8135 << Ex->getType() << false << Ex->getSourceRange(), 8136 Ex->getBeginLoc(), 8137 /*IsStringLocation*/ false, 8138 getSpecifierRange(startSpecifier, specifierLen)); 8139 } 8140 8141 return true; 8142 } 8143 8144 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8145 const Expr *OrigFormatExpr, 8146 ArrayRef<const Expr *> Args, 8147 bool HasVAListArg, unsigned format_idx, 8148 unsigned firstDataArg, 8149 Sema::FormatStringType Type, 8150 bool inFunctionCall, 8151 Sema::VariadicCallType CallType, 8152 llvm::SmallBitVector &CheckedVarArgs, 8153 UncoveredArgHandler &UncoveredArg) { 8154 // CHECK: is the format string a wide literal? 8155 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8156 CheckFormatHandler::EmitFormatDiagnostic( 8157 S, inFunctionCall, Args[format_idx], 8158 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8159 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8160 return; 8161 } 8162 8163 // Str - The format string. NOTE: this is NOT null-terminated! 8164 StringRef StrRef = FExpr->getString(); 8165 const char *Str = StrRef.data(); 8166 // Account for cases where the string literal is truncated in a declaration. 8167 const ConstantArrayType *T = 8168 S.Context.getAsConstantArrayType(FExpr->getType()); 8169 assert(T && "String literal not of constant array type!"); 8170 size_t TypeSize = T->getSize().getZExtValue(); 8171 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8172 const unsigned numDataArgs = Args.size() - firstDataArg; 8173 8174 // Emit a warning if the string literal is truncated and does not contain an 8175 // embedded null character. 8176 if (TypeSize <= StrRef.size() && 8177 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8178 CheckFormatHandler::EmitFormatDiagnostic( 8179 S, inFunctionCall, Args[format_idx], 8180 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8181 FExpr->getBeginLoc(), 8182 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8183 return; 8184 } 8185 8186 // CHECK: empty format string? 8187 if (StrLen == 0 && numDataArgs > 0) { 8188 CheckFormatHandler::EmitFormatDiagnostic( 8189 S, inFunctionCall, Args[format_idx], 8190 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8191 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8192 return; 8193 } 8194 8195 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8196 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8197 Type == Sema::FST_OSTrace) { 8198 CheckPrintfHandler H( 8199 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8200 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8201 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8202 CheckedVarArgs, UncoveredArg); 8203 8204 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8205 S.getLangOpts(), 8206 S.Context.getTargetInfo(), 8207 Type == Sema::FST_FreeBSDKPrintf)) 8208 H.DoneProcessing(); 8209 } else if (Type == Sema::FST_Scanf) { 8210 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8211 numDataArgs, Str, HasVAListArg, Args, format_idx, 8212 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8213 8214 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8215 S.getLangOpts(), 8216 S.Context.getTargetInfo())) 8217 H.DoneProcessing(); 8218 } // TODO: handle other formats 8219 } 8220 8221 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8222 // Str - The format string. NOTE: this is NOT null-terminated! 8223 StringRef StrRef = FExpr->getString(); 8224 const char *Str = StrRef.data(); 8225 // Account for cases where the string literal is truncated in a declaration. 8226 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8227 assert(T && "String literal not of constant array type!"); 8228 size_t TypeSize = T->getSize().getZExtValue(); 8229 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8230 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8231 getLangOpts(), 8232 Context.getTargetInfo()); 8233 } 8234 8235 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8236 8237 // Returns the related absolute value function that is larger, of 0 if one 8238 // does not exist. 8239 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8240 switch (AbsFunction) { 8241 default: 8242 return 0; 8243 8244 case Builtin::BI__builtin_abs: 8245 return Builtin::BI__builtin_labs; 8246 case Builtin::BI__builtin_labs: 8247 return Builtin::BI__builtin_llabs; 8248 case Builtin::BI__builtin_llabs: 8249 return 0; 8250 8251 case Builtin::BI__builtin_fabsf: 8252 return Builtin::BI__builtin_fabs; 8253 case Builtin::BI__builtin_fabs: 8254 return Builtin::BI__builtin_fabsl; 8255 case Builtin::BI__builtin_fabsl: 8256 return 0; 8257 8258 case Builtin::BI__builtin_cabsf: 8259 return Builtin::BI__builtin_cabs; 8260 case Builtin::BI__builtin_cabs: 8261 return Builtin::BI__builtin_cabsl; 8262 case Builtin::BI__builtin_cabsl: 8263 return 0; 8264 8265 case Builtin::BIabs: 8266 return Builtin::BIlabs; 8267 case Builtin::BIlabs: 8268 return Builtin::BIllabs; 8269 case Builtin::BIllabs: 8270 return 0; 8271 8272 case Builtin::BIfabsf: 8273 return Builtin::BIfabs; 8274 case Builtin::BIfabs: 8275 return Builtin::BIfabsl; 8276 case Builtin::BIfabsl: 8277 return 0; 8278 8279 case Builtin::BIcabsf: 8280 return Builtin::BIcabs; 8281 case Builtin::BIcabs: 8282 return Builtin::BIcabsl; 8283 case Builtin::BIcabsl: 8284 return 0; 8285 } 8286 } 8287 8288 // Returns the argument type of the absolute value function. 8289 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8290 unsigned AbsType) { 8291 if (AbsType == 0) 8292 return QualType(); 8293 8294 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8295 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8296 if (Error != ASTContext::GE_None) 8297 return QualType(); 8298 8299 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8300 if (!FT) 8301 return QualType(); 8302 8303 if (FT->getNumParams() != 1) 8304 return QualType(); 8305 8306 return FT->getParamType(0); 8307 } 8308 8309 // Returns the best absolute value function, or zero, based on type and 8310 // current absolute value function. 8311 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8312 unsigned AbsFunctionKind) { 8313 unsigned BestKind = 0; 8314 uint64_t ArgSize = Context.getTypeSize(ArgType); 8315 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8316 Kind = getLargerAbsoluteValueFunction(Kind)) { 8317 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8318 if (Context.getTypeSize(ParamType) >= ArgSize) { 8319 if (BestKind == 0) 8320 BestKind = Kind; 8321 else if (Context.hasSameType(ParamType, ArgType)) { 8322 BestKind = Kind; 8323 break; 8324 } 8325 } 8326 } 8327 return BestKind; 8328 } 8329 8330 enum AbsoluteValueKind { 8331 AVK_Integer, 8332 AVK_Floating, 8333 AVK_Complex 8334 }; 8335 8336 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8337 if (T->isIntegralOrEnumerationType()) 8338 return AVK_Integer; 8339 if (T->isRealFloatingType()) 8340 return AVK_Floating; 8341 if (T->isAnyComplexType()) 8342 return AVK_Complex; 8343 8344 llvm_unreachable("Type not integer, floating, or complex"); 8345 } 8346 8347 // Changes the absolute value function to a different type. Preserves whether 8348 // the function is a builtin. 8349 static unsigned changeAbsFunction(unsigned AbsKind, 8350 AbsoluteValueKind ValueKind) { 8351 switch (ValueKind) { 8352 case AVK_Integer: 8353 switch (AbsKind) { 8354 default: 8355 return 0; 8356 case Builtin::BI__builtin_fabsf: 8357 case Builtin::BI__builtin_fabs: 8358 case Builtin::BI__builtin_fabsl: 8359 case Builtin::BI__builtin_cabsf: 8360 case Builtin::BI__builtin_cabs: 8361 case Builtin::BI__builtin_cabsl: 8362 return Builtin::BI__builtin_abs; 8363 case Builtin::BIfabsf: 8364 case Builtin::BIfabs: 8365 case Builtin::BIfabsl: 8366 case Builtin::BIcabsf: 8367 case Builtin::BIcabs: 8368 case Builtin::BIcabsl: 8369 return Builtin::BIabs; 8370 } 8371 case AVK_Floating: 8372 switch (AbsKind) { 8373 default: 8374 return 0; 8375 case Builtin::BI__builtin_abs: 8376 case Builtin::BI__builtin_labs: 8377 case Builtin::BI__builtin_llabs: 8378 case Builtin::BI__builtin_cabsf: 8379 case Builtin::BI__builtin_cabs: 8380 case Builtin::BI__builtin_cabsl: 8381 return Builtin::BI__builtin_fabsf; 8382 case Builtin::BIabs: 8383 case Builtin::BIlabs: 8384 case Builtin::BIllabs: 8385 case Builtin::BIcabsf: 8386 case Builtin::BIcabs: 8387 case Builtin::BIcabsl: 8388 return Builtin::BIfabsf; 8389 } 8390 case AVK_Complex: 8391 switch (AbsKind) { 8392 default: 8393 return 0; 8394 case Builtin::BI__builtin_abs: 8395 case Builtin::BI__builtin_labs: 8396 case Builtin::BI__builtin_llabs: 8397 case Builtin::BI__builtin_fabsf: 8398 case Builtin::BI__builtin_fabs: 8399 case Builtin::BI__builtin_fabsl: 8400 return Builtin::BI__builtin_cabsf; 8401 case Builtin::BIabs: 8402 case Builtin::BIlabs: 8403 case Builtin::BIllabs: 8404 case Builtin::BIfabsf: 8405 case Builtin::BIfabs: 8406 case Builtin::BIfabsl: 8407 return Builtin::BIcabsf; 8408 } 8409 } 8410 llvm_unreachable("Unable to convert function"); 8411 } 8412 8413 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8414 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8415 if (!FnInfo) 8416 return 0; 8417 8418 switch (FDecl->getBuiltinID()) { 8419 default: 8420 return 0; 8421 case Builtin::BI__builtin_abs: 8422 case Builtin::BI__builtin_fabs: 8423 case Builtin::BI__builtin_fabsf: 8424 case Builtin::BI__builtin_fabsl: 8425 case Builtin::BI__builtin_labs: 8426 case Builtin::BI__builtin_llabs: 8427 case Builtin::BI__builtin_cabs: 8428 case Builtin::BI__builtin_cabsf: 8429 case Builtin::BI__builtin_cabsl: 8430 case Builtin::BIabs: 8431 case Builtin::BIlabs: 8432 case Builtin::BIllabs: 8433 case Builtin::BIfabs: 8434 case Builtin::BIfabsf: 8435 case Builtin::BIfabsl: 8436 case Builtin::BIcabs: 8437 case Builtin::BIcabsf: 8438 case Builtin::BIcabsl: 8439 return FDecl->getBuiltinID(); 8440 } 8441 llvm_unreachable("Unknown Builtin type"); 8442 } 8443 8444 // If the replacement is valid, emit a note with replacement function. 8445 // Additionally, suggest including the proper header if not already included. 8446 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8447 unsigned AbsKind, QualType ArgType) { 8448 bool EmitHeaderHint = true; 8449 const char *HeaderName = nullptr; 8450 const char *FunctionName = nullptr; 8451 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8452 FunctionName = "std::abs"; 8453 if (ArgType->isIntegralOrEnumerationType()) { 8454 HeaderName = "cstdlib"; 8455 } else if (ArgType->isRealFloatingType()) { 8456 HeaderName = "cmath"; 8457 } else { 8458 llvm_unreachable("Invalid Type"); 8459 } 8460 8461 // Lookup all std::abs 8462 if (NamespaceDecl *Std = S.getStdNamespace()) { 8463 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8464 R.suppressDiagnostics(); 8465 S.LookupQualifiedName(R, Std); 8466 8467 for (const auto *I : R) { 8468 const FunctionDecl *FDecl = nullptr; 8469 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8470 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8471 } else { 8472 FDecl = dyn_cast<FunctionDecl>(I); 8473 } 8474 if (!FDecl) 8475 continue; 8476 8477 // Found std::abs(), check that they are the right ones. 8478 if (FDecl->getNumParams() != 1) 8479 continue; 8480 8481 // Check that the parameter type can handle the argument. 8482 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8483 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8484 S.Context.getTypeSize(ArgType) <= 8485 S.Context.getTypeSize(ParamType)) { 8486 // Found a function, don't need the header hint. 8487 EmitHeaderHint = false; 8488 break; 8489 } 8490 } 8491 } 8492 } else { 8493 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8494 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8495 8496 if (HeaderName) { 8497 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8498 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8499 R.suppressDiagnostics(); 8500 S.LookupName(R, S.getCurScope()); 8501 8502 if (R.isSingleResult()) { 8503 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8504 if (FD && FD->getBuiltinID() == AbsKind) { 8505 EmitHeaderHint = false; 8506 } else { 8507 return; 8508 } 8509 } else if (!R.empty()) { 8510 return; 8511 } 8512 } 8513 } 8514 8515 S.Diag(Loc, diag::note_replace_abs_function) 8516 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8517 8518 if (!HeaderName) 8519 return; 8520 8521 if (!EmitHeaderHint) 8522 return; 8523 8524 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 8525 << FunctionName; 8526 } 8527 8528 template <std::size_t StrLen> 8529 static bool IsStdFunction(const FunctionDecl *FDecl, 8530 const char (&Str)[StrLen]) { 8531 if (!FDecl) 8532 return false; 8533 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 8534 return false; 8535 if (!FDecl->isInStdNamespace()) 8536 return false; 8537 8538 return true; 8539 } 8540 8541 // Warn when using the wrong abs() function. 8542 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 8543 const FunctionDecl *FDecl) { 8544 if (Call->getNumArgs() != 1) 8545 return; 8546 8547 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 8548 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 8549 if (AbsKind == 0 && !IsStdAbs) 8550 return; 8551 8552 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8553 QualType ParamType = Call->getArg(0)->getType(); 8554 8555 // Unsigned types cannot be negative. Suggest removing the absolute value 8556 // function call. 8557 if (ArgType->isUnsignedIntegerType()) { 8558 const char *FunctionName = 8559 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 8560 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 8561 Diag(Call->getExprLoc(), diag::note_remove_abs) 8562 << FunctionName 8563 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 8564 return; 8565 } 8566 8567 // Taking the absolute value of a pointer is very suspicious, they probably 8568 // wanted to index into an array, dereference a pointer, call a function, etc. 8569 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 8570 unsigned DiagType = 0; 8571 if (ArgType->isFunctionType()) 8572 DiagType = 1; 8573 else if (ArgType->isArrayType()) 8574 DiagType = 2; 8575 8576 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 8577 return; 8578 } 8579 8580 // std::abs has overloads which prevent most of the absolute value problems 8581 // from occurring. 8582 if (IsStdAbs) 8583 return; 8584 8585 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 8586 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 8587 8588 // The argument and parameter are the same kind. Check if they are the right 8589 // size. 8590 if (ArgValueKind == ParamValueKind) { 8591 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 8592 return; 8593 8594 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 8595 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 8596 << FDecl << ArgType << ParamType; 8597 8598 if (NewAbsKind == 0) 8599 return; 8600 8601 emitReplacement(*this, Call->getExprLoc(), 8602 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8603 return; 8604 } 8605 8606 // ArgValueKind != ParamValueKind 8607 // The wrong type of absolute value function was used. Attempt to find the 8608 // proper one. 8609 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 8610 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 8611 if (NewAbsKind == 0) 8612 return; 8613 8614 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 8615 << FDecl << ParamValueKind << ArgValueKind; 8616 8617 emitReplacement(*this, Call->getExprLoc(), 8618 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8619 } 8620 8621 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 8622 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 8623 const FunctionDecl *FDecl) { 8624 if (!Call || !FDecl) return; 8625 8626 // Ignore template specializations and macros. 8627 if (inTemplateInstantiation()) return; 8628 if (Call->getExprLoc().isMacroID()) return; 8629 8630 // Only care about the one template argument, two function parameter std::max 8631 if (Call->getNumArgs() != 2) return; 8632 if (!IsStdFunction(FDecl, "max")) return; 8633 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 8634 if (!ArgList) return; 8635 if (ArgList->size() != 1) return; 8636 8637 // Check that template type argument is unsigned integer. 8638 const auto& TA = ArgList->get(0); 8639 if (TA.getKind() != TemplateArgument::Type) return; 8640 QualType ArgType = TA.getAsType(); 8641 if (!ArgType->isUnsignedIntegerType()) return; 8642 8643 // See if either argument is a literal zero. 8644 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 8645 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 8646 if (!MTE) return false; 8647 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 8648 if (!Num) return false; 8649 if (Num->getValue() != 0) return false; 8650 return true; 8651 }; 8652 8653 const Expr *FirstArg = Call->getArg(0); 8654 const Expr *SecondArg = Call->getArg(1); 8655 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 8656 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 8657 8658 // Only warn when exactly one argument is zero. 8659 if (IsFirstArgZero == IsSecondArgZero) return; 8660 8661 SourceRange FirstRange = FirstArg->getSourceRange(); 8662 SourceRange SecondRange = SecondArg->getSourceRange(); 8663 8664 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 8665 8666 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 8667 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 8668 8669 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 8670 SourceRange RemovalRange; 8671 if (IsFirstArgZero) { 8672 RemovalRange = SourceRange(FirstRange.getBegin(), 8673 SecondRange.getBegin().getLocWithOffset(-1)); 8674 } else { 8675 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 8676 SecondRange.getEnd()); 8677 } 8678 8679 Diag(Call->getExprLoc(), diag::note_remove_max_call) 8680 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 8681 << FixItHint::CreateRemoval(RemovalRange); 8682 } 8683 8684 //===--- CHECK: Standard memory functions ---------------------------------===// 8685 8686 /// Takes the expression passed to the size_t parameter of functions 8687 /// such as memcmp, strncat, etc and warns if it's a comparison. 8688 /// 8689 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 8690 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 8691 IdentifierInfo *FnName, 8692 SourceLocation FnLoc, 8693 SourceLocation RParenLoc) { 8694 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 8695 if (!Size) 8696 return false; 8697 8698 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 8699 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 8700 return false; 8701 8702 SourceRange SizeRange = Size->getSourceRange(); 8703 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 8704 << SizeRange << FnName; 8705 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 8706 << FnName 8707 << FixItHint::CreateInsertion( 8708 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 8709 << FixItHint::CreateRemoval(RParenLoc); 8710 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 8711 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 8712 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 8713 ")"); 8714 8715 return true; 8716 } 8717 8718 /// Determine whether the given type is or contains a dynamic class type 8719 /// (e.g., whether it has a vtable). 8720 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 8721 bool &IsContained) { 8722 // Look through array types while ignoring qualifiers. 8723 const Type *Ty = T->getBaseElementTypeUnsafe(); 8724 IsContained = false; 8725 8726 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 8727 RD = RD ? RD->getDefinition() : nullptr; 8728 if (!RD || RD->isInvalidDecl()) 8729 return nullptr; 8730 8731 if (RD->isDynamicClass()) 8732 return RD; 8733 8734 // Check all the fields. If any bases were dynamic, the class is dynamic. 8735 // It's impossible for a class to transitively contain itself by value, so 8736 // infinite recursion is impossible. 8737 for (auto *FD : RD->fields()) { 8738 bool SubContained; 8739 if (const CXXRecordDecl *ContainedRD = 8740 getContainedDynamicClass(FD->getType(), SubContained)) { 8741 IsContained = true; 8742 return ContainedRD; 8743 } 8744 } 8745 8746 return nullptr; 8747 } 8748 8749 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 8750 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 8751 if (Unary->getKind() == UETT_SizeOf) 8752 return Unary; 8753 return nullptr; 8754 } 8755 8756 /// If E is a sizeof expression, returns its argument expression, 8757 /// otherwise returns NULL. 8758 static const Expr *getSizeOfExprArg(const Expr *E) { 8759 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8760 if (!SizeOf->isArgumentType()) 8761 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 8762 return nullptr; 8763 } 8764 8765 /// If E is a sizeof expression, returns its argument type. 8766 static QualType getSizeOfArgType(const Expr *E) { 8767 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8768 return SizeOf->getTypeOfArgument(); 8769 return QualType(); 8770 } 8771 8772 namespace { 8773 8774 struct SearchNonTrivialToInitializeField 8775 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 8776 using Super = 8777 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 8778 8779 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 8780 8781 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 8782 SourceLocation SL) { 8783 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8784 asDerived().visitArray(PDIK, AT, SL); 8785 return; 8786 } 8787 8788 Super::visitWithKind(PDIK, FT, SL); 8789 } 8790 8791 void visitARCStrong(QualType FT, SourceLocation SL) { 8792 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8793 } 8794 void visitARCWeak(QualType FT, SourceLocation SL) { 8795 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8796 } 8797 void visitStruct(QualType FT, SourceLocation SL) { 8798 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8799 visit(FD->getType(), FD->getLocation()); 8800 } 8801 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 8802 const ArrayType *AT, SourceLocation SL) { 8803 visit(getContext().getBaseElementType(AT), SL); 8804 } 8805 void visitTrivial(QualType FT, SourceLocation SL) {} 8806 8807 static void diag(QualType RT, const Expr *E, Sema &S) { 8808 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 8809 } 8810 8811 ASTContext &getContext() { return S.getASTContext(); } 8812 8813 const Expr *E; 8814 Sema &S; 8815 }; 8816 8817 struct SearchNonTrivialToCopyField 8818 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 8819 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 8820 8821 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 8822 8823 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 8824 SourceLocation SL) { 8825 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8826 asDerived().visitArray(PCK, AT, SL); 8827 return; 8828 } 8829 8830 Super::visitWithKind(PCK, FT, SL); 8831 } 8832 8833 void visitARCStrong(QualType FT, SourceLocation SL) { 8834 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8835 } 8836 void visitARCWeak(QualType FT, SourceLocation SL) { 8837 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8838 } 8839 void visitStruct(QualType FT, SourceLocation SL) { 8840 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8841 visit(FD->getType(), FD->getLocation()); 8842 } 8843 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 8844 SourceLocation SL) { 8845 visit(getContext().getBaseElementType(AT), SL); 8846 } 8847 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 8848 SourceLocation SL) {} 8849 void visitTrivial(QualType FT, SourceLocation SL) {} 8850 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 8851 8852 static void diag(QualType RT, const Expr *E, Sema &S) { 8853 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 8854 } 8855 8856 ASTContext &getContext() { return S.getASTContext(); } 8857 8858 const Expr *E; 8859 Sema &S; 8860 }; 8861 8862 } 8863 8864 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 8865 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 8866 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 8867 8868 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 8869 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 8870 return false; 8871 8872 return doesExprLikelyComputeSize(BO->getLHS()) || 8873 doesExprLikelyComputeSize(BO->getRHS()); 8874 } 8875 8876 return getAsSizeOfExpr(SizeofExpr) != nullptr; 8877 } 8878 8879 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 8880 /// 8881 /// \code 8882 /// #define MACRO 0 8883 /// foo(MACRO); 8884 /// foo(0); 8885 /// \endcode 8886 /// 8887 /// This should return true for the first call to foo, but not for the second 8888 /// (regardless of whether foo is a macro or function). 8889 static bool isArgumentExpandedFromMacro(SourceManager &SM, 8890 SourceLocation CallLoc, 8891 SourceLocation ArgLoc) { 8892 if (!CallLoc.isMacroID()) 8893 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 8894 8895 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 8896 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 8897 } 8898 8899 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 8900 /// last two arguments transposed. 8901 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 8902 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 8903 return; 8904 8905 const Expr *SizeArg = 8906 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 8907 8908 auto isLiteralZero = [](const Expr *E) { 8909 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 8910 }; 8911 8912 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 8913 SourceLocation CallLoc = Call->getRParenLoc(); 8914 SourceManager &SM = S.getSourceManager(); 8915 if (isLiteralZero(SizeArg) && 8916 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 8917 8918 SourceLocation DiagLoc = SizeArg->getExprLoc(); 8919 8920 // Some platforms #define bzero to __builtin_memset. See if this is the 8921 // case, and if so, emit a better diagnostic. 8922 if (BId == Builtin::BIbzero || 8923 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 8924 CallLoc, SM, S.getLangOpts()) == "bzero")) { 8925 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 8926 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 8927 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 8928 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 8929 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 8930 } 8931 return; 8932 } 8933 8934 // If the second argument to a memset is a sizeof expression and the third 8935 // isn't, this is also likely an error. This should catch 8936 // 'memset(buf, sizeof(buf), 0xff)'. 8937 if (BId == Builtin::BImemset && 8938 doesExprLikelyComputeSize(Call->getArg(1)) && 8939 !doesExprLikelyComputeSize(Call->getArg(2))) { 8940 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 8941 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 8942 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 8943 return; 8944 } 8945 } 8946 8947 /// Check for dangerous or invalid arguments to memset(). 8948 /// 8949 /// This issues warnings on known problematic, dangerous or unspecified 8950 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 8951 /// function calls. 8952 /// 8953 /// \param Call The call expression to diagnose. 8954 void Sema::CheckMemaccessArguments(const CallExpr *Call, 8955 unsigned BId, 8956 IdentifierInfo *FnName) { 8957 assert(BId != 0); 8958 8959 // It is possible to have a non-standard definition of memset. Validate 8960 // we have enough arguments, and if not, abort further checking. 8961 unsigned ExpectedNumArgs = 8962 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 8963 if (Call->getNumArgs() < ExpectedNumArgs) 8964 return; 8965 8966 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 8967 BId == Builtin::BIstrndup ? 1 : 2); 8968 unsigned LenArg = 8969 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 8970 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 8971 8972 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 8973 Call->getBeginLoc(), Call->getRParenLoc())) 8974 return; 8975 8976 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 8977 CheckMemaccessSize(*this, BId, Call); 8978 8979 // We have special checking when the length is a sizeof expression. 8980 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 8981 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 8982 llvm::FoldingSetNodeID SizeOfArgID; 8983 8984 // Although widely used, 'bzero' is not a standard function. Be more strict 8985 // with the argument types before allowing diagnostics and only allow the 8986 // form bzero(ptr, sizeof(...)). 8987 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8988 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 8989 return; 8990 8991 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 8992 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 8993 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 8994 8995 QualType DestTy = Dest->getType(); 8996 QualType PointeeTy; 8997 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 8998 PointeeTy = DestPtrTy->getPointeeType(); 8999 9000 // Never warn about void type pointers. This can be used to suppress 9001 // false positives. 9002 if (PointeeTy->isVoidType()) 9003 continue; 9004 9005 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9006 // actually comparing the expressions for equality. Because computing the 9007 // expression IDs can be expensive, we only do this if the diagnostic is 9008 // enabled. 9009 if (SizeOfArg && 9010 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9011 SizeOfArg->getExprLoc())) { 9012 // We only compute IDs for expressions if the warning is enabled, and 9013 // cache the sizeof arg's ID. 9014 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9015 SizeOfArg->Profile(SizeOfArgID, Context, true); 9016 llvm::FoldingSetNodeID DestID; 9017 Dest->Profile(DestID, Context, true); 9018 if (DestID == SizeOfArgID) { 9019 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9020 // over sizeof(src) as well. 9021 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9022 StringRef ReadableName = FnName->getName(); 9023 9024 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9025 if (UnaryOp->getOpcode() == UO_AddrOf) 9026 ActionIdx = 1; // If its an address-of operator, just remove it. 9027 if (!PointeeTy->isIncompleteType() && 9028 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9029 ActionIdx = 2; // If the pointee's size is sizeof(char), 9030 // suggest an explicit length. 9031 9032 // If the function is defined as a builtin macro, do not show macro 9033 // expansion. 9034 SourceLocation SL = SizeOfArg->getExprLoc(); 9035 SourceRange DSR = Dest->getSourceRange(); 9036 SourceRange SSR = SizeOfArg->getSourceRange(); 9037 SourceManager &SM = getSourceManager(); 9038 9039 if (SM.isMacroArgExpansion(SL)) { 9040 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9041 SL = SM.getSpellingLoc(SL); 9042 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9043 SM.getSpellingLoc(DSR.getEnd())); 9044 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9045 SM.getSpellingLoc(SSR.getEnd())); 9046 } 9047 9048 DiagRuntimeBehavior(SL, SizeOfArg, 9049 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9050 << ReadableName 9051 << PointeeTy 9052 << DestTy 9053 << DSR 9054 << SSR); 9055 DiagRuntimeBehavior(SL, SizeOfArg, 9056 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9057 << ActionIdx 9058 << SSR); 9059 9060 break; 9061 } 9062 } 9063 9064 // Also check for cases where the sizeof argument is the exact same 9065 // type as the memory argument, and where it points to a user-defined 9066 // record type. 9067 if (SizeOfArgTy != QualType()) { 9068 if (PointeeTy->isRecordType() && 9069 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9070 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9071 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9072 << FnName << SizeOfArgTy << ArgIdx 9073 << PointeeTy << Dest->getSourceRange() 9074 << LenExpr->getSourceRange()); 9075 break; 9076 } 9077 } 9078 } else if (DestTy->isArrayType()) { 9079 PointeeTy = DestTy; 9080 } 9081 9082 if (PointeeTy == QualType()) 9083 continue; 9084 9085 // Always complain about dynamic classes. 9086 bool IsContained; 9087 if (const CXXRecordDecl *ContainedRD = 9088 getContainedDynamicClass(PointeeTy, IsContained)) { 9089 9090 unsigned OperationType = 0; 9091 // "overwritten" if we're warning about the destination for any call 9092 // but memcmp; otherwise a verb appropriate to the call. 9093 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 9094 if (BId == Builtin::BImemcpy) 9095 OperationType = 1; 9096 else if(BId == Builtin::BImemmove) 9097 OperationType = 2; 9098 else if (BId == Builtin::BImemcmp) 9099 OperationType = 3; 9100 } 9101 9102 DiagRuntimeBehavior( 9103 Dest->getExprLoc(), Dest, 9104 PDiag(diag::warn_dyn_class_memaccess) 9105 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 9106 << FnName << IsContained << ContainedRD << OperationType 9107 << Call->getCallee()->getSourceRange()); 9108 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9109 BId != Builtin::BImemset) 9110 DiagRuntimeBehavior( 9111 Dest->getExprLoc(), Dest, 9112 PDiag(diag::warn_arc_object_memaccess) 9113 << ArgIdx << FnName << PointeeTy 9114 << Call->getCallee()->getSourceRange()); 9115 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9116 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9117 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9118 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9119 PDiag(diag::warn_cstruct_memaccess) 9120 << ArgIdx << FnName << PointeeTy << 0); 9121 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9122 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9123 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9124 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9125 PDiag(diag::warn_cstruct_memaccess) 9126 << ArgIdx << FnName << PointeeTy << 1); 9127 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9128 } else { 9129 continue; 9130 } 9131 } else 9132 continue; 9133 9134 DiagRuntimeBehavior( 9135 Dest->getExprLoc(), Dest, 9136 PDiag(diag::note_bad_memaccess_silence) 9137 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9138 break; 9139 } 9140 } 9141 9142 // A little helper routine: ignore addition and subtraction of integer literals. 9143 // This intentionally does not ignore all integer constant expressions because 9144 // we don't want to remove sizeof(). 9145 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9146 Ex = Ex->IgnoreParenCasts(); 9147 9148 while (true) { 9149 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9150 if (!BO || !BO->isAdditiveOp()) 9151 break; 9152 9153 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9154 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9155 9156 if (isa<IntegerLiteral>(RHS)) 9157 Ex = LHS; 9158 else if (isa<IntegerLiteral>(LHS)) 9159 Ex = RHS; 9160 else 9161 break; 9162 } 9163 9164 return Ex; 9165 } 9166 9167 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9168 ASTContext &Context) { 9169 // Only handle constant-sized or VLAs, but not flexible members. 9170 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9171 // Only issue the FIXIT for arrays of size > 1. 9172 if (CAT->getSize().getSExtValue() <= 1) 9173 return false; 9174 } else if (!Ty->isVariableArrayType()) { 9175 return false; 9176 } 9177 return true; 9178 } 9179 9180 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9181 // be the size of the source, instead of the destination. 9182 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9183 IdentifierInfo *FnName) { 9184 9185 // Don't crash if the user has the wrong number of arguments 9186 unsigned NumArgs = Call->getNumArgs(); 9187 if ((NumArgs != 3) && (NumArgs != 4)) 9188 return; 9189 9190 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9191 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9192 const Expr *CompareWithSrc = nullptr; 9193 9194 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9195 Call->getBeginLoc(), Call->getRParenLoc())) 9196 return; 9197 9198 // Look for 'strlcpy(dst, x, sizeof(x))' 9199 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9200 CompareWithSrc = Ex; 9201 else { 9202 // Look for 'strlcpy(dst, x, strlen(x))' 9203 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9204 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9205 SizeCall->getNumArgs() == 1) 9206 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9207 } 9208 } 9209 9210 if (!CompareWithSrc) 9211 return; 9212 9213 // Determine if the argument to sizeof/strlen is equal to the source 9214 // argument. In principle there's all kinds of things you could do 9215 // here, for instance creating an == expression and evaluating it with 9216 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9217 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9218 if (!SrcArgDRE) 9219 return; 9220 9221 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9222 if (!CompareWithSrcDRE || 9223 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9224 return; 9225 9226 const Expr *OriginalSizeArg = Call->getArg(2); 9227 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9228 << OriginalSizeArg->getSourceRange() << FnName; 9229 9230 // Output a FIXIT hint if the destination is an array (rather than a 9231 // pointer to an array). This could be enhanced to handle some 9232 // pointers if we know the actual size, like if DstArg is 'array+2' 9233 // we could say 'sizeof(array)-2'. 9234 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9235 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9236 return; 9237 9238 SmallString<128> sizeString; 9239 llvm::raw_svector_ostream OS(sizeString); 9240 OS << "sizeof("; 9241 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9242 OS << ")"; 9243 9244 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9245 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9246 OS.str()); 9247 } 9248 9249 /// Check if two expressions refer to the same declaration. 9250 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9251 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9252 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9253 return D1->getDecl() == D2->getDecl(); 9254 return false; 9255 } 9256 9257 static const Expr *getStrlenExprArg(const Expr *E) { 9258 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9259 const FunctionDecl *FD = CE->getDirectCallee(); 9260 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9261 return nullptr; 9262 return CE->getArg(0)->IgnoreParenCasts(); 9263 } 9264 return nullptr; 9265 } 9266 9267 // Warn on anti-patterns as the 'size' argument to strncat. 9268 // The correct size argument should look like following: 9269 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9270 void Sema::CheckStrncatArguments(const CallExpr *CE, 9271 IdentifierInfo *FnName) { 9272 // Don't crash if the user has the wrong number of arguments. 9273 if (CE->getNumArgs() < 3) 9274 return; 9275 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9276 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9277 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9278 9279 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9280 CE->getRParenLoc())) 9281 return; 9282 9283 // Identify common expressions, which are wrongly used as the size argument 9284 // to strncat and may lead to buffer overflows. 9285 unsigned PatternType = 0; 9286 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9287 // - sizeof(dst) 9288 if (referToTheSameDecl(SizeOfArg, DstArg)) 9289 PatternType = 1; 9290 // - sizeof(src) 9291 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9292 PatternType = 2; 9293 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9294 if (BE->getOpcode() == BO_Sub) { 9295 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9296 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9297 // - sizeof(dst) - strlen(dst) 9298 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9299 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9300 PatternType = 1; 9301 // - sizeof(src) - (anything) 9302 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9303 PatternType = 2; 9304 } 9305 } 9306 9307 if (PatternType == 0) 9308 return; 9309 9310 // Generate the diagnostic. 9311 SourceLocation SL = LenArg->getBeginLoc(); 9312 SourceRange SR = LenArg->getSourceRange(); 9313 SourceManager &SM = getSourceManager(); 9314 9315 // If the function is defined as a builtin macro, do not show macro expansion. 9316 if (SM.isMacroArgExpansion(SL)) { 9317 SL = SM.getSpellingLoc(SL); 9318 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9319 SM.getSpellingLoc(SR.getEnd())); 9320 } 9321 9322 // Check if the destination is an array (rather than a pointer to an array). 9323 QualType DstTy = DstArg->getType(); 9324 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9325 Context); 9326 if (!isKnownSizeArray) { 9327 if (PatternType == 1) 9328 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9329 else 9330 Diag(SL, diag::warn_strncat_src_size) << SR; 9331 return; 9332 } 9333 9334 if (PatternType == 1) 9335 Diag(SL, diag::warn_strncat_large_size) << SR; 9336 else 9337 Diag(SL, diag::warn_strncat_src_size) << SR; 9338 9339 SmallString<128> sizeString; 9340 llvm::raw_svector_ostream OS(sizeString); 9341 OS << "sizeof("; 9342 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9343 OS << ") - "; 9344 OS << "strlen("; 9345 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9346 OS << ") - 1"; 9347 9348 Diag(SL, diag::note_strncat_wrong_size) 9349 << FixItHint::CreateReplacement(SR, OS.str()); 9350 } 9351 9352 void 9353 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9354 SourceLocation ReturnLoc, 9355 bool isObjCMethod, 9356 const AttrVec *Attrs, 9357 const FunctionDecl *FD) { 9358 // Check if the return value is null but should not be. 9359 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9360 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9361 CheckNonNullExpr(*this, RetValExp)) 9362 Diag(ReturnLoc, diag::warn_null_ret) 9363 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9364 9365 // C++11 [basic.stc.dynamic.allocation]p4: 9366 // If an allocation function declared with a non-throwing 9367 // exception-specification fails to allocate storage, it shall return 9368 // a null pointer. Any other allocation function that fails to allocate 9369 // storage shall indicate failure only by throwing an exception [...] 9370 if (FD) { 9371 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9372 if (Op == OO_New || Op == OO_Array_New) { 9373 const FunctionProtoType *Proto 9374 = FD->getType()->castAs<FunctionProtoType>(); 9375 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9376 CheckNonNullExpr(*this, RetValExp)) 9377 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9378 << FD << getLangOpts().CPlusPlus11; 9379 } 9380 } 9381 } 9382 9383 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9384 9385 /// Check for comparisons of floating point operands using != and ==. 9386 /// Issue a warning if these are no self-comparisons, as they are not likely 9387 /// to do what the programmer intended. 9388 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9389 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9390 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9391 9392 // Special case: check for x == x (which is OK). 9393 // Do not emit warnings for such cases. 9394 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9395 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9396 if (DRL->getDecl() == DRR->getDecl()) 9397 return; 9398 9399 // Special case: check for comparisons against literals that can be exactly 9400 // represented by APFloat. In such cases, do not emit a warning. This 9401 // is a heuristic: often comparison against such literals are used to 9402 // detect if a value in a variable has not changed. This clearly can 9403 // lead to false negatives. 9404 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9405 if (FLL->isExact()) 9406 return; 9407 } else 9408 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9409 if (FLR->isExact()) 9410 return; 9411 9412 // Check for comparisons with builtin types. 9413 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9414 if (CL->getBuiltinCallee()) 9415 return; 9416 9417 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9418 if (CR->getBuiltinCallee()) 9419 return; 9420 9421 // Emit the diagnostic. 9422 Diag(Loc, diag::warn_floatingpoint_eq) 9423 << LHS->getSourceRange() << RHS->getSourceRange(); 9424 } 9425 9426 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9427 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9428 9429 namespace { 9430 9431 /// Structure recording the 'active' range of an integer-valued 9432 /// expression. 9433 struct IntRange { 9434 /// The number of bits active in the int. 9435 unsigned Width; 9436 9437 /// True if the int is known not to have negative values. 9438 bool NonNegative; 9439 9440 IntRange(unsigned Width, bool NonNegative) 9441 : Width(Width), NonNegative(NonNegative) {} 9442 9443 /// Returns the range of the bool type. 9444 static IntRange forBoolType() { 9445 return IntRange(1, true); 9446 } 9447 9448 /// Returns the range of an opaque value of the given integral type. 9449 static IntRange forValueOfType(ASTContext &C, QualType T) { 9450 return forValueOfCanonicalType(C, 9451 T->getCanonicalTypeInternal().getTypePtr()); 9452 } 9453 9454 /// Returns the range of an opaque value of a canonical integral type. 9455 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9456 assert(T->isCanonicalUnqualified()); 9457 9458 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9459 T = VT->getElementType().getTypePtr(); 9460 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9461 T = CT->getElementType().getTypePtr(); 9462 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9463 T = AT->getValueType().getTypePtr(); 9464 9465 if (!C.getLangOpts().CPlusPlus) { 9466 // For enum types in C code, use the underlying datatype. 9467 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9468 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9469 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9470 // For enum types in C++, use the known bit width of the enumerators. 9471 EnumDecl *Enum = ET->getDecl(); 9472 // In C++11, enums can have a fixed underlying type. Use this type to 9473 // compute the range. 9474 if (Enum->isFixed()) { 9475 return IntRange(C.getIntWidth(QualType(T, 0)), 9476 !ET->isSignedIntegerOrEnumerationType()); 9477 } 9478 9479 unsigned NumPositive = Enum->getNumPositiveBits(); 9480 unsigned NumNegative = Enum->getNumNegativeBits(); 9481 9482 if (NumNegative == 0) 9483 return IntRange(NumPositive, true/*NonNegative*/); 9484 else 9485 return IntRange(std::max(NumPositive + 1, NumNegative), 9486 false/*NonNegative*/); 9487 } 9488 9489 const BuiltinType *BT = cast<BuiltinType>(T); 9490 assert(BT->isInteger()); 9491 9492 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9493 } 9494 9495 /// Returns the "target" range of a canonical integral type, i.e. 9496 /// the range of values expressible in the type. 9497 /// 9498 /// This matches forValueOfCanonicalType except that enums have the 9499 /// full range of their type, not the range of their enumerators. 9500 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9501 assert(T->isCanonicalUnqualified()); 9502 9503 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9504 T = VT->getElementType().getTypePtr(); 9505 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9506 T = CT->getElementType().getTypePtr(); 9507 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9508 T = AT->getValueType().getTypePtr(); 9509 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9510 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9511 9512 const BuiltinType *BT = cast<BuiltinType>(T); 9513 assert(BT->isInteger()); 9514 9515 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9516 } 9517 9518 /// Returns the supremum of two ranges: i.e. their conservative merge. 9519 static IntRange join(IntRange L, IntRange R) { 9520 return IntRange(std::max(L.Width, R.Width), 9521 L.NonNegative && R.NonNegative); 9522 } 9523 9524 /// Returns the infinum of two ranges: i.e. their aggressive merge. 9525 static IntRange meet(IntRange L, IntRange R) { 9526 return IntRange(std::min(L.Width, R.Width), 9527 L.NonNegative || R.NonNegative); 9528 } 9529 }; 9530 9531 } // namespace 9532 9533 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 9534 unsigned MaxWidth) { 9535 if (value.isSigned() && value.isNegative()) 9536 return IntRange(value.getMinSignedBits(), false); 9537 9538 if (value.getBitWidth() > MaxWidth) 9539 value = value.trunc(MaxWidth); 9540 9541 // isNonNegative() just checks the sign bit without considering 9542 // signedness. 9543 return IntRange(value.getActiveBits(), true); 9544 } 9545 9546 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 9547 unsigned MaxWidth) { 9548 if (result.isInt()) 9549 return GetValueRange(C, result.getInt(), MaxWidth); 9550 9551 if (result.isVector()) { 9552 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 9553 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 9554 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 9555 R = IntRange::join(R, El); 9556 } 9557 return R; 9558 } 9559 9560 if (result.isComplexInt()) { 9561 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 9562 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 9563 return IntRange::join(R, I); 9564 } 9565 9566 // This can happen with lossless casts to intptr_t of "based" lvalues. 9567 // Assume it might use arbitrary bits. 9568 // FIXME: The only reason we need to pass the type in here is to get 9569 // the sign right on this one case. It would be nice if APValue 9570 // preserved this. 9571 assert(result.isLValue() || result.isAddrLabelDiff()); 9572 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 9573 } 9574 9575 static QualType GetExprType(const Expr *E) { 9576 QualType Ty = E->getType(); 9577 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 9578 Ty = AtomicRHS->getValueType(); 9579 return Ty; 9580 } 9581 9582 /// Pseudo-evaluate the given integer expression, estimating the 9583 /// range of values it might take. 9584 /// 9585 /// \param MaxWidth - the width to which the value will be truncated 9586 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 9587 E = E->IgnoreParens(); 9588 9589 // Try a full evaluation first. 9590 Expr::EvalResult result; 9591 if (E->EvaluateAsRValue(result, C)) 9592 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 9593 9594 // I think we only want to look through implicit casts here; if the 9595 // user has an explicit widening cast, we should treat the value as 9596 // being of the new, wider type. 9597 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 9598 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 9599 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 9600 9601 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 9602 9603 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 9604 CE->getCastKind() == CK_BooleanToSignedIntegral; 9605 9606 // Assume that non-integer casts can span the full range of the type. 9607 if (!isIntegerCast) 9608 return OutputTypeRange; 9609 9610 IntRange SubRange 9611 = GetExprRange(C, CE->getSubExpr(), 9612 std::min(MaxWidth, OutputTypeRange.Width)); 9613 9614 // Bail out if the subexpr's range is as wide as the cast type. 9615 if (SubRange.Width >= OutputTypeRange.Width) 9616 return OutputTypeRange; 9617 9618 // Otherwise, we take the smaller width, and we're non-negative if 9619 // either the output type or the subexpr is. 9620 return IntRange(SubRange.Width, 9621 SubRange.NonNegative || OutputTypeRange.NonNegative); 9622 } 9623 9624 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9625 // If we can fold the condition, just take that operand. 9626 bool CondResult; 9627 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9628 return GetExprRange(C, CondResult ? CO->getTrueExpr() 9629 : CO->getFalseExpr(), 9630 MaxWidth); 9631 9632 // Otherwise, conservatively merge. 9633 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 9634 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 9635 return IntRange::join(L, R); 9636 } 9637 9638 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9639 switch (BO->getOpcode()) { 9640 case BO_Cmp: 9641 llvm_unreachable("builtin <=> should have class type"); 9642 9643 // Boolean-valued operations are single-bit and positive. 9644 case BO_LAnd: 9645 case BO_LOr: 9646 case BO_LT: 9647 case BO_GT: 9648 case BO_LE: 9649 case BO_GE: 9650 case BO_EQ: 9651 case BO_NE: 9652 return IntRange::forBoolType(); 9653 9654 // The type of the assignments is the type of the LHS, so the RHS 9655 // is not necessarily the same type. 9656 case BO_MulAssign: 9657 case BO_DivAssign: 9658 case BO_RemAssign: 9659 case BO_AddAssign: 9660 case BO_SubAssign: 9661 case BO_XorAssign: 9662 case BO_OrAssign: 9663 // TODO: bitfields? 9664 return IntRange::forValueOfType(C, GetExprType(E)); 9665 9666 // Simple assignments just pass through the RHS, which will have 9667 // been coerced to the LHS type. 9668 case BO_Assign: 9669 // TODO: bitfields? 9670 return GetExprRange(C, BO->getRHS(), MaxWidth); 9671 9672 // Operations with opaque sources are black-listed. 9673 case BO_PtrMemD: 9674 case BO_PtrMemI: 9675 return IntRange::forValueOfType(C, GetExprType(E)); 9676 9677 // Bitwise-and uses the *infinum* of the two source ranges. 9678 case BO_And: 9679 case BO_AndAssign: 9680 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 9681 GetExprRange(C, BO->getRHS(), MaxWidth)); 9682 9683 // Left shift gets black-listed based on a judgement call. 9684 case BO_Shl: 9685 // ...except that we want to treat '1 << (blah)' as logically 9686 // positive. It's an important idiom. 9687 if (IntegerLiteral *I 9688 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 9689 if (I->getValue() == 1) { 9690 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 9691 return IntRange(R.Width, /*NonNegative*/ true); 9692 } 9693 } 9694 LLVM_FALLTHROUGH; 9695 9696 case BO_ShlAssign: 9697 return IntRange::forValueOfType(C, GetExprType(E)); 9698 9699 // Right shift by a constant can narrow its left argument. 9700 case BO_Shr: 9701 case BO_ShrAssign: { 9702 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9703 9704 // If the shift amount is a positive constant, drop the width by 9705 // that much. 9706 llvm::APSInt shift; 9707 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 9708 shift.isNonNegative()) { 9709 unsigned zext = shift.getZExtValue(); 9710 if (zext >= L.Width) 9711 L.Width = (L.NonNegative ? 0 : 1); 9712 else 9713 L.Width -= zext; 9714 } 9715 9716 return L; 9717 } 9718 9719 // Comma acts as its right operand. 9720 case BO_Comma: 9721 return GetExprRange(C, BO->getRHS(), MaxWidth); 9722 9723 // Black-list pointer subtractions. 9724 case BO_Sub: 9725 if (BO->getLHS()->getType()->isPointerType()) 9726 return IntRange::forValueOfType(C, GetExprType(E)); 9727 break; 9728 9729 // The width of a division result is mostly determined by the size 9730 // of the LHS. 9731 case BO_Div: { 9732 // Don't 'pre-truncate' the operands. 9733 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9734 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9735 9736 // If the divisor is constant, use that. 9737 llvm::APSInt divisor; 9738 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 9739 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 9740 if (log2 >= L.Width) 9741 L.Width = (L.NonNegative ? 0 : 1); 9742 else 9743 L.Width = std::min(L.Width - log2, MaxWidth); 9744 return L; 9745 } 9746 9747 // Otherwise, just use the LHS's width. 9748 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9749 return IntRange(L.Width, L.NonNegative && R.NonNegative); 9750 } 9751 9752 // The result of a remainder can't be larger than the result of 9753 // either side. 9754 case BO_Rem: { 9755 // Don't 'pre-truncate' the operands. 9756 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9757 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9758 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9759 9760 IntRange meet = IntRange::meet(L, R); 9761 meet.Width = std::min(meet.Width, MaxWidth); 9762 return meet; 9763 } 9764 9765 // The default behavior is okay for these. 9766 case BO_Mul: 9767 case BO_Add: 9768 case BO_Xor: 9769 case BO_Or: 9770 break; 9771 } 9772 9773 // The default case is to treat the operation as if it were closed 9774 // on the narrowest type that encompasses both operands. 9775 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9776 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 9777 return IntRange::join(L, R); 9778 } 9779 9780 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 9781 switch (UO->getOpcode()) { 9782 // Boolean-valued operations are white-listed. 9783 case UO_LNot: 9784 return IntRange::forBoolType(); 9785 9786 // Operations with opaque sources are black-listed. 9787 case UO_Deref: 9788 case UO_AddrOf: // should be impossible 9789 return IntRange::forValueOfType(C, GetExprType(E)); 9790 9791 default: 9792 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 9793 } 9794 } 9795 9796 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 9797 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 9798 9799 if (const auto *BitField = E->getSourceBitField()) 9800 return IntRange(BitField->getBitWidthValue(C), 9801 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 9802 9803 return IntRange::forValueOfType(C, GetExprType(E)); 9804 } 9805 9806 static IntRange GetExprRange(ASTContext &C, const Expr *E) { 9807 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 9808 } 9809 9810 /// Checks whether the given value, which currently has the given 9811 /// source semantics, has the same value when coerced through the 9812 /// target semantics. 9813 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 9814 const llvm::fltSemantics &Src, 9815 const llvm::fltSemantics &Tgt) { 9816 llvm::APFloat truncated = value; 9817 9818 bool ignored; 9819 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 9820 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 9821 9822 return truncated.bitwiseIsEqual(value); 9823 } 9824 9825 /// Checks whether the given value, which currently has the given 9826 /// source semantics, has the same value when coerced through the 9827 /// target semantics. 9828 /// 9829 /// The value might be a vector of floats (or a complex number). 9830 static bool IsSameFloatAfterCast(const APValue &value, 9831 const llvm::fltSemantics &Src, 9832 const llvm::fltSemantics &Tgt) { 9833 if (value.isFloat()) 9834 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 9835 9836 if (value.isVector()) { 9837 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 9838 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 9839 return false; 9840 return true; 9841 } 9842 9843 assert(value.isComplexFloat()); 9844 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 9845 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 9846 } 9847 9848 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 9849 9850 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 9851 // Suppress cases where we are comparing against an enum constant. 9852 if (const DeclRefExpr *DR = 9853 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 9854 if (isa<EnumConstantDecl>(DR->getDecl())) 9855 return true; 9856 9857 // Suppress cases where the '0' value is expanded from a macro. 9858 if (E->getBeginLoc().isMacroID()) 9859 return true; 9860 9861 return false; 9862 } 9863 9864 static bool isKnownToHaveUnsignedValue(Expr *E) { 9865 return E->getType()->isIntegerType() && 9866 (!E->getType()->isSignedIntegerType() || 9867 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 9868 } 9869 9870 namespace { 9871 /// The promoted range of values of a type. In general this has the 9872 /// following structure: 9873 /// 9874 /// |-----------| . . . |-----------| 9875 /// ^ ^ ^ ^ 9876 /// Min HoleMin HoleMax Max 9877 /// 9878 /// ... where there is only a hole if a signed type is promoted to unsigned 9879 /// (in which case Min and Max are the smallest and largest representable 9880 /// values). 9881 struct PromotedRange { 9882 // Min, or HoleMax if there is a hole. 9883 llvm::APSInt PromotedMin; 9884 // Max, or HoleMin if there is a hole. 9885 llvm::APSInt PromotedMax; 9886 9887 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 9888 if (R.Width == 0) 9889 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 9890 else if (R.Width >= BitWidth && !Unsigned) { 9891 // Promotion made the type *narrower*. This happens when promoting 9892 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 9893 // Treat all values of 'signed int' as being in range for now. 9894 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 9895 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 9896 } else { 9897 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 9898 .extOrTrunc(BitWidth); 9899 PromotedMin.setIsUnsigned(Unsigned); 9900 9901 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 9902 .extOrTrunc(BitWidth); 9903 PromotedMax.setIsUnsigned(Unsigned); 9904 } 9905 } 9906 9907 // Determine whether this range is contiguous (has no hole). 9908 bool isContiguous() const { return PromotedMin <= PromotedMax; } 9909 9910 // Where a constant value is within the range. 9911 enum ComparisonResult { 9912 LT = 0x1, 9913 LE = 0x2, 9914 GT = 0x4, 9915 GE = 0x8, 9916 EQ = 0x10, 9917 NE = 0x20, 9918 InRangeFlag = 0x40, 9919 9920 Less = LE | LT | NE, 9921 Min = LE | InRangeFlag, 9922 InRange = InRangeFlag, 9923 Max = GE | InRangeFlag, 9924 Greater = GE | GT | NE, 9925 9926 OnlyValue = LE | GE | EQ | InRangeFlag, 9927 InHole = NE 9928 }; 9929 9930 ComparisonResult compare(const llvm::APSInt &Value) const { 9931 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 9932 Value.isUnsigned() == PromotedMin.isUnsigned()); 9933 if (!isContiguous()) { 9934 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 9935 if (Value.isMinValue()) return Min; 9936 if (Value.isMaxValue()) return Max; 9937 if (Value >= PromotedMin) return InRange; 9938 if (Value <= PromotedMax) return InRange; 9939 return InHole; 9940 } 9941 9942 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 9943 case -1: return Less; 9944 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 9945 case 1: 9946 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 9947 case -1: return InRange; 9948 case 0: return Max; 9949 case 1: return Greater; 9950 } 9951 } 9952 9953 llvm_unreachable("impossible compare result"); 9954 } 9955 9956 static llvm::Optional<StringRef> 9957 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 9958 if (Op == BO_Cmp) { 9959 ComparisonResult LTFlag = LT, GTFlag = GT; 9960 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 9961 9962 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 9963 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 9964 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 9965 return llvm::None; 9966 } 9967 9968 ComparisonResult TrueFlag, FalseFlag; 9969 if (Op == BO_EQ) { 9970 TrueFlag = EQ; 9971 FalseFlag = NE; 9972 } else if (Op == BO_NE) { 9973 TrueFlag = NE; 9974 FalseFlag = EQ; 9975 } else { 9976 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 9977 TrueFlag = LT; 9978 FalseFlag = GE; 9979 } else { 9980 TrueFlag = GT; 9981 FalseFlag = LE; 9982 } 9983 if (Op == BO_GE || Op == BO_LE) 9984 std::swap(TrueFlag, FalseFlag); 9985 } 9986 if (R & TrueFlag) 9987 return StringRef("true"); 9988 if (R & FalseFlag) 9989 return StringRef("false"); 9990 return llvm::None; 9991 } 9992 }; 9993 } 9994 9995 static bool HasEnumType(Expr *E) { 9996 // Strip off implicit integral promotions. 9997 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9998 if (ICE->getCastKind() != CK_IntegralCast && 9999 ICE->getCastKind() != CK_NoOp) 10000 break; 10001 E = ICE->getSubExpr(); 10002 } 10003 10004 return E->getType()->isEnumeralType(); 10005 } 10006 10007 static int classifyConstantValue(Expr *Constant) { 10008 // The values of this enumeration are used in the diagnostics 10009 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10010 enum ConstantValueKind { 10011 Miscellaneous = 0, 10012 LiteralTrue, 10013 LiteralFalse 10014 }; 10015 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10016 return BL->getValue() ? ConstantValueKind::LiteralTrue 10017 : ConstantValueKind::LiteralFalse; 10018 return ConstantValueKind::Miscellaneous; 10019 } 10020 10021 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10022 Expr *Constant, Expr *Other, 10023 const llvm::APSInt &Value, 10024 bool RhsConstant) { 10025 if (S.inTemplateInstantiation()) 10026 return false; 10027 10028 Expr *OriginalOther = Other; 10029 10030 Constant = Constant->IgnoreParenImpCasts(); 10031 Other = Other->IgnoreParenImpCasts(); 10032 10033 // Suppress warnings on tautological comparisons between values of the same 10034 // enumeration type. There are only two ways we could warn on this: 10035 // - If the constant is outside the range of representable values of 10036 // the enumeration. In such a case, we should warn about the cast 10037 // to enumeration type, not about the comparison. 10038 // - If the constant is the maximum / minimum in-range value. For an 10039 // enumeratin type, such comparisons can be meaningful and useful. 10040 if (Constant->getType()->isEnumeralType() && 10041 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10042 return false; 10043 10044 // TODO: Investigate using GetExprRange() to get tighter bounds 10045 // on the bit ranges. 10046 QualType OtherT = Other->getType(); 10047 if (const auto *AT = OtherT->getAs<AtomicType>()) 10048 OtherT = AT->getValueType(); 10049 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10050 10051 // Whether we're treating Other as being a bool because of the form of 10052 // expression despite it having another type (typically 'int' in C). 10053 bool OtherIsBooleanDespiteType = 10054 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10055 if (OtherIsBooleanDespiteType) 10056 OtherRange = IntRange::forBoolType(); 10057 10058 // Determine the promoted range of the other type and see if a comparison of 10059 // the constant against that range is tautological. 10060 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10061 Value.isUnsigned()); 10062 auto Cmp = OtherPromotedRange.compare(Value); 10063 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10064 if (!Result) 10065 return false; 10066 10067 // Suppress the diagnostic for an in-range comparison if the constant comes 10068 // from a macro or enumerator. We don't want to diagnose 10069 // 10070 // some_long_value <= INT_MAX 10071 // 10072 // when sizeof(int) == sizeof(long). 10073 bool InRange = Cmp & PromotedRange::InRangeFlag; 10074 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10075 return false; 10076 10077 // If this is a comparison to an enum constant, include that 10078 // constant in the diagnostic. 10079 const EnumConstantDecl *ED = nullptr; 10080 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10081 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10082 10083 // Should be enough for uint128 (39 decimal digits) 10084 SmallString<64> PrettySourceValue; 10085 llvm::raw_svector_ostream OS(PrettySourceValue); 10086 if (ED) 10087 OS << '\'' << *ED << "' (" << Value << ")"; 10088 else 10089 OS << Value; 10090 10091 // FIXME: We use a somewhat different formatting for the in-range cases and 10092 // cases involving boolean values for historical reasons. We should pick a 10093 // consistent way of presenting these diagnostics. 10094 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10095 S.DiagRuntimeBehavior( 10096 E->getOperatorLoc(), E, 10097 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10098 : diag::warn_tautological_bool_compare) 10099 << OS.str() << classifyConstantValue(Constant) 10100 << OtherT << OtherIsBooleanDespiteType << *Result 10101 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10102 } else { 10103 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10104 ? (HasEnumType(OriginalOther) 10105 ? diag::warn_unsigned_enum_always_true_comparison 10106 : diag::warn_unsigned_always_true_comparison) 10107 : diag::warn_tautological_constant_compare; 10108 10109 S.Diag(E->getOperatorLoc(), Diag) 10110 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10111 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10112 } 10113 10114 return true; 10115 } 10116 10117 /// Analyze the operands of the given comparison. Implements the 10118 /// fallback case from AnalyzeComparison. 10119 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10120 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10121 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10122 } 10123 10124 /// Implements -Wsign-compare. 10125 /// 10126 /// \param E the binary operator to check for warnings 10127 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10128 // The type the comparison is being performed in. 10129 QualType T = E->getLHS()->getType(); 10130 10131 // Only analyze comparison operators where both sides have been converted to 10132 // the same type. 10133 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10134 return AnalyzeImpConvsInComparison(S, E); 10135 10136 // Don't analyze value-dependent comparisons directly. 10137 if (E->isValueDependent()) 10138 return AnalyzeImpConvsInComparison(S, E); 10139 10140 Expr *LHS = E->getLHS(); 10141 Expr *RHS = E->getRHS(); 10142 10143 if (T->isIntegralType(S.Context)) { 10144 llvm::APSInt RHSValue; 10145 llvm::APSInt LHSValue; 10146 10147 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10148 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10149 10150 // We don't care about expressions whose result is a constant. 10151 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10152 return AnalyzeImpConvsInComparison(S, E); 10153 10154 // We only care about expressions where just one side is literal 10155 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10156 // Is the constant on the RHS or LHS? 10157 const bool RhsConstant = IsRHSIntegralLiteral; 10158 Expr *Const = RhsConstant ? RHS : LHS; 10159 Expr *Other = RhsConstant ? LHS : RHS; 10160 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10161 10162 // Check whether an integer constant comparison results in a value 10163 // of 'true' or 'false'. 10164 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10165 return AnalyzeImpConvsInComparison(S, E); 10166 } 10167 } 10168 10169 if (!T->hasUnsignedIntegerRepresentation()) { 10170 // We don't do anything special if this isn't an unsigned integral 10171 // comparison: we're only interested in integral comparisons, and 10172 // signed comparisons only happen in cases we don't care to warn about. 10173 return AnalyzeImpConvsInComparison(S, E); 10174 } 10175 10176 LHS = LHS->IgnoreParenImpCasts(); 10177 RHS = RHS->IgnoreParenImpCasts(); 10178 10179 if (!S.getLangOpts().CPlusPlus) { 10180 // Avoid warning about comparison of integers with different signs when 10181 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10182 // the type of `E`. 10183 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10184 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10185 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10186 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10187 } 10188 10189 // Check to see if one of the (unmodified) operands is of different 10190 // signedness. 10191 Expr *signedOperand, *unsignedOperand; 10192 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10193 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10194 "unsigned comparison between two signed integer expressions?"); 10195 signedOperand = LHS; 10196 unsignedOperand = RHS; 10197 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10198 signedOperand = RHS; 10199 unsignedOperand = LHS; 10200 } else { 10201 return AnalyzeImpConvsInComparison(S, E); 10202 } 10203 10204 // Otherwise, calculate the effective range of the signed operand. 10205 IntRange signedRange = GetExprRange(S.Context, signedOperand); 10206 10207 // Go ahead and analyze implicit conversions in the operands. Note 10208 // that we skip the implicit conversions on both sides. 10209 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10210 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10211 10212 // If the signed range is non-negative, -Wsign-compare won't fire. 10213 if (signedRange.NonNegative) 10214 return; 10215 10216 // For (in)equality comparisons, if the unsigned operand is a 10217 // constant which cannot collide with a overflowed signed operand, 10218 // then reinterpreting the signed operand as unsigned will not 10219 // change the result of the comparison. 10220 if (E->isEqualityOp()) { 10221 unsigned comparisonWidth = S.Context.getIntWidth(T); 10222 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 10223 10224 // We should never be unable to prove that the unsigned operand is 10225 // non-negative. 10226 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10227 10228 if (unsignedRange.Width < comparisonWidth) 10229 return; 10230 } 10231 10232 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10233 S.PDiag(diag::warn_mixed_sign_comparison) 10234 << LHS->getType() << RHS->getType() 10235 << LHS->getSourceRange() << RHS->getSourceRange()); 10236 } 10237 10238 /// Analyzes an attempt to assign the given value to a bitfield. 10239 /// 10240 /// Returns true if there was something fishy about the attempt. 10241 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10242 SourceLocation InitLoc) { 10243 assert(Bitfield->isBitField()); 10244 if (Bitfield->isInvalidDecl()) 10245 return false; 10246 10247 // White-list bool bitfields. 10248 QualType BitfieldType = Bitfield->getType(); 10249 if (BitfieldType->isBooleanType()) 10250 return false; 10251 10252 if (BitfieldType->isEnumeralType()) { 10253 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 10254 // If the underlying enum type was not explicitly specified as an unsigned 10255 // type and the enum contain only positive values, MSVC++ will cause an 10256 // inconsistency by storing this as a signed type. 10257 if (S.getLangOpts().CPlusPlus11 && 10258 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10259 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10260 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10261 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10262 << BitfieldEnumDecl->getNameAsString(); 10263 } 10264 } 10265 10266 if (Bitfield->getType()->isBooleanType()) 10267 return false; 10268 10269 // Ignore value- or type-dependent expressions. 10270 if (Bitfield->getBitWidth()->isValueDependent() || 10271 Bitfield->getBitWidth()->isTypeDependent() || 10272 Init->isValueDependent() || 10273 Init->isTypeDependent()) 10274 return false; 10275 10276 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10277 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10278 10279 Expr::EvalResult Result; 10280 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10281 Expr::SE_AllowSideEffects)) { 10282 // The RHS is not constant. If the RHS has an enum type, make sure the 10283 // bitfield is wide enough to hold all the values of the enum without 10284 // truncation. 10285 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10286 EnumDecl *ED = EnumTy->getDecl(); 10287 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10288 10289 // Enum types are implicitly signed on Windows, so check if there are any 10290 // negative enumerators to see if the enum was intended to be signed or 10291 // not. 10292 bool SignedEnum = ED->getNumNegativeBits() > 0; 10293 10294 // Check for surprising sign changes when assigning enum values to a 10295 // bitfield of different signedness. If the bitfield is signed and we 10296 // have exactly the right number of bits to store this unsigned enum, 10297 // suggest changing the enum to an unsigned type. This typically happens 10298 // on Windows where unfixed enums always use an underlying type of 'int'. 10299 unsigned DiagID = 0; 10300 if (SignedEnum && !SignedBitfield) { 10301 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10302 } else if (SignedBitfield && !SignedEnum && 10303 ED->getNumPositiveBits() == FieldWidth) { 10304 DiagID = diag::warn_signed_bitfield_enum_conversion; 10305 } 10306 10307 if (DiagID) { 10308 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10309 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10310 SourceRange TypeRange = 10311 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10312 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10313 << SignedEnum << TypeRange; 10314 } 10315 10316 // Compute the required bitwidth. If the enum has negative values, we need 10317 // one more bit than the normal number of positive bits to represent the 10318 // sign bit. 10319 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10320 ED->getNumNegativeBits()) 10321 : ED->getNumPositiveBits(); 10322 10323 // Check the bitwidth. 10324 if (BitsNeeded > FieldWidth) { 10325 Expr *WidthExpr = Bitfield->getBitWidth(); 10326 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10327 << Bitfield << ED; 10328 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10329 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10330 } 10331 } 10332 10333 return false; 10334 } 10335 10336 llvm::APSInt Value = Result.Val.getInt(); 10337 10338 unsigned OriginalWidth = Value.getBitWidth(); 10339 10340 if (!Value.isSigned() || Value.isNegative()) 10341 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10342 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10343 OriginalWidth = Value.getMinSignedBits(); 10344 10345 if (OriginalWidth <= FieldWidth) 10346 return false; 10347 10348 // Compute the value which the bitfield will contain. 10349 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10350 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10351 10352 // Check whether the stored value is equal to the original value. 10353 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10354 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10355 return false; 10356 10357 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10358 // therefore don't strictly fit into a signed bitfield of width 1. 10359 if (FieldWidth == 1 && Value == 1) 10360 return false; 10361 10362 std::string PrettyValue = Value.toString(10); 10363 std::string PrettyTrunc = TruncatedValue.toString(10); 10364 10365 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10366 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10367 << Init->getSourceRange(); 10368 10369 return true; 10370 } 10371 10372 /// Analyze the given simple or compound assignment for warning-worthy 10373 /// operations. 10374 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10375 // Just recurse on the LHS. 10376 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10377 10378 // We want to recurse on the RHS as normal unless we're assigning to 10379 // a bitfield. 10380 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10381 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10382 E->getOperatorLoc())) { 10383 // Recurse, ignoring any implicit conversions on the RHS. 10384 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10385 E->getOperatorLoc()); 10386 } 10387 } 10388 10389 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10390 10391 // Diagnose implicitly sequentially-consistent atomic assignment. 10392 if (E->getLHS()->getType()->isAtomicType()) 10393 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10394 } 10395 10396 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10397 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10398 SourceLocation CContext, unsigned diag, 10399 bool pruneControlFlow = false) { 10400 if (pruneControlFlow) { 10401 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10402 S.PDiag(diag) 10403 << SourceType << T << E->getSourceRange() 10404 << SourceRange(CContext)); 10405 return; 10406 } 10407 S.Diag(E->getExprLoc(), diag) 10408 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10409 } 10410 10411 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10412 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10413 SourceLocation CContext, 10414 unsigned diag, bool pruneControlFlow = false) { 10415 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10416 } 10417 10418 /// Diagnose an implicit cast from a floating point value to an integer value. 10419 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10420 SourceLocation CContext) { 10421 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10422 const bool PruneWarnings = S.inTemplateInstantiation(); 10423 10424 Expr *InnerE = E->IgnoreParenImpCasts(); 10425 // We also want to warn on, e.g., "int i = -1.234" 10426 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10427 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10428 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10429 10430 const bool IsLiteral = 10431 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10432 10433 llvm::APFloat Value(0.0); 10434 bool IsConstant = 10435 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10436 if (!IsConstant) { 10437 return DiagnoseImpCast(S, E, T, CContext, 10438 diag::warn_impcast_float_integer, PruneWarnings); 10439 } 10440 10441 bool isExact = false; 10442 10443 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10444 T->hasUnsignedIntegerRepresentation()); 10445 llvm::APFloat::opStatus Result = Value.convertToInteger( 10446 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10447 10448 if (Result == llvm::APFloat::opOK && isExact) { 10449 if (IsLiteral) return; 10450 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 10451 PruneWarnings); 10452 } 10453 10454 // Conversion of a floating-point value to a non-bool integer where the 10455 // integral part cannot be represented by the integer type is undefined. 10456 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 10457 return DiagnoseImpCast( 10458 S, E, T, CContext, 10459 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 10460 : diag::warn_impcast_float_to_integer_out_of_range, 10461 PruneWarnings); 10462 10463 unsigned DiagID = 0; 10464 if (IsLiteral) { 10465 // Warn on floating point literal to integer. 10466 DiagID = diag::warn_impcast_literal_float_to_integer; 10467 } else if (IntegerValue == 0) { 10468 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 10469 return DiagnoseImpCast(S, E, T, CContext, 10470 diag::warn_impcast_float_integer, PruneWarnings); 10471 } 10472 // Warn on non-zero to zero conversion. 10473 DiagID = diag::warn_impcast_float_to_integer_zero; 10474 } else { 10475 if (IntegerValue.isUnsigned()) { 10476 if (!IntegerValue.isMaxValue()) { 10477 return DiagnoseImpCast(S, E, T, CContext, 10478 diag::warn_impcast_float_integer, PruneWarnings); 10479 } 10480 } else { // IntegerValue.isSigned() 10481 if (!IntegerValue.isMaxSignedValue() && 10482 !IntegerValue.isMinSignedValue()) { 10483 return DiagnoseImpCast(S, E, T, CContext, 10484 diag::warn_impcast_float_integer, PruneWarnings); 10485 } 10486 } 10487 // Warn on evaluatable floating point expression to integer conversion. 10488 DiagID = diag::warn_impcast_float_to_integer; 10489 } 10490 10491 // FIXME: Force the precision of the source value down so we don't print 10492 // digits which are usually useless (we don't really care here if we 10493 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10494 // would automatically print the shortest representation, but it's a bit 10495 // tricky to implement. 10496 SmallString<16> PrettySourceValue; 10497 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10498 precision = (precision * 59 + 195) / 196; 10499 Value.toString(PrettySourceValue, precision); 10500 10501 SmallString<16> PrettyTargetValue; 10502 if (IsBool) 10503 PrettyTargetValue = Value.isZero() ? "false" : "true"; 10504 else 10505 IntegerValue.toString(PrettyTargetValue); 10506 10507 if (PruneWarnings) { 10508 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10509 S.PDiag(DiagID) 10510 << E->getType() << T.getUnqualifiedType() 10511 << PrettySourceValue << PrettyTargetValue 10512 << E->getSourceRange() << SourceRange(CContext)); 10513 } else { 10514 S.Diag(E->getExprLoc(), DiagID) 10515 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 10516 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 10517 } 10518 } 10519 10520 /// Analyze the given compound assignment for the possible losing of 10521 /// floating-point precision. 10522 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 10523 assert(isa<CompoundAssignOperator>(E) && 10524 "Must be compound assignment operation"); 10525 // Recurse on the LHS and RHS in here 10526 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10527 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10528 10529 if (E->getLHS()->getType()->isAtomicType()) 10530 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 10531 10532 // Now check the outermost expression 10533 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 10534 const auto *RBT = cast<CompoundAssignOperator>(E) 10535 ->getComputationResultType() 10536 ->getAs<BuiltinType>(); 10537 10538 // The below checks assume source is floating point. 10539 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 10540 10541 // If source is floating point but target is not. 10542 if (!ResultBT->isFloatingPoint()) 10543 return DiagnoseFloatingImpCast(S, E, E->getRHS()->getType(), 10544 E->getExprLoc()); 10545 10546 // If both source and target are floating points. 10547 // Builtin FP kinds are ordered by increasing FP rank. 10548 if (ResultBT->getKind() < RBT->getKind() && 10549 // We don't want to warn for system macro. 10550 !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 10551 // warn about dropping FP rank. 10552 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 10553 diag::warn_impcast_float_result_precision); 10554 } 10555 10556 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 10557 IntRange Range) { 10558 if (!Range.Width) return "0"; 10559 10560 llvm::APSInt ValueInRange = Value; 10561 ValueInRange.setIsSigned(!Range.NonNegative); 10562 ValueInRange = ValueInRange.trunc(Range.Width); 10563 return ValueInRange.toString(10); 10564 } 10565 10566 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 10567 if (!isa<ImplicitCastExpr>(Ex)) 10568 return false; 10569 10570 Expr *InnerE = Ex->IgnoreParenImpCasts(); 10571 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 10572 const Type *Source = 10573 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 10574 if (Target->isDependentType()) 10575 return false; 10576 10577 const BuiltinType *FloatCandidateBT = 10578 dyn_cast<BuiltinType>(ToBool ? Source : Target); 10579 const Type *BoolCandidateType = ToBool ? Target : Source; 10580 10581 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 10582 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 10583 } 10584 10585 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 10586 SourceLocation CC) { 10587 unsigned NumArgs = TheCall->getNumArgs(); 10588 for (unsigned i = 0; i < NumArgs; ++i) { 10589 Expr *CurrA = TheCall->getArg(i); 10590 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 10591 continue; 10592 10593 bool IsSwapped = ((i > 0) && 10594 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 10595 IsSwapped |= ((i < (NumArgs - 1)) && 10596 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 10597 if (IsSwapped) { 10598 // Warn on this floating-point to bool conversion. 10599 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 10600 CurrA->getType(), CC, 10601 diag::warn_impcast_floating_point_to_bool); 10602 } 10603 } 10604 } 10605 10606 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 10607 SourceLocation CC) { 10608 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 10609 E->getExprLoc())) 10610 return; 10611 10612 // Don't warn on functions which have return type nullptr_t. 10613 if (isa<CallExpr>(E)) 10614 return; 10615 10616 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 10617 const Expr::NullPointerConstantKind NullKind = 10618 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 10619 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 10620 return; 10621 10622 // Return if target type is a safe conversion. 10623 if (T->isAnyPointerType() || T->isBlockPointerType() || 10624 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 10625 return; 10626 10627 SourceLocation Loc = E->getSourceRange().getBegin(); 10628 10629 // Venture through the macro stacks to get to the source of macro arguments. 10630 // The new location is a better location than the complete location that was 10631 // passed in. 10632 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 10633 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 10634 10635 // __null is usually wrapped in a macro. Go up a macro if that is the case. 10636 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 10637 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 10638 Loc, S.SourceMgr, S.getLangOpts()); 10639 if (MacroName == "NULL") 10640 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 10641 } 10642 10643 // Only warn if the null and context location are in the same macro expansion. 10644 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 10645 return; 10646 10647 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 10648 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 10649 << FixItHint::CreateReplacement(Loc, 10650 S.getFixItZeroLiteralForType(T, Loc)); 10651 } 10652 10653 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10654 ObjCArrayLiteral *ArrayLiteral); 10655 10656 static void 10657 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10658 ObjCDictionaryLiteral *DictionaryLiteral); 10659 10660 /// Check a single element within a collection literal against the 10661 /// target element type. 10662 static void checkObjCCollectionLiteralElement(Sema &S, 10663 QualType TargetElementType, 10664 Expr *Element, 10665 unsigned ElementKind) { 10666 // Skip a bitcast to 'id' or qualified 'id'. 10667 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 10668 if (ICE->getCastKind() == CK_BitCast && 10669 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 10670 Element = ICE->getSubExpr(); 10671 } 10672 10673 QualType ElementType = Element->getType(); 10674 ExprResult ElementResult(Element); 10675 if (ElementType->getAs<ObjCObjectPointerType>() && 10676 S.CheckSingleAssignmentConstraints(TargetElementType, 10677 ElementResult, 10678 false, false) 10679 != Sema::Compatible) { 10680 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 10681 << ElementType << ElementKind << TargetElementType 10682 << Element->getSourceRange(); 10683 } 10684 10685 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 10686 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 10687 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 10688 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 10689 } 10690 10691 /// Check an Objective-C array literal being converted to the given 10692 /// target type. 10693 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10694 ObjCArrayLiteral *ArrayLiteral) { 10695 if (!S.NSArrayDecl) 10696 return; 10697 10698 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10699 if (!TargetObjCPtr) 10700 return; 10701 10702 if (TargetObjCPtr->isUnspecialized() || 10703 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10704 != S.NSArrayDecl->getCanonicalDecl()) 10705 return; 10706 10707 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10708 if (TypeArgs.size() != 1) 10709 return; 10710 10711 QualType TargetElementType = TypeArgs[0]; 10712 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 10713 checkObjCCollectionLiteralElement(S, TargetElementType, 10714 ArrayLiteral->getElement(I), 10715 0); 10716 } 10717 } 10718 10719 /// Check an Objective-C dictionary literal being converted to the given 10720 /// target type. 10721 static void 10722 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10723 ObjCDictionaryLiteral *DictionaryLiteral) { 10724 if (!S.NSDictionaryDecl) 10725 return; 10726 10727 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10728 if (!TargetObjCPtr) 10729 return; 10730 10731 if (TargetObjCPtr->isUnspecialized() || 10732 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10733 != S.NSDictionaryDecl->getCanonicalDecl()) 10734 return; 10735 10736 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10737 if (TypeArgs.size() != 2) 10738 return; 10739 10740 QualType TargetKeyType = TypeArgs[0]; 10741 QualType TargetObjectType = TypeArgs[1]; 10742 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 10743 auto Element = DictionaryLiteral->getKeyValueElement(I); 10744 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 10745 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 10746 } 10747 } 10748 10749 // Helper function to filter out cases for constant width constant conversion. 10750 // Don't warn on char array initialization or for non-decimal values. 10751 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 10752 SourceLocation CC) { 10753 // If initializing from a constant, and the constant starts with '0', 10754 // then it is a binary, octal, or hexadecimal. Allow these constants 10755 // to fill all the bits, even if there is a sign change. 10756 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 10757 const char FirstLiteralCharacter = 10758 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 10759 if (FirstLiteralCharacter == '0') 10760 return false; 10761 } 10762 10763 // If the CC location points to a '{', and the type is char, then assume 10764 // assume it is an array initialization. 10765 if (CC.isValid() && T->isCharType()) { 10766 const char FirstContextCharacter = 10767 S.getSourceManager().getCharacterData(CC)[0]; 10768 if (FirstContextCharacter == '{') 10769 return false; 10770 } 10771 10772 return true; 10773 } 10774 10775 static void 10776 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, 10777 bool *ICContext = nullptr) { 10778 if (E->isTypeDependent() || E->isValueDependent()) return; 10779 10780 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 10781 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 10782 if (Source == Target) return; 10783 if (Target->isDependentType()) return; 10784 10785 // If the conversion context location is invalid don't complain. We also 10786 // don't want to emit a warning if the issue occurs from the expansion of 10787 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 10788 // delay this check as long as possible. Once we detect we are in that 10789 // scenario, we just return. 10790 if (CC.isInvalid()) 10791 return; 10792 10793 if (Source->isAtomicType()) 10794 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 10795 10796 // Diagnose implicit casts to bool. 10797 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 10798 if (isa<StringLiteral>(E)) 10799 // Warn on string literal to bool. Checks for string literals in logical 10800 // and expressions, for instance, assert(0 && "error here"), are 10801 // prevented by a check in AnalyzeImplicitConversions(). 10802 return DiagnoseImpCast(S, E, T, CC, 10803 diag::warn_impcast_string_literal_to_bool); 10804 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 10805 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 10806 // This covers the literal expressions that evaluate to Objective-C 10807 // objects. 10808 return DiagnoseImpCast(S, E, T, CC, 10809 diag::warn_impcast_objective_c_literal_to_bool); 10810 } 10811 if (Source->isPointerType() || Source->canDecayToPointerType()) { 10812 // Warn on pointer to bool conversion that is always true. 10813 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 10814 SourceRange(CC)); 10815 } 10816 } 10817 10818 // Check implicit casts from Objective-C collection literals to specialized 10819 // collection types, e.g., NSArray<NSString *> *. 10820 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 10821 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 10822 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 10823 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 10824 10825 // Strip vector types. 10826 if (isa<VectorType>(Source)) { 10827 if (!isa<VectorType>(Target)) { 10828 if (S.SourceMgr.isInSystemMacro(CC)) 10829 return; 10830 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 10831 } 10832 10833 // If the vector cast is cast between two vectors of the same size, it is 10834 // a bitcast, not a conversion. 10835 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 10836 return; 10837 10838 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 10839 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 10840 } 10841 if (auto VecTy = dyn_cast<VectorType>(Target)) 10842 Target = VecTy->getElementType().getTypePtr(); 10843 10844 // Strip complex types. 10845 if (isa<ComplexType>(Source)) { 10846 if (!isa<ComplexType>(Target)) { 10847 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 10848 return; 10849 10850 return DiagnoseImpCast(S, E, T, CC, 10851 S.getLangOpts().CPlusPlus 10852 ? diag::err_impcast_complex_scalar 10853 : diag::warn_impcast_complex_scalar); 10854 } 10855 10856 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 10857 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 10858 } 10859 10860 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 10861 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 10862 10863 // If the source is floating point... 10864 if (SourceBT && SourceBT->isFloatingPoint()) { 10865 // ...and the target is floating point... 10866 if (TargetBT && TargetBT->isFloatingPoint()) { 10867 // ...then warn if we're dropping FP rank. 10868 10869 // Builtin FP kinds are ordered by increasing FP rank. 10870 if (SourceBT->getKind() > TargetBT->getKind()) { 10871 // Don't warn about float constants that are precisely 10872 // representable in the target type. 10873 Expr::EvalResult result; 10874 if (E->EvaluateAsRValue(result, S.Context)) { 10875 // Value might be a float, a float vector, or a float complex. 10876 if (IsSameFloatAfterCast(result.Val, 10877 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 10878 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 10879 return; 10880 } 10881 10882 if (S.SourceMgr.isInSystemMacro(CC)) 10883 return; 10884 10885 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 10886 } 10887 // ... or possibly if we're increasing rank, too 10888 else if (TargetBT->getKind() > SourceBT->getKind()) { 10889 if (S.SourceMgr.isInSystemMacro(CC)) 10890 return; 10891 10892 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 10893 } 10894 return; 10895 } 10896 10897 // If the target is integral, always warn. 10898 if (TargetBT && TargetBT->isInteger()) { 10899 if (S.SourceMgr.isInSystemMacro(CC)) 10900 return; 10901 10902 DiagnoseFloatingImpCast(S, E, T, CC); 10903 } 10904 10905 // Detect the case where a call result is converted from floating-point to 10906 // to bool, and the final argument to the call is converted from bool, to 10907 // discover this typo: 10908 // 10909 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 10910 // 10911 // FIXME: This is an incredibly special case; is there some more general 10912 // way to detect this class of misplaced-parentheses bug? 10913 if (Target->isBooleanType() && isa<CallExpr>(E)) { 10914 // Check last argument of function call to see if it is an 10915 // implicit cast from a type matching the type the result 10916 // is being cast to. 10917 CallExpr *CEx = cast<CallExpr>(E); 10918 if (unsigned NumArgs = CEx->getNumArgs()) { 10919 Expr *LastA = CEx->getArg(NumArgs - 1); 10920 Expr *InnerE = LastA->IgnoreParenImpCasts(); 10921 if (isa<ImplicitCastExpr>(LastA) && 10922 InnerE->getType()->isBooleanType()) { 10923 // Warn on this floating-point to bool conversion 10924 DiagnoseImpCast(S, E, T, CC, 10925 diag::warn_impcast_floating_point_to_bool); 10926 } 10927 } 10928 } 10929 return; 10930 } 10931 10932 DiagnoseNullConversion(S, E, T, CC); 10933 10934 S.DiscardMisalignedMemberAddress(Target, E); 10935 10936 if (!Source->isIntegerType() || !Target->isIntegerType()) 10937 return; 10938 10939 // TODO: remove this early return once the false positives for constant->bool 10940 // in templates, macros, etc, are reduced or removed. 10941 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 10942 return; 10943 10944 IntRange SourceRange = GetExprRange(S.Context, E); 10945 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 10946 10947 if (SourceRange.Width > TargetRange.Width) { 10948 // If the source is a constant, use a default-on diagnostic. 10949 // TODO: this should happen for bitfield stores, too. 10950 Expr::EvalResult Result; 10951 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 10952 llvm::APSInt Value(32); 10953 Value = Result.Val.getInt(); 10954 10955 if (S.SourceMgr.isInSystemMacro(CC)) 10956 return; 10957 10958 std::string PrettySourceValue = Value.toString(10); 10959 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10960 10961 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10962 S.PDiag(diag::warn_impcast_integer_precision_constant) 10963 << PrettySourceValue << PrettyTargetValue 10964 << E->getType() << T << E->getSourceRange() 10965 << clang::SourceRange(CC)); 10966 return; 10967 } 10968 10969 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 10970 if (S.SourceMgr.isInSystemMacro(CC)) 10971 return; 10972 10973 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 10974 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 10975 /* pruneControlFlow */ true); 10976 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 10977 } 10978 10979 if (TargetRange.Width > SourceRange.Width) { 10980 if (auto *UO = dyn_cast<UnaryOperator>(E)) 10981 if (UO->getOpcode() == UO_Minus) 10982 if (Source->isUnsignedIntegerType()) { 10983 if (Target->isUnsignedIntegerType()) 10984 return DiagnoseImpCast(S, E, T, CC, 10985 diag::warn_impcast_high_order_zero_bits); 10986 if (Target->isSignedIntegerType()) 10987 return DiagnoseImpCast(S, E, T, CC, 10988 diag::warn_impcast_nonnegative_result); 10989 } 10990 } 10991 10992 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 10993 SourceRange.NonNegative && Source->isSignedIntegerType()) { 10994 // Warn when doing a signed to signed conversion, warn if the positive 10995 // source value is exactly the width of the target type, which will 10996 // cause a negative value to be stored. 10997 10998 Expr::EvalResult Result; 10999 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11000 !S.SourceMgr.isInSystemMacro(CC)) { 11001 llvm::APSInt Value = Result.Val.getInt(); 11002 if (isSameWidthConstantConversion(S, E, T, CC)) { 11003 std::string PrettySourceValue = Value.toString(10); 11004 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11005 11006 S.DiagRuntimeBehavior( 11007 E->getExprLoc(), E, 11008 S.PDiag(diag::warn_impcast_integer_precision_constant) 11009 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11010 << E->getSourceRange() << clang::SourceRange(CC)); 11011 return; 11012 } 11013 } 11014 11015 // Fall through for non-constants to give a sign conversion warning. 11016 } 11017 11018 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11019 (!TargetRange.NonNegative && SourceRange.NonNegative && 11020 SourceRange.Width == TargetRange.Width)) { 11021 if (S.SourceMgr.isInSystemMacro(CC)) 11022 return; 11023 11024 unsigned DiagID = diag::warn_impcast_integer_sign; 11025 11026 // Traditionally, gcc has warned about this under -Wsign-compare. 11027 // We also want to warn about it in -Wconversion. 11028 // So if -Wconversion is off, use a completely identical diagnostic 11029 // in the sign-compare group. 11030 // The conditional-checking code will 11031 if (ICContext) { 11032 DiagID = diag::warn_impcast_integer_sign_conditional; 11033 *ICContext = true; 11034 } 11035 11036 return DiagnoseImpCast(S, E, T, CC, DiagID); 11037 } 11038 11039 // Diagnose conversions between different enumeration types. 11040 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11041 // type, to give us better diagnostics. 11042 QualType SourceType = E->getType(); 11043 if (!S.getLangOpts().CPlusPlus) { 11044 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11045 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11046 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11047 SourceType = S.Context.getTypeDeclType(Enum); 11048 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11049 } 11050 } 11051 11052 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11053 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11054 if (SourceEnum->getDecl()->hasNameForLinkage() && 11055 TargetEnum->getDecl()->hasNameForLinkage() && 11056 SourceEnum != TargetEnum) { 11057 if (S.SourceMgr.isInSystemMacro(CC)) 11058 return; 11059 11060 return DiagnoseImpCast(S, E, SourceType, T, CC, 11061 diag::warn_impcast_different_enum_types); 11062 } 11063 } 11064 11065 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11066 SourceLocation CC, QualType T); 11067 11068 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11069 SourceLocation CC, bool &ICContext) { 11070 E = E->IgnoreParenImpCasts(); 11071 11072 if (isa<ConditionalOperator>(E)) 11073 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11074 11075 AnalyzeImplicitConversions(S, E, CC); 11076 if (E->getType() != T) 11077 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11078 } 11079 11080 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11081 SourceLocation CC, QualType T) { 11082 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11083 11084 bool Suspicious = false; 11085 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11086 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11087 11088 // If -Wconversion would have warned about either of the candidates 11089 // for a signedness conversion to the context type... 11090 if (!Suspicious) return; 11091 11092 // ...but it's currently ignored... 11093 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11094 return; 11095 11096 // ...then check whether it would have warned about either of the 11097 // candidates for a signedness conversion to the condition type. 11098 if (E->getType() == T) return; 11099 11100 Suspicious = false; 11101 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11102 E->getType(), CC, &Suspicious); 11103 if (!Suspicious) 11104 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11105 E->getType(), CC, &Suspicious); 11106 } 11107 11108 /// Check conversion of given expression to boolean. 11109 /// Input argument E is a logical expression. 11110 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11111 if (S.getLangOpts().Bool) 11112 return; 11113 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11114 return; 11115 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11116 } 11117 11118 /// AnalyzeImplicitConversions - Find and report any interesting 11119 /// implicit conversions in the given expression. There are a couple 11120 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 11121 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, 11122 SourceLocation CC) { 11123 QualType T = OrigE->getType(); 11124 Expr *E = OrigE->IgnoreParenImpCasts(); 11125 11126 if (E->isTypeDependent() || E->isValueDependent()) 11127 return; 11128 11129 // For conditional operators, we analyze the arguments as if they 11130 // were being fed directly into the output. 11131 if (isa<ConditionalOperator>(E)) { 11132 ConditionalOperator *CO = cast<ConditionalOperator>(E); 11133 CheckConditionalOperator(S, CO, CC, T); 11134 return; 11135 } 11136 11137 // Check implicit argument conversions for function calls. 11138 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 11139 CheckImplicitArgumentConversions(S, Call, CC); 11140 11141 // Go ahead and check any implicit conversions we might have skipped. 11142 // The non-canonical typecheck is just an optimization; 11143 // CheckImplicitConversion will filter out dead implicit conversions. 11144 if (E->getType() != T) 11145 CheckImplicitConversion(S, E, T, CC); 11146 11147 // Now continue drilling into this expression. 11148 11149 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11150 // The bound subexpressions in a PseudoObjectExpr are not reachable 11151 // as transitive children. 11152 // FIXME: Use a more uniform representation for this. 11153 for (auto *SE : POE->semantics()) 11154 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11155 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 11156 } 11157 11158 // Skip past explicit casts. 11159 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11160 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11161 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11162 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11163 return AnalyzeImplicitConversions(S, E, CC); 11164 } 11165 11166 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11167 // Do a somewhat different check with comparison operators. 11168 if (BO->isComparisonOp()) 11169 return AnalyzeComparison(S, BO); 11170 11171 // And with simple assignments. 11172 if (BO->getOpcode() == BO_Assign) 11173 return AnalyzeAssignment(S, BO); 11174 // And with compound assignments. 11175 if (BO->isAssignmentOp()) 11176 return AnalyzeCompoundAssignment(S, BO); 11177 } 11178 11179 // These break the otherwise-useful invariant below. Fortunately, 11180 // we don't really need to recurse into them, because any internal 11181 // expressions should have been analyzed already when they were 11182 // built into statements. 11183 if (isa<StmtExpr>(E)) return; 11184 11185 // Don't descend into unevaluated contexts. 11186 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11187 11188 // Now just recurse over the expression's children. 11189 CC = E->getExprLoc(); 11190 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11191 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11192 for (Stmt *SubStmt : E->children()) { 11193 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11194 if (!ChildExpr) 11195 continue; 11196 11197 if (IsLogicalAndOperator && 11198 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11199 // Ignore checking string literals that are in logical and operators. 11200 // This is a common pattern for asserts. 11201 continue; 11202 AnalyzeImplicitConversions(S, ChildExpr, CC); 11203 } 11204 11205 if (BO && BO->isLogicalOp()) { 11206 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11207 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11208 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11209 11210 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11211 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11212 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11213 } 11214 11215 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 11216 if (U->getOpcode() == UO_LNot) { 11217 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11218 } else if (U->getOpcode() != UO_AddrOf) { 11219 if (U->getSubExpr()->getType()->isAtomicType()) 11220 S.Diag(U->getSubExpr()->getBeginLoc(), 11221 diag::warn_atomic_implicit_seq_cst); 11222 } 11223 } 11224 } 11225 11226 /// Diagnose integer type and any valid implicit conversion to it. 11227 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 11228 // Taking into account implicit conversions, 11229 // allow any integer. 11230 if (!E->getType()->isIntegerType()) { 11231 S.Diag(E->getBeginLoc(), 11232 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 11233 return true; 11234 } 11235 // Potentially emit standard warnings for implicit conversions if enabled 11236 // using -Wconversion. 11237 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 11238 return false; 11239 } 11240 11241 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 11242 // Returns true when emitting a warning about taking the address of a reference. 11243 static bool CheckForReference(Sema &SemaRef, const Expr *E, 11244 const PartialDiagnostic &PD) { 11245 E = E->IgnoreParenImpCasts(); 11246 11247 const FunctionDecl *FD = nullptr; 11248 11249 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11250 if (!DRE->getDecl()->getType()->isReferenceType()) 11251 return false; 11252 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11253 if (!M->getMemberDecl()->getType()->isReferenceType()) 11254 return false; 11255 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 11256 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 11257 return false; 11258 FD = Call->getDirectCallee(); 11259 } else { 11260 return false; 11261 } 11262 11263 SemaRef.Diag(E->getExprLoc(), PD); 11264 11265 // If possible, point to location of function. 11266 if (FD) { 11267 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 11268 } 11269 11270 return true; 11271 } 11272 11273 // Returns true if the SourceLocation is expanded from any macro body. 11274 // Returns false if the SourceLocation is invalid, is from not in a macro 11275 // expansion, or is from expanded from a top-level macro argument. 11276 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 11277 if (Loc.isInvalid()) 11278 return false; 11279 11280 while (Loc.isMacroID()) { 11281 if (SM.isMacroBodyExpansion(Loc)) 11282 return true; 11283 Loc = SM.getImmediateMacroCallerLoc(Loc); 11284 } 11285 11286 return false; 11287 } 11288 11289 /// Diagnose pointers that are always non-null. 11290 /// \param E the expression containing the pointer 11291 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 11292 /// compared to a null pointer 11293 /// \param IsEqual True when the comparison is equal to a null pointer 11294 /// \param Range Extra SourceRange to highlight in the diagnostic 11295 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 11296 Expr::NullPointerConstantKind NullKind, 11297 bool IsEqual, SourceRange Range) { 11298 if (!E) 11299 return; 11300 11301 // Don't warn inside macros. 11302 if (E->getExprLoc().isMacroID()) { 11303 const SourceManager &SM = getSourceManager(); 11304 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 11305 IsInAnyMacroBody(SM, Range.getBegin())) 11306 return; 11307 } 11308 E = E->IgnoreImpCasts(); 11309 11310 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 11311 11312 if (isa<CXXThisExpr>(E)) { 11313 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 11314 : diag::warn_this_bool_conversion; 11315 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 11316 return; 11317 } 11318 11319 bool IsAddressOf = false; 11320 11321 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11322 if (UO->getOpcode() != UO_AddrOf) 11323 return; 11324 IsAddressOf = true; 11325 E = UO->getSubExpr(); 11326 } 11327 11328 if (IsAddressOf) { 11329 unsigned DiagID = IsCompare 11330 ? diag::warn_address_of_reference_null_compare 11331 : diag::warn_address_of_reference_bool_conversion; 11332 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 11333 << IsEqual; 11334 if (CheckForReference(*this, E, PD)) { 11335 return; 11336 } 11337 } 11338 11339 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 11340 bool IsParam = isa<NonNullAttr>(NonnullAttr); 11341 std::string Str; 11342 llvm::raw_string_ostream S(Str); 11343 E->printPretty(S, nullptr, getPrintingPolicy()); 11344 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 11345 : diag::warn_cast_nonnull_to_bool; 11346 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 11347 << E->getSourceRange() << Range << IsEqual; 11348 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 11349 }; 11350 11351 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 11352 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 11353 if (auto *Callee = Call->getDirectCallee()) { 11354 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 11355 ComplainAboutNonnullParamOrCall(A); 11356 return; 11357 } 11358 } 11359 } 11360 11361 // Expect to find a single Decl. Skip anything more complicated. 11362 ValueDecl *D = nullptr; 11363 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 11364 D = R->getDecl(); 11365 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11366 D = M->getMemberDecl(); 11367 } 11368 11369 // Weak Decls can be null. 11370 if (!D || D->isWeak()) 11371 return; 11372 11373 // Check for parameter decl with nonnull attribute 11374 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 11375 if (getCurFunction() && 11376 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 11377 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 11378 ComplainAboutNonnullParamOrCall(A); 11379 return; 11380 } 11381 11382 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 11383 auto ParamIter = llvm::find(FD->parameters(), PV); 11384 assert(ParamIter != FD->param_end()); 11385 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 11386 11387 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 11388 if (!NonNull->args_size()) { 11389 ComplainAboutNonnullParamOrCall(NonNull); 11390 return; 11391 } 11392 11393 for (const ParamIdx &ArgNo : NonNull->args()) { 11394 if (ArgNo.getASTIndex() == ParamNo) { 11395 ComplainAboutNonnullParamOrCall(NonNull); 11396 return; 11397 } 11398 } 11399 } 11400 } 11401 } 11402 } 11403 11404 QualType T = D->getType(); 11405 const bool IsArray = T->isArrayType(); 11406 const bool IsFunction = T->isFunctionType(); 11407 11408 // Address of function is used to silence the function warning. 11409 if (IsAddressOf && IsFunction) { 11410 return; 11411 } 11412 11413 // Found nothing. 11414 if (!IsAddressOf && !IsFunction && !IsArray) 11415 return; 11416 11417 // Pretty print the expression for the diagnostic. 11418 std::string Str; 11419 llvm::raw_string_ostream S(Str); 11420 E->printPretty(S, nullptr, getPrintingPolicy()); 11421 11422 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 11423 : diag::warn_impcast_pointer_to_bool; 11424 enum { 11425 AddressOf, 11426 FunctionPointer, 11427 ArrayPointer 11428 } DiagType; 11429 if (IsAddressOf) 11430 DiagType = AddressOf; 11431 else if (IsFunction) 11432 DiagType = FunctionPointer; 11433 else if (IsArray) 11434 DiagType = ArrayPointer; 11435 else 11436 llvm_unreachable("Could not determine diagnostic."); 11437 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 11438 << Range << IsEqual; 11439 11440 if (!IsFunction) 11441 return; 11442 11443 // Suggest '&' to silence the function warning. 11444 Diag(E->getExprLoc(), diag::note_function_warning_silence) 11445 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 11446 11447 // Check to see if '()' fixit should be emitted. 11448 QualType ReturnType; 11449 UnresolvedSet<4> NonTemplateOverloads; 11450 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 11451 if (ReturnType.isNull()) 11452 return; 11453 11454 if (IsCompare) { 11455 // There are two cases here. If there is null constant, the only suggest 11456 // for a pointer return type. If the null is 0, then suggest if the return 11457 // type is a pointer or an integer type. 11458 if (!ReturnType->isPointerType()) { 11459 if (NullKind == Expr::NPCK_ZeroExpression || 11460 NullKind == Expr::NPCK_ZeroLiteral) { 11461 if (!ReturnType->isIntegerType()) 11462 return; 11463 } else { 11464 return; 11465 } 11466 } 11467 } else { // !IsCompare 11468 // For function to bool, only suggest if the function pointer has bool 11469 // return type. 11470 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 11471 return; 11472 } 11473 Diag(E->getExprLoc(), diag::note_function_to_function_call) 11474 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 11475 } 11476 11477 /// Diagnoses "dangerous" implicit conversions within the given 11478 /// expression (which is a full expression). Implements -Wconversion 11479 /// and -Wsign-compare. 11480 /// 11481 /// \param CC the "context" location of the implicit conversion, i.e. 11482 /// the most location of the syntactic entity requiring the implicit 11483 /// conversion 11484 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 11485 // Don't diagnose in unevaluated contexts. 11486 if (isUnevaluatedContext()) 11487 return; 11488 11489 // Don't diagnose for value- or type-dependent expressions. 11490 if (E->isTypeDependent() || E->isValueDependent()) 11491 return; 11492 11493 // Check for array bounds violations in cases where the check isn't triggered 11494 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 11495 // ArraySubscriptExpr is on the RHS of a variable initialization. 11496 CheckArrayAccess(E); 11497 11498 // This is not the right CC for (e.g.) a variable initialization. 11499 AnalyzeImplicitConversions(*this, E, CC); 11500 } 11501 11502 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 11503 /// Input argument E is a logical expression. 11504 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 11505 ::CheckBoolLikeConversion(*this, E, CC); 11506 } 11507 11508 /// Diagnose when expression is an integer constant expression and its evaluation 11509 /// results in integer overflow 11510 void Sema::CheckForIntOverflow (Expr *E) { 11511 // Use a work list to deal with nested struct initializers. 11512 SmallVector<Expr *, 2> Exprs(1, E); 11513 11514 do { 11515 Expr *OriginalE = Exprs.pop_back_val(); 11516 Expr *E = OriginalE->IgnoreParenCasts(); 11517 11518 if (isa<BinaryOperator>(E)) { 11519 E->EvaluateForOverflow(Context); 11520 continue; 11521 } 11522 11523 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 11524 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 11525 else if (isa<ObjCBoxedExpr>(OriginalE)) 11526 E->EvaluateForOverflow(Context); 11527 else if (auto Call = dyn_cast<CallExpr>(E)) 11528 Exprs.append(Call->arg_begin(), Call->arg_end()); 11529 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 11530 Exprs.append(Message->arg_begin(), Message->arg_end()); 11531 } while (!Exprs.empty()); 11532 } 11533 11534 namespace { 11535 11536 /// Visitor for expressions which looks for unsequenced operations on the 11537 /// same object. 11538 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 11539 using Base = EvaluatedExprVisitor<SequenceChecker>; 11540 11541 /// A tree of sequenced regions within an expression. Two regions are 11542 /// unsequenced if one is an ancestor or a descendent of the other. When we 11543 /// finish processing an expression with sequencing, such as a comma 11544 /// expression, we fold its tree nodes into its parent, since they are 11545 /// unsequenced with respect to nodes we will visit later. 11546 class SequenceTree { 11547 struct Value { 11548 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 11549 unsigned Parent : 31; 11550 unsigned Merged : 1; 11551 }; 11552 SmallVector<Value, 8> Values; 11553 11554 public: 11555 /// A region within an expression which may be sequenced with respect 11556 /// to some other region. 11557 class Seq { 11558 friend class SequenceTree; 11559 11560 unsigned Index = 0; 11561 11562 explicit Seq(unsigned N) : Index(N) {} 11563 11564 public: 11565 Seq() = default; 11566 }; 11567 11568 SequenceTree() { Values.push_back(Value(0)); } 11569 Seq root() const { return Seq(0); } 11570 11571 /// Create a new sequence of operations, which is an unsequenced 11572 /// subset of \p Parent. This sequence of operations is sequenced with 11573 /// respect to other children of \p Parent. 11574 Seq allocate(Seq Parent) { 11575 Values.push_back(Value(Parent.Index)); 11576 return Seq(Values.size() - 1); 11577 } 11578 11579 /// Merge a sequence of operations into its parent. 11580 void merge(Seq S) { 11581 Values[S.Index].Merged = true; 11582 } 11583 11584 /// Determine whether two operations are unsequenced. This operation 11585 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 11586 /// should have been merged into its parent as appropriate. 11587 bool isUnsequenced(Seq Cur, Seq Old) { 11588 unsigned C = representative(Cur.Index); 11589 unsigned Target = representative(Old.Index); 11590 while (C >= Target) { 11591 if (C == Target) 11592 return true; 11593 C = Values[C].Parent; 11594 } 11595 return false; 11596 } 11597 11598 private: 11599 /// Pick a representative for a sequence. 11600 unsigned representative(unsigned K) { 11601 if (Values[K].Merged) 11602 // Perform path compression as we go. 11603 return Values[K].Parent = representative(Values[K].Parent); 11604 return K; 11605 } 11606 }; 11607 11608 /// An object for which we can track unsequenced uses. 11609 using Object = NamedDecl *; 11610 11611 /// Different flavors of object usage which we track. We only track the 11612 /// least-sequenced usage of each kind. 11613 enum UsageKind { 11614 /// A read of an object. Multiple unsequenced reads are OK. 11615 UK_Use, 11616 11617 /// A modification of an object which is sequenced before the value 11618 /// computation of the expression, such as ++n in C++. 11619 UK_ModAsValue, 11620 11621 /// A modification of an object which is not sequenced before the value 11622 /// computation of the expression, such as n++. 11623 UK_ModAsSideEffect, 11624 11625 UK_Count = UK_ModAsSideEffect + 1 11626 }; 11627 11628 struct Usage { 11629 Expr *Use = nullptr; 11630 SequenceTree::Seq Seq; 11631 11632 Usage() = default; 11633 }; 11634 11635 struct UsageInfo { 11636 Usage Uses[UK_Count]; 11637 11638 /// Have we issued a diagnostic for this variable already? 11639 bool Diagnosed = false; 11640 11641 UsageInfo() = default; 11642 }; 11643 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 11644 11645 Sema &SemaRef; 11646 11647 /// Sequenced regions within the expression. 11648 SequenceTree Tree; 11649 11650 /// Declaration modifications and references which we have seen. 11651 UsageInfoMap UsageMap; 11652 11653 /// The region we are currently within. 11654 SequenceTree::Seq Region; 11655 11656 /// Filled in with declarations which were modified as a side-effect 11657 /// (that is, post-increment operations). 11658 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 11659 11660 /// Expressions to check later. We defer checking these to reduce 11661 /// stack usage. 11662 SmallVectorImpl<Expr *> &WorkList; 11663 11664 /// RAII object wrapping the visitation of a sequenced subexpression of an 11665 /// expression. At the end of this process, the side-effects of the evaluation 11666 /// become sequenced with respect to the value computation of the result, so 11667 /// we downgrade any UK_ModAsSideEffect within the evaluation to 11668 /// UK_ModAsValue. 11669 struct SequencedSubexpression { 11670 SequencedSubexpression(SequenceChecker &Self) 11671 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 11672 Self.ModAsSideEffect = &ModAsSideEffect; 11673 } 11674 11675 ~SequencedSubexpression() { 11676 for (auto &M : llvm::reverse(ModAsSideEffect)) { 11677 UsageInfo &U = Self.UsageMap[M.first]; 11678 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 11679 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 11680 SideEffectUsage = M.second; 11681 } 11682 Self.ModAsSideEffect = OldModAsSideEffect; 11683 } 11684 11685 SequenceChecker &Self; 11686 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 11687 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 11688 }; 11689 11690 /// RAII object wrapping the visitation of a subexpression which we might 11691 /// choose to evaluate as a constant. If any subexpression is evaluated and 11692 /// found to be non-constant, this allows us to suppress the evaluation of 11693 /// the outer expression. 11694 class EvaluationTracker { 11695 public: 11696 EvaluationTracker(SequenceChecker &Self) 11697 : Self(Self), Prev(Self.EvalTracker) { 11698 Self.EvalTracker = this; 11699 } 11700 11701 ~EvaluationTracker() { 11702 Self.EvalTracker = Prev; 11703 if (Prev) 11704 Prev->EvalOK &= EvalOK; 11705 } 11706 11707 bool evaluate(const Expr *E, bool &Result) { 11708 if (!EvalOK || E->isValueDependent()) 11709 return false; 11710 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 11711 return EvalOK; 11712 } 11713 11714 private: 11715 SequenceChecker &Self; 11716 EvaluationTracker *Prev; 11717 bool EvalOK = true; 11718 } *EvalTracker = nullptr; 11719 11720 /// Find the object which is produced by the specified expression, 11721 /// if any. 11722 Object getObject(Expr *E, bool Mod) const { 11723 E = E->IgnoreParenCasts(); 11724 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11725 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 11726 return getObject(UO->getSubExpr(), Mod); 11727 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11728 if (BO->getOpcode() == BO_Comma) 11729 return getObject(BO->getRHS(), Mod); 11730 if (Mod && BO->isAssignmentOp()) 11731 return getObject(BO->getLHS(), Mod); 11732 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11733 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 11734 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 11735 return ME->getMemberDecl(); 11736 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11737 // FIXME: If this is a reference, map through to its value. 11738 return DRE->getDecl(); 11739 return nullptr; 11740 } 11741 11742 /// Note that an object was modified or used by an expression. 11743 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 11744 Usage &U = UI.Uses[UK]; 11745 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 11746 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 11747 ModAsSideEffect->push_back(std::make_pair(O, U)); 11748 U.Use = Ref; 11749 U.Seq = Region; 11750 } 11751 } 11752 11753 /// Check whether a modification or use conflicts with a prior usage. 11754 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 11755 bool IsModMod) { 11756 if (UI.Diagnosed) 11757 return; 11758 11759 const Usage &U = UI.Uses[OtherKind]; 11760 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 11761 return; 11762 11763 Expr *Mod = U.Use; 11764 Expr *ModOrUse = Ref; 11765 if (OtherKind == UK_Use) 11766 std::swap(Mod, ModOrUse); 11767 11768 SemaRef.Diag(Mod->getExprLoc(), 11769 IsModMod ? diag::warn_unsequenced_mod_mod 11770 : diag::warn_unsequenced_mod_use) 11771 << O << SourceRange(ModOrUse->getExprLoc()); 11772 UI.Diagnosed = true; 11773 } 11774 11775 void notePreUse(Object O, Expr *Use) { 11776 UsageInfo &U = UsageMap[O]; 11777 // Uses conflict with other modifications. 11778 checkUsage(O, U, Use, UK_ModAsValue, false); 11779 } 11780 11781 void notePostUse(Object O, Expr *Use) { 11782 UsageInfo &U = UsageMap[O]; 11783 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 11784 addUsage(U, O, Use, UK_Use); 11785 } 11786 11787 void notePreMod(Object O, Expr *Mod) { 11788 UsageInfo &U = UsageMap[O]; 11789 // Modifications conflict with other modifications and with uses. 11790 checkUsage(O, U, Mod, UK_ModAsValue, true); 11791 checkUsage(O, U, Mod, UK_Use, false); 11792 } 11793 11794 void notePostMod(Object O, Expr *Use, UsageKind UK) { 11795 UsageInfo &U = UsageMap[O]; 11796 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 11797 addUsage(U, O, Use, UK); 11798 } 11799 11800 public: 11801 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 11802 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 11803 Visit(E); 11804 } 11805 11806 void VisitStmt(Stmt *S) { 11807 // Skip all statements which aren't expressions for now. 11808 } 11809 11810 void VisitExpr(Expr *E) { 11811 // By default, just recurse to evaluated subexpressions. 11812 Base::VisitStmt(E); 11813 } 11814 11815 void VisitCastExpr(CastExpr *E) { 11816 Object O = Object(); 11817 if (E->getCastKind() == CK_LValueToRValue) 11818 O = getObject(E->getSubExpr(), false); 11819 11820 if (O) 11821 notePreUse(O, E); 11822 VisitExpr(E); 11823 if (O) 11824 notePostUse(O, E); 11825 } 11826 11827 void VisitBinComma(BinaryOperator *BO) { 11828 // C++11 [expr.comma]p1: 11829 // Every value computation and side effect associated with the left 11830 // expression is sequenced before every value computation and side 11831 // effect associated with the right expression. 11832 SequenceTree::Seq LHS = Tree.allocate(Region); 11833 SequenceTree::Seq RHS = Tree.allocate(Region); 11834 SequenceTree::Seq OldRegion = Region; 11835 11836 { 11837 SequencedSubexpression SeqLHS(*this); 11838 Region = LHS; 11839 Visit(BO->getLHS()); 11840 } 11841 11842 Region = RHS; 11843 Visit(BO->getRHS()); 11844 11845 Region = OldRegion; 11846 11847 // Forget that LHS and RHS are sequenced. They are both unsequenced 11848 // with respect to other stuff. 11849 Tree.merge(LHS); 11850 Tree.merge(RHS); 11851 } 11852 11853 void VisitBinAssign(BinaryOperator *BO) { 11854 // The modification is sequenced after the value computation of the LHS 11855 // and RHS, so check it before inspecting the operands and update the 11856 // map afterwards. 11857 Object O = getObject(BO->getLHS(), true); 11858 if (!O) 11859 return VisitExpr(BO); 11860 11861 notePreMod(O, BO); 11862 11863 // C++11 [expr.ass]p7: 11864 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 11865 // only once. 11866 // 11867 // Therefore, for a compound assignment operator, O is considered used 11868 // everywhere except within the evaluation of E1 itself. 11869 if (isa<CompoundAssignOperator>(BO)) 11870 notePreUse(O, BO); 11871 11872 Visit(BO->getLHS()); 11873 11874 if (isa<CompoundAssignOperator>(BO)) 11875 notePostUse(O, BO); 11876 11877 Visit(BO->getRHS()); 11878 11879 // C++11 [expr.ass]p1: 11880 // the assignment is sequenced [...] before the value computation of the 11881 // assignment expression. 11882 // C11 6.5.16/3 has no such rule. 11883 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11884 : UK_ModAsSideEffect); 11885 } 11886 11887 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 11888 VisitBinAssign(CAO); 11889 } 11890 11891 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11892 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11893 void VisitUnaryPreIncDec(UnaryOperator *UO) { 11894 Object O = getObject(UO->getSubExpr(), true); 11895 if (!O) 11896 return VisitExpr(UO); 11897 11898 notePreMod(O, UO); 11899 Visit(UO->getSubExpr()); 11900 // C++11 [expr.pre.incr]p1: 11901 // the expression ++x is equivalent to x+=1 11902 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11903 : UK_ModAsSideEffect); 11904 } 11905 11906 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11907 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11908 void VisitUnaryPostIncDec(UnaryOperator *UO) { 11909 Object O = getObject(UO->getSubExpr(), true); 11910 if (!O) 11911 return VisitExpr(UO); 11912 11913 notePreMod(O, UO); 11914 Visit(UO->getSubExpr()); 11915 notePostMod(O, UO, UK_ModAsSideEffect); 11916 } 11917 11918 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 11919 void VisitBinLOr(BinaryOperator *BO) { 11920 // The side-effects of the LHS of an '&&' are sequenced before the 11921 // value computation of the RHS, and hence before the value computation 11922 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 11923 // as if they were unconditionally sequenced. 11924 EvaluationTracker Eval(*this); 11925 { 11926 SequencedSubexpression Sequenced(*this); 11927 Visit(BO->getLHS()); 11928 } 11929 11930 bool Result; 11931 if (Eval.evaluate(BO->getLHS(), Result)) { 11932 if (!Result) 11933 Visit(BO->getRHS()); 11934 } else { 11935 // Check for unsequenced operations in the RHS, treating it as an 11936 // entirely separate evaluation. 11937 // 11938 // FIXME: If there are operations in the RHS which are unsequenced 11939 // with respect to operations outside the RHS, and those operations 11940 // are unconditionally evaluated, diagnose them. 11941 WorkList.push_back(BO->getRHS()); 11942 } 11943 } 11944 void VisitBinLAnd(BinaryOperator *BO) { 11945 EvaluationTracker Eval(*this); 11946 { 11947 SequencedSubexpression Sequenced(*this); 11948 Visit(BO->getLHS()); 11949 } 11950 11951 bool Result; 11952 if (Eval.evaluate(BO->getLHS(), Result)) { 11953 if (Result) 11954 Visit(BO->getRHS()); 11955 } else { 11956 WorkList.push_back(BO->getRHS()); 11957 } 11958 } 11959 11960 // Only visit the condition, unless we can be sure which subexpression will 11961 // be chosen. 11962 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 11963 EvaluationTracker Eval(*this); 11964 { 11965 SequencedSubexpression Sequenced(*this); 11966 Visit(CO->getCond()); 11967 } 11968 11969 bool Result; 11970 if (Eval.evaluate(CO->getCond(), Result)) 11971 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 11972 else { 11973 WorkList.push_back(CO->getTrueExpr()); 11974 WorkList.push_back(CO->getFalseExpr()); 11975 } 11976 } 11977 11978 void VisitCallExpr(CallExpr *CE) { 11979 // C++11 [intro.execution]p15: 11980 // When calling a function [...], every value computation and side effect 11981 // associated with any argument expression, or with the postfix expression 11982 // designating the called function, is sequenced before execution of every 11983 // expression or statement in the body of the function [and thus before 11984 // the value computation of its result]. 11985 SequencedSubexpression Sequenced(*this); 11986 Base::VisitCallExpr(CE); 11987 11988 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 11989 } 11990 11991 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 11992 // This is a call, so all subexpressions are sequenced before the result. 11993 SequencedSubexpression Sequenced(*this); 11994 11995 if (!CCE->isListInitialization()) 11996 return VisitExpr(CCE); 11997 11998 // In C++11, list initializations are sequenced. 11999 SmallVector<SequenceTree::Seq, 32> Elts; 12000 SequenceTree::Seq Parent = Region; 12001 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 12002 E = CCE->arg_end(); 12003 I != E; ++I) { 12004 Region = Tree.allocate(Parent); 12005 Elts.push_back(Region); 12006 Visit(*I); 12007 } 12008 12009 // Forget that the initializers are sequenced. 12010 Region = Parent; 12011 for (unsigned I = 0; I < Elts.size(); ++I) 12012 Tree.merge(Elts[I]); 12013 } 12014 12015 void VisitInitListExpr(InitListExpr *ILE) { 12016 if (!SemaRef.getLangOpts().CPlusPlus11) 12017 return VisitExpr(ILE); 12018 12019 // In C++11, list initializations are sequenced. 12020 SmallVector<SequenceTree::Seq, 32> Elts; 12021 SequenceTree::Seq Parent = Region; 12022 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 12023 Expr *E = ILE->getInit(I); 12024 if (!E) continue; 12025 Region = Tree.allocate(Parent); 12026 Elts.push_back(Region); 12027 Visit(E); 12028 } 12029 12030 // Forget that the initializers are sequenced. 12031 Region = Parent; 12032 for (unsigned I = 0; I < Elts.size(); ++I) 12033 Tree.merge(Elts[I]); 12034 } 12035 }; 12036 12037 } // namespace 12038 12039 void Sema::CheckUnsequencedOperations(Expr *E) { 12040 SmallVector<Expr *, 8> WorkList; 12041 WorkList.push_back(E); 12042 while (!WorkList.empty()) { 12043 Expr *Item = WorkList.pop_back_val(); 12044 SequenceChecker(*this, Item, WorkList); 12045 } 12046 } 12047 12048 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 12049 bool IsConstexpr) { 12050 CheckImplicitConversions(E, CheckLoc); 12051 if (!E->isInstantiationDependent()) 12052 CheckUnsequencedOperations(E); 12053 if (!IsConstexpr && !E->isValueDependent()) 12054 CheckForIntOverflow(E); 12055 DiagnoseMisalignedMembers(); 12056 } 12057 12058 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 12059 FieldDecl *BitField, 12060 Expr *Init) { 12061 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 12062 } 12063 12064 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 12065 SourceLocation Loc) { 12066 if (!PType->isVariablyModifiedType()) 12067 return; 12068 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 12069 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 12070 return; 12071 } 12072 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 12073 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 12074 return; 12075 } 12076 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 12077 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 12078 return; 12079 } 12080 12081 const ArrayType *AT = S.Context.getAsArrayType(PType); 12082 if (!AT) 12083 return; 12084 12085 if (AT->getSizeModifier() != ArrayType::Star) { 12086 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 12087 return; 12088 } 12089 12090 S.Diag(Loc, diag::err_array_star_in_function_definition); 12091 } 12092 12093 /// CheckParmsForFunctionDef - Check that the parameters of the given 12094 /// function are appropriate for the definition of a function. This 12095 /// takes care of any checks that cannot be performed on the 12096 /// declaration itself, e.g., that the types of each of the function 12097 /// parameters are complete. 12098 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 12099 bool CheckParameterNames) { 12100 bool HasInvalidParm = false; 12101 for (ParmVarDecl *Param : Parameters) { 12102 // C99 6.7.5.3p4: the parameters in a parameter type list in a 12103 // function declarator that is part of a function definition of 12104 // that function shall not have incomplete type. 12105 // 12106 // This is also C++ [dcl.fct]p6. 12107 if (!Param->isInvalidDecl() && 12108 RequireCompleteType(Param->getLocation(), Param->getType(), 12109 diag::err_typecheck_decl_incomplete_type)) { 12110 Param->setInvalidDecl(); 12111 HasInvalidParm = true; 12112 } 12113 12114 // C99 6.9.1p5: If the declarator includes a parameter type list, the 12115 // declaration of each parameter shall include an identifier. 12116 if (CheckParameterNames && 12117 Param->getIdentifier() == nullptr && 12118 !Param->isImplicit() && 12119 !getLangOpts().CPlusPlus) 12120 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12121 12122 // C99 6.7.5.3p12: 12123 // If the function declarator is not part of a definition of that 12124 // function, parameters may have incomplete type and may use the [*] 12125 // notation in their sequences of declarator specifiers to specify 12126 // variable length array types. 12127 QualType PType = Param->getOriginalType(); 12128 // FIXME: This diagnostic should point the '[*]' if source-location 12129 // information is added for it. 12130 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 12131 12132 // If the parameter is a c++ class type and it has to be destructed in the 12133 // callee function, declare the destructor so that it can be called by the 12134 // callee function. Do not perform any direct access check on the dtor here. 12135 if (!Param->isInvalidDecl()) { 12136 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 12137 if (!ClassDecl->isInvalidDecl() && 12138 !ClassDecl->hasIrrelevantDestructor() && 12139 !ClassDecl->isDependentContext() && 12140 ClassDecl->isParamDestroyedInCallee()) { 12141 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12142 MarkFunctionReferenced(Param->getLocation(), Destructor); 12143 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 12144 } 12145 } 12146 } 12147 12148 // Parameters with the pass_object_size attribute only need to be marked 12149 // constant at function definitions. Because we lack information about 12150 // whether we're on a declaration or definition when we're instantiating the 12151 // attribute, we need to check for constness here. 12152 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 12153 if (!Param->getType().isConstQualified()) 12154 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 12155 << Attr->getSpelling() << 1; 12156 12157 // Check for parameter names shadowing fields from the class. 12158 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 12159 // The owning context for the parameter should be the function, but we 12160 // want to see if this function's declaration context is a record. 12161 DeclContext *DC = Param->getDeclContext(); 12162 if (DC && DC->isFunctionOrMethod()) { 12163 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 12164 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 12165 RD, /*DeclIsField*/ false); 12166 } 12167 } 12168 } 12169 12170 return HasInvalidParm; 12171 } 12172 12173 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 12174 /// or MemberExpr. 12175 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 12176 ASTContext &Context) { 12177 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 12178 return Context.getDeclAlign(DRE->getDecl()); 12179 12180 if (const auto *ME = dyn_cast<MemberExpr>(E)) 12181 return Context.getDeclAlign(ME->getMemberDecl()); 12182 12183 return TypeAlign; 12184 } 12185 12186 /// CheckCastAlign - Implements -Wcast-align, which warns when a 12187 /// pointer cast increases the alignment requirements. 12188 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 12189 // This is actually a lot of work to potentially be doing on every 12190 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 12191 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 12192 return; 12193 12194 // Ignore dependent types. 12195 if (T->isDependentType() || Op->getType()->isDependentType()) 12196 return; 12197 12198 // Require that the destination be a pointer type. 12199 const PointerType *DestPtr = T->getAs<PointerType>(); 12200 if (!DestPtr) return; 12201 12202 // If the destination has alignment 1, we're done. 12203 QualType DestPointee = DestPtr->getPointeeType(); 12204 if (DestPointee->isIncompleteType()) return; 12205 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 12206 if (DestAlign.isOne()) return; 12207 12208 // Require that the source be a pointer type. 12209 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 12210 if (!SrcPtr) return; 12211 QualType SrcPointee = SrcPtr->getPointeeType(); 12212 12213 // Whitelist casts from cv void*. We already implicitly 12214 // whitelisted casts to cv void*, since they have alignment 1. 12215 // Also whitelist casts involving incomplete types, which implicitly 12216 // includes 'void'. 12217 if (SrcPointee->isIncompleteType()) return; 12218 12219 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 12220 12221 if (auto *CE = dyn_cast<CastExpr>(Op)) { 12222 if (CE->getCastKind() == CK_ArrayToPointerDecay) 12223 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 12224 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 12225 if (UO->getOpcode() == UO_AddrOf) 12226 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 12227 } 12228 12229 if (SrcAlign >= DestAlign) return; 12230 12231 Diag(TRange.getBegin(), diag::warn_cast_align) 12232 << Op->getType() << T 12233 << static_cast<unsigned>(SrcAlign.getQuantity()) 12234 << static_cast<unsigned>(DestAlign.getQuantity()) 12235 << TRange << Op->getSourceRange(); 12236 } 12237 12238 /// Check whether this array fits the idiom of a size-one tail padded 12239 /// array member of a struct. 12240 /// 12241 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 12242 /// commonly used to emulate flexible arrays in C89 code. 12243 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 12244 const NamedDecl *ND) { 12245 if (Size != 1 || !ND) return false; 12246 12247 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 12248 if (!FD) return false; 12249 12250 // Don't consider sizes resulting from macro expansions or template argument 12251 // substitution to form C89 tail-padded arrays. 12252 12253 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 12254 while (TInfo) { 12255 TypeLoc TL = TInfo->getTypeLoc(); 12256 // Look through typedefs. 12257 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 12258 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 12259 TInfo = TDL->getTypeSourceInfo(); 12260 continue; 12261 } 12262 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 12263 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 12264 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 12265 return false; 12266 } 12267 break; 12268 } 12269 12270 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 12271 if (!RD) return false; 12272 if (RD->isUnion()) return false; 12273 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12274 if (!CRD->isStandardLayout()) return false; 12275 } 12276 12277 // See if this is the last field decl in the record. 12278 const Decl *D = FD; 12279 while ((D = D->getNextDeclInContext())) 12280 if (isa<FieldDecl>(D)) 12281 return false; 12282 return true; 12283 } 12284 12285 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 12286 const ArraySubscriptExpr *ASE, 12287 bool AllowOnePastEnd, bool IndexNegated) { 12288 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 12289 if (IndexExpr->isValueDependent()) 12290 return; 12291 12292 const Type *EffectiveType = 12293 BaseExpr->getType()->getPointeeOrArrayElementType(); 12294 BaseExpr = BaseExpr->IgnoreParenCasts(); 12295 const ConstantArrayType *ArrayTy = 12296 Context.getAsConstantArrayType(BaseExpr->getType()); 12297 if (!ArrayTy) 12298 return; 12299 12300 Expr::EvalResult Result; 12301 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 12302 return; 12303 12304 llvm::APSInt index = Result.Val.getInt(); 12305 if (IndexNegated) 12306 index = -index; 12307 12308 const NamedDecl *ND = nullptr; 12309 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12310 ND = DRE->getDecl(); 12311 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12312 ND = ME->getMemberDecl(); 12313 12314 if (index.isUnsigned() || !index.isNegative()) { 12315 llvm::APInt size = ArrayTy->getSize(); 12316 if (!size.isStrictlyPositive()) 12317 return; 12318 12319 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 12320 if (BaseType != EffectiveType) { 12321 // Make sure we're comparing apples to apples when comparing index to size 12322 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 12323 uint64_t array_typesize = Context.getTypeSize(BaseType); 12324 // Handle ptrarith_typesize being zero, such as when casting to void* 12325 if (!ptrarith_typesize) ptrarith_typesize = 1; 12326 if (ptrarith_typesize != array_typesize) { 12327 // There's a cast to a different size type involved 12328 uint64_t ratio = array_typesize / ptrarith_typesize; 12329 // TODO: Be smarter about handling cases where array_typesize is not a 12330 // multiple of ptrarith_typesize 12331 if (ptrarith_typesize * ratio == array_typesize) 12332 size *= llvm::APInt(size.getBitWidth(), ratio); 12333 } 12334 } 12335 12336 if (size.getBitWidth() > index.getBitWidth()) 12337 index = index.zext(size.getBitWidth()); 12338 else if (size.getBitWidth() < index.getBitWidth()) 12339 size = size.zext(index.getBitWidth()); 12340 12341 // For array subscripting the index must be less than size, but for pointer 12342 // arithmetic also allow the index (offset) to be equal to size since 12343 // computing the next address after the end of the array is legal and 12344 // commonly done e.g. in C++ iterators and range-based for loops. 12345 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 12346 return; 12347 12348 // Also don't warn for arrays of size 1 which are members of some 12349 // structure. These are often used to approximate flexible arrays in C89 12350 // code. 12351 if (IsTailPaddedMemberArray(*this, size, ND)) 12352 return; 12353 12354 // Suppress the warning if the subscript expression (as identified by the 12355 // ']' location) and the index expression are both from macro expansions 12356 // within a system header. 12357 if (ASE) { 12358 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 12359 ASE->getRBracketLoc()); 12360 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 12361 SourceLocation IndexLoc = 12362 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 12363 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 12364 return; 12365 } 12366 } 12367 12368 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 12369 if (ASE) 12370 DiagID = diag::warn_array_index_exceeds_bounds; 12371 12372 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12373 PDiag(DiagID) << index.toString(10, true) 12374 << size.toString(10, true) 12375 << (unsigned)size.getLimitedValue(~0U) 12376 << IndexExpr->getSourceRange()); 12377 } else { 12378 unsigned DiagID = diag::warn_array_index_precedes_bounds; 12379 if (!ASE) { 12380 DiagID = diag::warn_ptr_arith_precedes_bounds; 12381 if (index.isNegative()) index = -index; 12382 } 12383 12384 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12385 PDiag(DiagID) << index.toString(10, true) 12386 << IndexExpr->getSourceRange()); 12387 } 12388 12389 if (!ND) { 12390 // Try harder to find a NamedDecl to point at in the note. 12391 while (const ArraySubscriptExpr *ASE = 12392 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 12393 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 12394 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12395 ND = DRE->getDecl(); 12396 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12397 ND = ME->getMemberDecl(); 12398 } 12399 12400 if (ND) 12401 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 12402 PDiag(diag::note_array_index_out_of_bounds) 12403 << ND->getDeclName()); 12404 } 12405 12406 void Sema::CheckArrayAccess(const Expr *expr) { 12407 int AllowOnePastEnd = 0; 12408 while (expr) { 12409 expr = expr->IgnoreParenImpCasts(); 12410 switch (expr->getStmtClass()) { 12411 case Stmt::ArraySubscriptExprClass: { 12412 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 12413 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 12414 AllowOnePastEnd > 0); 12415 expr = ASE->getBase(); 12416 break; 12417 } 12418 case Stmt::MemberExprClass: { 12419 expr = cast<MemberExpr>(expr)->getBase(); 12420 break; 12421 } 12422 case Stmt::OMPArraySectionExprClass: { 12423 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 12424 if (ASE->getLowerBound()) 12425 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 12426 /*ASE=*/nullptr, AllowOnePastEnd > 0); 12427 return; 12428 } 12429 case Stmt::UnaryOperatorClass: { 12430 // Only unwrap the * and & unary operators 12431 const UnaryOperator *UO = cast<UnaryOperator>(expr); 12432 expr = UO->getSubExpr(); 12433 switch (UO->getOpcode()) { 12434 case UO_AddrOf: 12435 AllowOnePastEnd++; 12436 break; 12437 case UO_Deref: 12438 AllowOnePastEnd--; 12439 break; 12440 default: 12441 return; 12442 } 12443 break; 12444 } 12445 case Stmt::ConditionalOperatorClass: { 12446 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 12447 if (const Expr *lhs = cond->getLHS()) 12448 CheckArrayAccess(lhs); 12449 if (const Expr *rhs = cond->getRHS()) 12450 CheckArrayAccess(rhs); 12451 return; 12452 } 12453 case Stmt::CXXOperatorCallExprClass: { 12454 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 12455 for (const auto *Arg : OCE->arguments()) 12456 CheckArrayAccess(Arg); 12457 return; 12458 } 12459 default: 12460 return; 12461 } 12462 } 12463 } 12464 12465 //===--- CHECK: Objective-C retain cycles ----------------------------------// 12466 12467 namespace { 12468 12469 struct RetainCycleOwner { 12470 VarDecl *Variable = nullptr; 12471 SourceRange Range; 12472 SourceLocation Loc; 12473 bool Indirect = false; 12474 12475 RetainCycleOwner() = default; 12476 12477 void setLocsFrom(Expr *e) { 12478 Loc = e->getExprLoc(); 12479 Range = e->getSourceRange(); 12480 } 12481 }; 12482 12483 } // namespace 12484 12485 /// Consider whether capturing the given variable can possibly lead to 12486 /// a retain cycle. 12487 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 12488 // In ARC, it's captured strongly iff the variable has __strong 12489 // lifetime. In MRR, it's captured strongly if the variable is 12490 // __block and has an appropriate type. 12491 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12492 return false; 12493 12494 owner.Variable = var; 12495 if (ref) 12496 owner.setLocsFrom(ref); 12497 return true; 12498 } 12499 12500 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 12501 while (true) { 12502 e = e->IgnoreParens(); 12503 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 12504 switch (cast->getCastKind()) { 12505 case CK_BitCast: 12506 case CK_LValueBitCast: 12507 case CK_LValueToRValue: 12508 case CK_ARCReclaimReturnedObject: 12509 e = cast->getSubExpr(); 12510 continue; 12511 12512 default: 12513 return false; 12514 } 12515 } 12516 12517 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 12518 ObjCIvarDecl *ivar = ref->getDecl(); 12519 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12520 return false; 12521 12522 // Try to find a retain cycle in the base. 12523 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 12524 return false; 12525 12526 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 12527 owner.Indirect = true; 12528 return true; 12529 } 12530 12531 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 12532 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 12533 if (!var) return false; 12534 return considerVariable(var, ref, owner); 12535 } 12536 12537 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 12538 if (member->isArrow()) return false; 12539 12540 // Don't count this as an indirect ownership. 12541 e = member->getBase(); 12542 continue; 12543 } 12544 12545 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 12546 // Only pay attention to pseudo-objects on property references. 12547 ObjCPropertyRefExpr *pre 12548 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 12549 ->IgnoreParens()); 12550 if (!pre) return false; 12551 if (pre->isImplicitProperty()) return false; 12552 ObjCPropertyDecl *property = pre->getExplicitProperty(); 12553 if (!property->isRetaining() && 12554 !(property->getPropertyIvarDecl() && 12555 property->getPropertyIvarDecl()->getType() 12556 .getObjCLifetime() == Qualifiers::OCL_Strong)) 12557 return false; 12558 12559 owner.Indirect = true; 12560 if (pre->isSuperReceiver()) { 12561 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 12562 if (!owner.Variable) 12563 return false; 12564 owner.Loc = pre->getLocation(); 12565 owner.Range = pre->getSourceRange(); 12566 return true; 12567 } 12568 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 12569 ->getSourceExpr()); 12570 continue; 12571 } 12572 12573 // Array ivars? 12574 12575 return false; 12576 } 12577 } 12578 12579 namespace { 12580 12581 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 12582 ASTContext &Context; 12583 VarDecl *Variable; 12584 Expr *Capturer = nullptr; 12585 bool VarWillBeReased = false; 12586 12587 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 12588 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 12589 Context(Context), Variable(variable) {} 12590 12591 void VisitDeclRefExpr(DeclRefExpr *ref) { 12592 if (ref->getDecl() == Variable && !Capturer) 12593 Capturer = ref; 12594 } 12595 12596 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 12597 if (Capturer) return; 12598 Visit(ref->getBase()); 12599 if (Capturer && ref->isFreeIvar()) 12600 Capturer = ref; 12601 } 12602 12603 void VisitBlockExpr(BlockExpr *block) { 12604 // Look inside nested blocks 12605 if (block->getBlockDecl()->capturesVariable(Variable)) 12606 Visit(block->getBlockDecl()->getBody()); 12607 } 12608 12609 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 12610 if (Capturer) return; 12611 if (OVE->getSourceExpr()) 12612 Visit(OVE->getSourceExpr()); 12613 } 12614 12615 void VisitBinaryOperator(BinaryOperator *BinOp) { 12616 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 12617 return; 12618 Expr *LHS = BinOp->getLHS(); 12619 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 12620 if (DRE->getDecl() != Variable) 12621 return; 12622 if (Expr *RHS = BinOp->getRHS()) { 12623 RHS = RHS->IgnoreParenCasts(); 12624 llvm::APSInt Value; 12625 VarWillBeReased = 12626 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 12627 } 12628 } 12629 } 12630 }; 12631 12632 } // namespace 12633 12634 /// Check whether the given argument is a block which captures a 12635 /// variable. 12636 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 12637 assert(owner.Variable && owner.Loc.isValid()); 12638 12639 e = e->IgnoreParenCasts(); 12640 12641 // Look through [^{...} copy] and Block_copy(^{...}). 12642 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 12643 Selector Cmd = ME->getSelector(); 12644 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 12645 e = ME->getInstanceReceiver(); 12646 if (!e) 12647 return nullptr; 12648 e = e->IgnoreParenCasts(); 12649 } 12650 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 12651 if (CE->getNumArgs() == 1) { 12652 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 12653 if (Fn) { 12654 const IdentifierInfo *FnI = Fn->getIdentifier(); 12655 if (FnI && FnI->isStr("_Block_copy")) { 12656 e = CE->getArg(0)->IgnoreParenCasts(); 12657 } 12658 } 12659 } 12660 } 12661 12662 BlockExpr *block = dyn_cast<BlockExpr>(e); 12663 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 12664 return nullptr; 12665 12666 FindCaptureVisitor visitor(S.Context, owner.Variable); 12667 visitor.Visit(block->getBlockDecl()->getBody()); 12668 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 12669 } 12670 12671 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 12672 RetainCycleOwner &owner) { 12673 assert(capturer); 12674 assert(owner.Variable && owner.Loc.isValid()); 12675 12676 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 12677 << owner.Variable << capturer->getSourceRange(); 12678 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 12679 << owner.Indirect << owner.Range; 12680 } 12681 12682 /// Check for a keyword selector that starts with the word 'add' or 12683 /// 'set'. 12684 static bool isSetterLikeSelector(Selector sel) { 12685 if (sel.isUnarySelector()) return false; 12686 12687 StringRef str = sel.getNameForSlot(0); 12688 while (!str.empty() && str.front() == '_') str = str.substr(1); 12689 if (str.startswith("set")) 12690 str = str.substr(3); 12691 else if (str.startswith("add")) { 12692 // Specially whitelist 'addOperationWithBlock:'. 12693 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 12694 return false; 12695 str = str.substr(3); 12696 } 12697 else 12698 return false; 12699 12700 if (str.empty()) return true; 12701 return !isLowercase(str.front()); 12702 } 12703 12704 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 12705 ObjCMessageExpr *Message) { 12706 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 12707 Message->getReceiverInterface(), 12708 NSAPI::ClassId_NSMutableArray); 12709 if (!IsMutableArray) { 12710 return None; 12711 } 12712 12713 Selector Sel = Message->getSelector(); 12714 12715 Optional<NSAPI::NSArrayMethodKind> MKOpt = 12716 S.NSAPIObj->getNSArrayMethodKind(Sel); 12717 if (!MKOpt) { 12718 return None; 12719 } 12720 12721 NSAPI::NSArrayMethodKind MK = *MKOpt; 12722 12723 switch (MK) { 12724 case NSAPI::NSMutableArr_addObject: 12725 case NSAPI::NSMutableArr_insertObjectAtIndex: 12726 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 12727 return 0; 12728 case NSAPI::NSMutableArr_replaceObjectAtIndex: 12729 return 1; 12730 12731 default: 12732 return None; 12733 } 12734 12735 return None; 12736 } 12737 12738 static 12739 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 12740 ObjCMessageExpr *Message) { 12741 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 12742 Message->getReceiverInterface(), 12743 NSAPI::ClassId_NSMutableDictionary); 12744 if (!IsMutableDictionary) { 12745 return None; 12746 } 12747 12748 Selector Sel = Message->getSelector(); 12749 12750 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 12751 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 12752 if (!MKOpt) { 12753 return None; 12754 } 12755 12756 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 12757 12758 switch (MK) { 12759 case NSAPI::NSMutableDict_setObjectForKey: 12760 case NSAPI::NSMutableDict_setValueForKey: 12761 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 12762 return 0; 12763 12764 default: 12765 return None; 12766 } 12767 12768 return None; 12769 } 12770 12771 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 12772 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 12773 Message->getReceiverInterface(), 12774 NSAPI::ClassId_NSMutableSet); 12775 12776 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 12777 Message->getReceiverInterface(), 12778 NSAPI::ClassId_NSMutableOrderedSet); 12779 if (!IsMutableSet && !IsMutableOrderedSet) { 12780 return None; 12781 } 12782 12783 Selector Sel = Message->getSelector(); 12784 12785 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 12786 if (!MKOpt) { 12787 return None; 12788 } 12789 12790 NSAPI::NSSetMethodKind MK = *MKOpt; 12791 12792 switch (MK) { 12793 case NSAPI::NSMutableSet_addObject: 12794 case NSAPI::NSOrderedSet_setObjectAtIndex: 12795 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 12796 case NSAPI::NSOrderedSet_insertObjectAtIndex: 12797 return 0; 12798 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 12799 return 1; 12800 } 12801 12802 return None; 12803 } 12804 12805 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 12806 if (!Message->isInstanceMessage()) { 12807 return; 12808 } 12809 12810 Optional<int> ArgOpt; 12811 12812 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 12813 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 12814 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 12815 return; 12816 } 12817 12818 int ArgIndex = *ArgOpt; 12819 12820 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 12821 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 12822 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 12823 } 12824 12825 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 12826 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12827 if (ArgRE->isObjCSelfExpr()) { 12828 Diag(Message->getSourceRange().getBegin(), 12829 diag::warn_objc_circular_container) 12830 << ArgRE->getDecl() << StringRef("'super'"); 12831 } 12832 } 12833 } else { 12834 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 12835 12836 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 12837 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 12838 } 12839 12840 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 12841 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12842 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 12843 ValueDecl *Decl = ReceiverRE->getDecl(); 12844 Diag(Message->getSourceRange().getBegin(), 12845 diag::warn_objc_circular_container) 12846 << Decl << Decl; 12847 if (!ArgRE->isObjCSelfExpr()) { 12848 Diag(Decl->getLocation(), 12849 diag::note_objc_circular_container_declared_here) 12850 << Decl; 12851 } 12852 } 12853 } 12854 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 12855 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 12856 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 12857 ObjCIvarDecl *Decl = IvarRE->getDecl(); 12858 Diag(Message->getSourceRange().getBegin(), 12859 diag::warn_objc_circular_container) 12860 << Decl << Decl; 12861 Diag(Decl->getLocation(), 12862 diag::note_objc_circular_container_declared_here) 12863 << Decl; 12864 } 12865 } 12866 } 12867 } 12868 } 12869 12870 /// Check a message send to see if it's likely to cause a retain cycle. 12871 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 12872 // Only check instance methods whose selector looks like a setter. 12873 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 12874 return; 12875 12876 // Try to find a variable that the receiver is strongly owned by. 12877 RetainCycleOwner owner; 12878 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 12879 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 12880 return; 12881 } else { 12882 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 12883 owner.Variable = getCurMethodDecl()->getSelfDecl(); 12884 owner.Loc = msg->getSuperLoc(); 12885 owner.Range = msg->getSuperLoc(); 12886 } 12887 12888 // Check whether the receiver is captured by any of the arguments. 12889 const ObjCMethodDecl *MD = msg->getMethodDecl(); 12890 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 12891 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 12892 // noescape blocks should not be retained by the method. 12893 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 12894 continue; 12895 return diagnoseRetainCycle(*this, capturer, owner); 12896 } 12897 } 12898 } 12899 12900 /// Check a property assign to see if it's likely to cause a retain cycle. 12901 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 12902 RetainCycleOwner owner; 12903 if (!findRetainCycleOwner(*this, receiver, owner)) 12904 return; 12905 12906 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 12907 diagnoseRetainCycle(*this, capturer, owner); 12908 } 12909 12910 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 12911 RetainCycleOwner Owner; 12912 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 12913 return; 12914 12915 // Because we don't have an expression for the variable, we have to set the 12916 // location explicitly here. 12917 Owner.Loc = Var->getLocation(); 12918 Owner.Range = Var->getSourceRange(); 12919 12920 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 12921 diagnoseRetainCycle(*this, Capturer, Owner); 12922 } 12923 12924 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 12925 Expr *RHS, bool isProperty) { 12926 // Check if RHS is an Objective-C object literal, which also can get 12927 // immediately zapped in a weak reference. Note that we explicitly 12928 // allow ObjCStringLiterals, since those are designed to never really die. 12929 RHS = RHS->IgnoreParenImpCasts(); 12930 12931 // This enum needs to match with the 'select' in 12932 // warn_objc_arc_literal_assign (off-by-1). 12933 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 12934 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 12935 return false; 12936 12937 S.Diag(Loc, diag::warn_arc_literal_assign) 12938 << (unsigned) Kind 12939 << (isProperty ? 0 : 1) 12940 << RHS->getSourceRange(); 12941 12942 return true; 12943 } 12944 12945 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 12946 Qualifiers::ObjCLifetime LT, 12947 Expr *RHS, bool isProperty) { 12948 // Strip off any implicit cast added to get to the one ARC-specific. 12949 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12950 if (cast->getCastKind() == CK_ARCConsumeObject) { 12951 S.Diag(Loc, diag::warn_arc_retained_assign) 12952 << (LT == Qualifiers::OCL_ExplicitNone) 12953 << (isProperty ? 0 : 1) 12954 << RHS->getSourceRange(); 12955 return true; 12956 } 12957 RHS = cast->getSubExpr(); 12958 } 12959 12960 if (LT == Qualifiers::OCL_Weak && 12961 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 12962 return true; 12963 12964 return false; 12965 } 12966 12967 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 12968 QualType LHS, Expr *RHS) { 12969 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 12970 12971 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 12972 return false; 12973 12974 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 12975 return true; 12976 12977 return false; 12978 } 12979 12980 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 12981 Expr *LHS, Expr *RHS) { 12982 QualType LHSType; 12983 // PropertyRef on LHS type need be directly obtained from 12984 // its declaration as it has a PseudoType. 12985 ObjCPropertyRefExpr *PRE 12986 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 12987 if (PRE && !PRE->isImplicitProperty()) { 12988 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12989 if (PD) 12990 LHSType = PD->getType(); 12991 } 12992 12993 if (LHSType.isNull()) 12994 LHSType = LHS->getType(); 12995 12996 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 12997 12998 if (LT == Qualifiers::OCL_Weak) { 12999 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 13000 getCurFunction()->markSafeWeakUse(LHS); 13001 } 13002 13003 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 13004 return; 13005 13006 // FIXME. Check for other life times. 13007 if (LT != Qualifiers::OCL_None) 13008 return; 13009 13010 if (PRE) { 13011 if (PRE->isImplicitProperty()) 13012 return; 13013 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13014 if (!PD) 13015 return; 13016 13017 unsigned Attributes = PD->getPropertyAttributes(); 13018 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 13019 // when 'assign' attribute was not explicitly specified 13020 // by user, ignore it and rely on property type itself 13021 // for lifetime info. 13022 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 13023 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 13024 LHSType->isObjCRetainableType()) 13025 return; 13026 13027 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13028 if (cast->getCastKind() == CK_ARCConsumeObject) { 13029 Diag(Loc, diag::warn_arc_retained_property_assign) 13030 << RHS->getSourceRange(); 13031 return; 13032 } 13033 RHS = cast->getSubExpr(); 13034 } 13035 } 13036 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 13037 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 13038 return; 13039 } 13040 } 13041 } 13042 13043 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 13044 13045 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 13046 SourceLocation StmtLoc, 13047 const NullStmt *Body) { 13048 // Do not warn if the body is a macro that expands to nothing, e.g: 13049 // 13050 // #define CALL(x) 13051 // if (condition) 13052 // CALL(0); 13053 if (Body->hasLeadingEmptyMacro()) 13054 return false; 13055 13056 // Get line numbers of statement and body. 13057 bool StmtLineInvalid; 13058 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 13059 &StmtLineInvalid); 13060 if (StmtLineInvalid) 13061 return false; 13062 13063 bool BodyLineInvalid; 13064 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 13065 &BodyLineInvalid); 13066 if (BodyLineInvalid) 13067 return false; 13068 13069 // Warn if null statement and body are on the same line. 13070 if (StmtLine != BodyLine) 13071 return false; 13072 13073 return true; 13074 } 13075 13076 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 13077 const Stmt *Body, 13078 unsigned DiagID) { 13079 // Since this is a syntactic check, don't emit diagnostic for template 13080 // instantiations, this just adds noise. 13081 if (CurrentInstantiationScope) 13082 return; 13083 13084 // The body should be a null statement. 13085 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13086 if (!NBody) 13087 return; 13088 13089 // Do the usual checks. 13090 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13091 return; 13092 13093 Diag(NBody->getSemiLoc(), DiagID); 13094 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13095 } 13096 13097 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 13098 const Stmt *PossibleBody) { 13099 assert(!CurrentInstantiationScope); // Ensured by caller 13100 13101 SourceLocation StmtLoc; 13102 const Stmt *Body; 13103 unsigned DiagID; 13104 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 13105 StmtLoc = FS->getRParenLoc(); 13106 Body = FS->getBody(); 13107 DiagID = diag::warn_empty_for_body; 13108 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 13109 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 13110 Body = WS->getBody(); 13111 DiagID = diag::warn_empty_while_body; 13112 } else 13113 return; // Neither `for' nor `while'. 13114 13115 // The body should be a null statement. 13116 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13117 if (!NBody) 13118 return; 13119 13120 // Skip expensive checks if diagnostic is disabled. 13121 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 13122 return; 13123 13124 // Do the usual checks. 13125 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13126 return; 13127 13128 // `for(...);' and `while(...);' are popular idioms, so in order to keep 13129 // noise level low, emit diagnostics only if for/while is followed by a 13130 // CompoundStmt, e.g.: 13131 // for (int i = 0; i < n; i++); 13132 // { 13133 // a(i); 13134 // } 13135 // or if for/while is followed by a statement with more indentation 13136 // than for/while itself: 13137 // for (int i = 0; i < n; i++); 13138 // a(i); 13139 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 13140 if (!ProbableTypo) { 13141 bool BodyColInvalid; 13142 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 13143 PossibleBody->getBeginLoc(), &BodyColInvalid); 13144 if (BodyColInvalid) 13145 return; 13146 13147 bool StmtColInvalid; 13148 unsigned StmtCol = 13149 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 13150 if (StmtColInvalid) 13151 return; 13152 13153 if (BodyCol > StmtCol) 13154 ProbableTypo = true; 13155 } 13156 13157 if (ProbableTypo) { 13158 Diag(NBody->getSemiLoc(), DiagID); 13159 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13160 } 13161 } 13162 13163 //===--- CHECK: Warn on self move with std::move. -------------------------===// 13164 13165 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 13166 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 13167 SourceLocation OpLoc) { 13168 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 13169 return; 13170 13171 if (inTemplateInstantiation()) 13172 return; 13173 13174 // Strip parens and casts away. 13175 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13176 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13177 13178 // Check for a call expression 13179 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 13180 if (!CE || CE->getNumArgs() != 1) 13181 return; 13182 13183 // Check for a call to std::move 13184 if (!CE->isCallToStdMove()) 13185 return; 13186 13187 // Get argument from std::move 13188 RHSExpr = CE->getArg(0); 13189 13190 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13191 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13192 13193 // Two DeclRefExpr's, check that the decls are the same. 13194 if (LHSDeclRef && RHSDeclRef) { 13195 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13196 return; 13197 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13198 RHSDeclRef->getDecl()->getCanonicalDecl()) 13199 return; 13200 13201 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13202 << LHSExpr->getSourceRange() 13203 << RHSExpr->getSourceRange(); 13204 return; 13205 } 13206 13207 // Member variables require a different approach to check for self moves. 13208 // MemberExpr's are the same if every nested MemberExpr refers to the same 13209 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 13210 // the base Expr's are CXXThisExpr's. 13211 const Expr *LHSBase = LHSExpr; 13212 const Expr *RHSBase = RHSExpr; 13213 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 13214 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 13215 if (!LHSME || !RHSME) 13216 return; 13217 13218 while (LHSME && RHSME) { 13219 if (LHSME->getMemberDecl()->getCanonicalDecl() != 13220 RHSME->getMemberDecl()->getCanonicalDecl()) 13221 return; 13222 13223 LHSBase = LHSME->getBase(); 13224 RHSBase = RHSME->getBase(); 13225 LHSME = dyn_cast<MemberExpr>(LHSBase); 13226 RHSME = dyn_cast<MemberExpr>(RHSBase); 13227 } 13228 13229 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 13230 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 13231 if (LHSDeclRef && RHSDeclRef) { 13232 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13233 return; 13234 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13235 RHSDeclRef->getDecl()->getCanonicalDecl()) 13236 return; 13237 13238 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13239 << LHSExpr->getSourceRange() 13240 << RHSExpr->getSourceRange(); 13241 return; 13242 } 13243 13244 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 13245 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13246 << LHSExpr->getSourceRange() 13247 << RHSExpr->getSourceRange(); 13248 } 13249 13250 //===--- Layout compatibility ----------------------------------------------// 13251 13252 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 13253 13254 /// Check if two enumeration types are layout-compatible. 13255 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 13256 // C++11 [dcl.enum] p8: 13257 // Two enumeration types are layout-compatible if they have the same 13258 // underlying type. 13259 return ED1->isComplete() && ED2->isComplete() && 13260 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 13261 } 13262 13263 /// Check if two fields are layout-compatible. 13264 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 13265 FieldDecl *Field2) { 13266 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 13267 return false; 13268 13269 if (Field1->isBitField() != Field2->isBitField()) 13270 return false; 13271 13272 if (Field1->isBitField()) { 13273 // Make sure that the bit-fields are the same length. 13274 unsigned Bits1 = Field1->getBitWidthValue(C); 13275 unsigned Bits2 = Field2->getBitWidthValue(C); 13276 13277 if (Bits1 != Bits2) 13278 return false; 13279 } 13280 13281 return true; 13282 } 13283 13284 /// Check if two standard-layout structs are layout-compatible. 13285 /// (C++11 [class.mem] p17) 13286 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 13287 RecordDecl *RD2) { 13288 // If both records are C++ classes, check that base classes match. 13289 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 13290 // If one of records is a CXXRecordDecl we are in C++ mode, 13291 // thus the other one is a CXXRecordDecl, too. 13292 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 13293 // Check number of base classes. 13294 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 13295 return false; 13296 13297 // Check the base classes. 13298 for (CXXRecordDecl::base_class_const_iterator 13299 Base1 = D1CXX->bases_begin(), 13300 BaseEnd1 = D1CXX->bases_end(), 13301 Base2 = D2CXX->bases_begin(); 13302 Base1 != BaseEnd1; 13303 ++Base1, ++Base2) { 13304 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 13305 return false; 13306 } 13307 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 13308 // If only RD2 is a C++ class, it should have zero base classes. 13309 if (D2CXX->getNumBases() > 0) 13310 return false; 13311 } 13312 13313 // Check the fields. 13314 RecordDecl::field_iterator Field2 = RD2->field_begin(), 13315 Field2End = RD2->field_end(), 13316 Field1 = RD1->field_begin(), 13317 Field1End = RD1->field_end(); 13318 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 13319 if (!isLayoutCompatible(C, *Field1, *Field2)) 13320 return false; 13321 } 13322 if (Field1 != Field1End || Field2 != Field2End) 13323 return false; 13324 13325 return true; 13326 } 13327 13328 /// Check if two standard-layout unions are layout-compatible. 13329 /// (C++11 [class.mem] p18) 13330 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 13331 RecordDecl *RD2) { 13332 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 13333 for (auto *Field2 : RD2->fields()) 13334 UnmatchedFields.insert(Field2); 13335 13336 for (auto *Field1 : RD1->fields()) { 13337 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 13338 I = UnmatchedFields.begin(), 13339 E = UnmatchedFields.end(); 13340 13341 for ( ; I != E; ++I) { 13342 if (isLayoutCompatible(C, Field1, *I)) { 13343 bool Result = UnmatchedFields.erase(*I); 13344 (void) Result; 13345 assert(Result); 13346 break; 13347 } 13348 } 13349 if (I == E) 13350 return false; 13351 } 13352 13353 return UnmatchedFields.empty(); 13354 } 13355 13356 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 13357 RecordDecl *RD2) { 13358 if (RD1->isUnion() != RD2->isUnion()) 13359 return false; 13360 13361 if (RD1->isUnion()) 13362 return isLayoutCompatibleUnion(C, RD1, RD2); 13363 else 13364 return isLayoutCompatibleStruct(C, RD1, RD2); 13365 } 13366 13367 /// Check if two types are layout-compatible in C++11 sense. 13368 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 13369 if (T1.isNull() || T2.isNull()) 13370 return false; 13371 13372 // C++11 [basic.types] p11: 13373 // If two types T1 and T2 are the same type, then T1 and T2 are 13374 // layout-compatible types. 13375 if (C.hasSameType(T1, T2)) 13376 return true; 13377 13378 T1 = T1.getCanonicalType().getUnqualifiedType(); 13379 T2 = T2.getCanonicalType().getUnqualifiedType(); 13380 13381 const Type::TypeClass TC1 = T1->getTypeClass(); 13382 const Type::TypeClass TC2 = T2->getTypeClass(); 13383 13384 if (TC1 != TC2) 13385 return false; 13386 13387 if (TC1 == Type::Enum) { 13388 return isLayoutCompatible(C, 13389 cast<EnumType>(T1)->getDecl(), 13390 cast<EnumType>(T2)->getDecl()); 13391 } else if (TC1 == Type::Record) { 13392 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 13393 return false; 13394 13395 return isLayoutCompatible(C, 13396 cast<RecordType>(T1)->getDecl(), 13397 cast<RecordType>(T2)->getDecl()); 13398 } 13399 13400 return false; 13401 } 13402 13403 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 13404 13405 /// Given a type tag expression find the type tag itself. 13406 /// 13407 /// \param TypeExpr Type tag expression, as it appears in user's code. 13408 /// 13409 /// \param VD Declaration of an identifier that appears in a type tag. 13410 /// 13411 /// \param MagicValue Type tag magic value. 13412 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 13413 const ValueDecl **VD, uint64_t *MagicValue) { 13414 while(true) { 13415 if (!TypeExpr) 13416 return false; 13417 13418 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 13419 13420 switch (TypeExpr->getStmtClass()) { 13421 case Stmt::UnaryOperatorClass: { 13422 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 13423 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 13424 TypeExpr = UO->getSubExpr(); 13425 continue; 13426 } 13427 return false; 13428 } 13429 13430 case Stmt::DeclRefExprClass: { 13431 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 13432 *VD = DRE->getDecl(); 13433 return true; 13434 } 13435 13436 case Stmt::IntegerLiteralClass: { 13437 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 13438 llvm::APInt MagicValueAPInt = IL->getValue(); 13439 if (MagicValueAPInt.getActiveBits() <= 64) { 13440 *MagicValue = MagicValueAPInt.getZExtValue(); 13441 return true; 13442 } else 13443 return false; 13444 } 13445 13446 case Stmt::BinaryConditionalOperatorClass: 13447 case Stmt::ConditionalOperatorClass: { 13448 const AbstractConditionalOperator *ACO = 13449 cast<AbstractConditionalOperator>(TypeExpr); 13450 bool Result; 13451 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 13452 if (Result) 13453 TypeExpr = ACO->getTrueExpr(); 13454 else 13455 TypeExpr = ACO->getFalseExpr(); 13456 continue; 13457 } 13458 return false; 13459 } 13460 13461 case Stmt::BinaryOperatorClass: { 13462 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 13463 if (BO->getOpcode() == BO_Comma) { 13464 TypeExpr = BO->getRHS(); 13465 continue; 13466 } 13467 return false; 13468 } 13469 13470 default: 13471 return false; 13472 } 13473 } 13474 } 13475 13476 /// Retrieve the C type corresponding to type tag TypeExpr. 13477 /// 13478 /// \param TypeExpr Expression that specifies a type tag. 13479 /// 13480 /// \param MagicValues Registered magic values. 13481 /// 13482 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 13483 /// kind. 13484 /// 13485 /// \param TypeInfo Information about the corresponding C type. 13486 /// 13487 /// \returns true if the corresponding C type was found. 13488 static bool GetMatchingCType( 13489 const IdentifierInfo *ArgumentKind, 13490 const Expr *TypeExpr, const ASTContext &Ctx, 13491 const llvm::DenseMap<Sema::TypeTagMagicValue, 13492 Sema::TypeTagData> *MagicValues, 13493 bool &FoundWrongKind, 13494 Sema::TypeTagData &TypeInfo) { 13495 FoundWrongKind = false; 13496 13497 // Variable declaration that has type_tag_for_datatype attribute. 13498 const ValueDecl *VD = nullptr; 13499 13500 uint64_t MagicValue; 13501 13502 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 13503 return false; 13504 13505 if (VD) { 13506 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 13507 if (I->getArgumentKind() != ArgumentKind) { 13508 FoundWrongKind = true; 13509 return false; 13510 } 13511 TypeInfo.Type = I->getMatchingCType(); 13512 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 13513 TypeInfo.MustBeNull = I->getMustBeNull(); 13514 return true; 13515 } 13516 return false; 13517 } 13518 13519 if (!MagicValues) 13520 return false; 13521 13522 llvm::DenseMap<Sema::TypeTagMagicValue, 13523 Sema::TypeTagData>::const_iterator I = 13524 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 13525 if (I == MagicValues->end()) 13526 return false; 13527 13528 TypeInfo = I->second; 13529 return true; 13530 } 13531 13532 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 13533 uint64_t MagicValue, QualType Type, 13534 bool LayoutCompatible, 13535 bool MustBeNull) { 13536 if (!TypeTagForDatatypeMagicValues) 13537 TypeTagForDatatypeMagicValues.reset( 13538 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 13539 13540 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 13541 (*TypeTagForDatatypeMagicValues)[Magic] = 13542 TypeTagData(Type, LayoutCompatible, MustBeNull); 13543 } 13544 13545 static bool IsSameCharType(QualType T1, QualType T2) { 13546 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 13547 if (!BT1) 13548 return false; 13549 13550 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 13551 if (!BT2) 13552 return false; 13553 13554 BuiltinType::Kind T1Kind = BT1->getKind(); 13555 BuiltinType::Kind T2Kind = BT2->getKind(); 13556 13557 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 13558 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 13559 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 13560 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 13561 } 13562 13563 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 13564 const ArrayRef<const Expr *> ExprArgs, 13565 SourceLocation CallSiteLoc) { 13566 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 13567 bool IsPointerAttr = Attr->getIsPointer(); 13568 13569 // Retrieve the argument representing the 'type_tag'. 13570 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 13571 if (TypeTagIdxAST >= ExprArgs.size()) { 13572 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 13573 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 13574 return; 13575 } 13576 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 13577 bool FoundWrongKind; 13578 TypeTagData TypeInfo; 13579 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 13580 TypeTagForDatatypeMagicValues.get(), 13581 FoundWrongKind, TypeInfo)) { 13582 if (FoundWrongKind) 13583 Diag(TypeTagExpr->getExprLoc(), 13584 diag::warn_type_tag_for_datatype_wrong_kind) 13585 << TypeTagExpr->getSourceRange(); 13586 return; 13587 } 13588 13589 // Retrieve the argument representing the 'arg_idx'. 13590 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 13591 if (ArgumentIdxAST >= ExprArgs.size()) { 13592 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 13593 << 1 << Attr->getArgumentIdx().getSourceIndex(); 13594 return; 13595 } 13596 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 13597 if (IsPointerAttr) { 13598 // Skip implicit cast of pointer to `void *' (as a function argument). 13599 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 13600 if (ICE->getType()->isVoidPointerType() && 13601 ICE->getCastKind() == CK_BitCast) 13602 ArgumentExpr = ICE->getSubExpr(); 13603 } 13604 QualType ArgumentType = ArgumentExpr->getType(); 13605 13606 // Passing a `void*' pointer shouldn't trigger a warning. 13607 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 13608 return; 13609 13610 if (TypeInfo.MustBeNull) { 13611 // Type tag with matching void type requires a null pointer. 13612 if (!ArgumentExpr->isNullPointerConstant(Context, 13613 Expr::NPC_ValueDependentIsNotNull)) { 13614 Diag(ArgumentExpr->getExprLoc(), 13615 diag::warn_type_safety_null_pointer_required) 13616 << ArgumentKind->getName() 13617 << ArgumentExpr->getSourceRange() 13618 << TypeTagExpr->getSourceRange(); 13619 } 13620 return; 13621 } 13622 13623 QualType RequiredType = TypeInfo.Type; 13624 if (IsPointerAttr) 13625 RequiredType = Context.getPointerType(RequiredType); 13626 13627 bool mismatch = false; 13628 if (!TypeInfo.LayoutCompatible) { 13629 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 13630 13631 // C++11 [basic.fundamental] p1: 13632 // Plain char, signed char, and unsigned char are three distinct types. 13633 // 13634 // But we treat plain `char' as equivalent to `signed char' or `unsigned 13635 // char' depending on the current char signedness mode. 13636 if (mismatch) 13637 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 13638 RequiredType->getPointeeType())) || 13639 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 13640 mismatch = false; 13641 } else 13642 if (IsPointerAttr) 13643 mismatch = !isLayoutCompatible(Context, 13644 ArgumentType->getPointeeType(), 13645 RequiredType->getPointeeType()); 13646 else 13647 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 13648 13649 if (mismatch) 13650 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 13651 << ArgumentType << ArgumentKind 13652 << TypeInfo.LayoutCompatible << RequiredType 13653 << ArgumentExpr->getSourceRange() 13654 << TypeTagExpr->getSourceRange(); 13655 } 13656 13657 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 13658 CharUnits Alignment) { 13659 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 13660 } 13661 13662 void Sema::DiagnoseMisalignedMembers() { 13663 for (MisalignedMember &m : MisalignedMembers) { 13664 const NamedDecl *ND = m.RD; 13665 if (ND->getName().empty()) { 13666 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 13667 ND = TD; 13668 } 13669 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 13670 << m.MD << ND << m.E->getSourceRange(); 13671 } 13672 MisalignedMembers.clear(); 13673 } 13674 13675 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 13676 E = E->IgnoreParens(); 13677 if (!T->isPointerType() && !T->isIntegerType()) 13678 return; 13679 if (isa<UnaryOperator>(E) && 13680 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 13681 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 13682 if (isa<MemberExpr>(Op)) { 13683 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 13684 MisalignedMember(Op)); 13685 if (MA != MisalignedMembers.end() && 13686 (T->isIntegerType() || 13687 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 13688 Context.getTypeAlignInChars( 13689 T->getPointeeType()) <= MA->Alignment)))) 13690 MisalignedMembers.erase(MA); 13691 } 13692 } 13693 } 13694 13695 void Sema::RefersToMemberWithReducedAlignment( 13696 Expr *E, 13697 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 13698 Action) { 13699 const auto *ME = dyn_cast<MemberExpr>(E); 13700 if (!ME) 13701 return; 13702 13703 // No need to check expressions with an __unaligned-qualified type. 13704 if (E->getType().getQualifiers().hasUnaligned()) 13705 return; 13706 13707 // For a chain of MemberExpr like "a.b.c.d" this list 13708 // will keep FieldDecl's like [d, c, b]. 13709 SmallVector<FieldDecl *, 4> ReverseMemberChain; 13710 const MemberExpr *TopME = nullptr; 13711 bool AnyIsPacked = false; 13712 do { 13713 QualType BaseType = ME->getBase()->getType(); 13714 if (ME->isArrow()) 13715 BaseType = BaseType->getPointeeType(); 13716 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 13717 if (RD->isInvalidDecl()) 13718 return; 13719 13720 ValueDecl *MD = ME->getMemberDecl(); 13721 auto *FD = dyn_cast<FieldDecl>(MD); 13722 // We do not care about non-data members. 13723 if (!FD || FD->isInvalidDecl()) 13724 return; 13725 13726 AnyIsPacked = 13727 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 13728 ReverseMemberChain.push_back(FD); 13729 13730 TopME = ME; 13731 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 13732 } while (ME); 13733 assert(TopME && "We did not compute a topmost MemberExpr!"); 13734 13735 // Not the scope of this diagnostic. 13736 if (!AnyIsPacked) 13737 return; 13738 13739 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 13740 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 13741 // TODO: The innermost base of the member expression may be too complicated. 13742 // For now, just disregard these cases. This is left for future 13743 // improvement. 13744 if (!DRE && !isa<CXXThisExpr>(TopBase)) 13745 return; 13746 13747 // Alignment expected by the whole expression. 13748 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 13749 13750 // No need to do anything else with this case. 13751 if (ExpectedAlignment.isOne()) 13752 return; 13753 13754 // Synthesize offset of the whole access. 13755 CharUnits Offset; 13756 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 13757 I++) { 13758 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 13759 } 13760 13761 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 13762 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 13763 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 13764 13765 // The base expression of the innermost MemberExpr may give 13766 // stronger guarantees than the class containing the member. 13767 if (DRE && !TopME->isArrow()) { 13768 const ValueDecl *VD = DRE->getDecl(); 13769 if (!VD->getType()->isReferenceType()) 13770 CompleteObjectAlignment = 13771 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 13772 } 13773 13774 // Check if the synthesized offset fulfills the alignment. 13775 if (Offset % ExpectedAlignment != 0 || 13776 // It may fulfill the offset it but the effective alignment may still be 13777 // lower than the expected expression alignment. 13778 CompleteObjectAlignment < ExpectedAlignment) { 13779 // If this happens, we want to determine a sensible culprit of this. 13780 // Intuitively, watching the chain of member expressions from right to 13781 // left, we start with the required alignment (as required by the field 13782 // type) but some packed attribute in that chain has reduced the alignment. 13783 // It may happen that another packed structure increases it again. But if 13784 // we are here such increase has not been enough. So pointing the first 13785 // FieldDecl that either is packed or else its RecordDecl is, 13786 // seems reasonable. 13787 FieldDecl *FD = nullptr; 13788 CharUnits Alignment; 13789 for (FieldDecl *FDI : ReverseMemberChain) { 13790 if (FDI->hasAttr<PackedAttr>() || 13791 FDI->getParent()->hasAttr<PackedAttr>()) { 13792 FD = FDI; 13793 Alignment = std::min( 13794 Context.getTypeAlignInChars(FD->getType()), 13795 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 13796 break; 13797 } 13798 } 13799 assert(FD && "We did not find a packed FieldDecl!"); 13800 Action(E, FD->getParent(), FD, Alignment); 13801 } 13802 } 13803 13804 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 13805 using namespace std::placeholders; 13806 13807 RefersToMemberWithReducedAlignment( 13808 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 13809 _2, _3, _4)); 13810 } 13811