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/ASTContext.h" 16 #include "clang/AST/CharUnits.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/DeclObjC.h" 19 #include "clang/AST/EvaluatedExprVisitor.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/ExprObjC.h" 23 #include "clang/AST/ExprOpenMP.h" 24 #include "clang/AST/StmtCXX.h" 25 #include "clang/AST/StmtObjC.h" 26 #include "clang/Analysis/Analyses/FormatString.h" 27 #include "clang/Basic/CharInfo.h" 28 #include "clang/Basic/SyncScope.h" 29 #include "clang/Basic/TargetBuiltins.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 32 #include "clang/Sema/Initialization.h" 33 #include "clang/Sema/Lookup.h" 34 #include "clang/Sema/ScopeInfo.h" 35 #include "clang/Sema/Sema.h" 36 #include "clang/Sema/SemaInternal.h" 37 #include "llvm/ADT/STLExtras.h" 38 #include "llvm/ADT/SmallBitVector.h" 39 #include "llvm/ADT/SmallString.h" 40 #include "llvm/Support/ConvertUTF.h" 41 #include "llvm/Support/Format.h" 42 #include "llvm/Support/Locale.h" 43 #include "llvm/Support/raw_ostream.h" 44 45 using namespace clang; 46 using namespace sema; 47 48 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 49 unsigned ByteNo) const { 50 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 51 Context.getTargetInfo()); 52 } 53 54 /// Checks that a call expression's argument count is the desired number. 55 /// This is useful when doing custom type-checking. Returns true on error. 56 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 57 unsigned argCount = call->getNumArgs(); 58 if (argCount == desiredArgCount) return false; 59 60 if (argCount < desiredArgCount) 61 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 62 << 0 /*function call*/ << desiredArgCount << argCount 63 << call->getSourceRange(); 64 65 // Highlight all the excess arguments. 66 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 67 call->getArg(argCount - 1)->getLocEnd()); 68 69 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 70 << 0 /*function call*/ << desiredArgCount << argCount 71 << call->getArg(1)->getSourceRange(); 72 } 73 74 /// Check that the first argument to __builtin_annotation is an integer 75 /// and the second argument is a non-wide string literal. 76 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 77 if (checkArgCount(S, TheCall, 2)) 78 return true; 79 80 // First argument should be an integer. 81 Expr *ValArg = TheCall->getArg(0); 82 QualType Ty = ValArg->getType(); 83 if (!Ty->isIntegerType()) { 84 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 85 << ValArg->getSourceRange(); 86 return true; 87 } 88 89 // Second argument should be a constant string. 90 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 91 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 92 if (!Literal || !Literal->isAscii()) { 93 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 94 << StrArg->getSourceRange(); 95 return true; 96 } 97 98 TheCall->setType(Ty); 99 return false; 100 } 101 102 /// Check that the argument to __builtin_addressof is a glvalue, and set the 103 /// result type to the corresponding pointer type. 104 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 105 if (checkArgCount(S, TheCall, 1)) 106 return true; 107 108 ExprResult Arg(TheCall->getArg(0)); 109 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 110 if (ResultType.isNull()) 111 return true; 112 113 TheCall->setArg(0, Arg.get()); 114 TheCall->setType(ResultType); 115 return false; 116 } 117 118 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 119 if (checkArgCount(S, TheCall, 3)) 120 return true; 121 122 // First two arguments should be integers. 123 for (unsigned I = 0; I < 2; ++I) { 124 Expr *Arg = TheCall->getArg(I); 125 QualType Ty = Arg->getType(); 126 if (!Ty->isIntegerType()) { 127 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int) 128 << Ty << Arg->getSourceRange(); 129 return true; 130 } 131 } 132 133 // Third argument should be a pointer to a non-const integer. 134 // IRGen correctly handles volatile, restrict, and address spaces, and 135 // the other qualifiers aren't possible. 136 { 137 Expr *Arg = TheCall->getArg(2); 138 QualType Ty = Arg->getType(); 139 const auto *PtrTy = Ty->getAs<PointerType>(); 140 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 141 !PtrTy->getPointeeType().isConstQualified())) { 142 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int) 143 << Ty << Arg->getSourceRange(); 144 return true; 145 } 146 } 147 148 return false; 149 } 150 151 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 152 CallExpr *TheCall, unsigned SizeIdx, 153 unsigned DstSizeIdx) { 154 if (TheCall->getNumArgs() <= SizeIdx || 155 TheCall->getNumArgs() <= DstSizeIdx) 156 return; 157 158 const Expr *SizeArg = TheCall->getArg(SizeIdx); 159 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 160 161 llvm::APSInt Size, DstSize; 162 163 // find out if both sizes are known at compile time 164 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 165 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 166 return; 167 168 if (Size.ule(DstSize)) 169 return; 170 171 // confirmed overflow so generate the diagnostic. 172 IdentifierInfo *FnName = FDecl->getIdentifier(); 173 SourceLocation SL = TheCall->getLocStart(); 174 SourceRange SR = TheCall->getSourceRange(); 175 176 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; 177 } 178 179 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 180 if (checkArgCount(S, BuiltinCall, 2)) 181 return true; 182 183 SourceLocation BuiltinLoc = BuiltinCall->getLocStart(); 184 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 185 Expr *Call = BuiltinCall->getArg(0); 186 Expr *Chain = BuiltinCall->getArg(1); 187 188 if (Call->getStmtClass() != Stmt::CallExprClass) { 189 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 190 << Call->getSourceRange(); 191 return true; 192 } 193 194 auto CE = cast<CallExpr>(Call); 195 if (CE->getCallee()->getType()->isBlockPointerType()) { 196 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 197 << Call->getSourceRange(); 198 return true; 199 } 200 201 const Decl *TargetDecl = CE->getCalleeDecl(); 202 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 203 if (FD->getBuiltinID()) { 204 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 205 << Call->getSourceRange(); 206 return true; 207 } 208 209 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 210 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 211 << Call->getSourceRange(); 212 return true; 213 } 214 215 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 216 if (ChainResult.isInvalid()) 217 return true; 218 if (!ChainResult.get()->getType()->isPointerType()) { 219 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 220 << Chain->getSourceRange(); 221 return true; 222 } 223 224 QualType ReturnTy = CE->getCallReturnType(S.Context); 225 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 226 QualType BuiltinTy = S.Context.getFunctionType( 227 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 228 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 229 230 Builtin = 231 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 232 233 BuiltinCall->setType(CE->getType()); 234 BuiltinCall->setValueKind(CE->getValueKind()); 235 BuiltinCall->setObjectKind(CE->getObjectKind()); 236 BuiltinCall->setCallee(Builtin); 237 BuiltinCall->setArg(1, ChainResult.get()); 238 239 return false; 240 } 241 242 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 243 Scope::ScopeFlags NeededScopeFlags, 244 unsigned DiagID) { 245 // Scopes aren't available during instantiation. Fortunately, builtin 246 // functions cannot be template args so they cannot be formed through template 247 // instantiation. Therefore checking once during the parse is sufficient. 248 if (SemaRef.inTemplateInstantiation()) 249 return false; 250 251 Scope *S = SemaRef.getCurScope(); 252 while (S && !S->isSEHExceptScope()) 253 S = S->getParent(); 254 if (!S || !(S->getFlags() & NeededScopeFlags)) { 255 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 256 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 257 << DRE->getDecl()->getIdentifier(); 258 return true; 259 } 260 261 return false; 262 } 263 264 static inline bool isBlockPointer(Expr *Arg) { 265 return Arg->getType()->isBlockPointerType(); 266 } 267 268 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 269 /// void*, which is a requirement of device side enqueue. 270 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 271 const BlockPointerType *BPT = 272 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 273 ArrayRef<QualType> Params = 274 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 275 unsigned ArgCounter = 0; 276 bool IllegalParams = false; 277 // Iterate through the block parameters until either one is found that is not 278 // a local void*, or the block is valid. 279 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 280 I != E; ++I, ++ArgCounter) { 281 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 282 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 283 LangAS::opencl_local) { 284 // Get the location of the error. If a block literal has been passed 285 // (BlockExpr) then we can point straight to the offending argument, 286 // else we just point to the variable reference. 287 SourceLocation ErrorLoc; 288 if (isa<BlockExpr>(BlockArg)) { 289 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 290 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart(); 291 } else if (isa<DeclRefExpr>(BlockArg)) { 292 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart(); 293 } 294 S.Diag(ErrorLoc, 295 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 296 IllegalParams = true; 297 } 298 } 299 300 return IllegalParams; 301 } 302 303 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 304 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 305 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension) 306 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 307 return true; 308 } 309 return false; 310 } 311 312 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 313 if (checkArgCount(S, TheCall, 2)) 314 return true; 315 316 if (checkOpenCLSubgroupExt(S, TheCall)) 317 return true; 318 319 // First argument is an ndrange_t type. 320 Expr *NDRangeArg = TheCall->getArg(0); 321 if (NDRangeArg->getType().getAsString() != "ndrange_t") { 322 S.Diag(NDRangeArg->getLocStart(), 323 diag::err_opencl_builtin_expected_type) 324 << TheCall->getDirectCallee() << "'ndrange_t'"; 325 return true; 326 } 327 328 Expr *BlockArg = TheCall->getArg(1); 329 if (!isBlockPointer(BlockArg)) { 330 S.Diag(BlockArg->getLocStart(), 331 diag::err_opencl_builtin_expected_type) 332 << TheCall->getDirectCallee() << "block"; 333 return true; 334 } 335 return checkOpenCLBlockArgs(S, BlockArg); 336 } 337 338 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 339 /// get_kernel_work_group_size 340 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 341 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 342 if (checkArgCount(S, TheCall, 1)) 343 return true; 344 345 Expr *BlockArg = TheCall->getArg(0); 346 if (!isBlockPointer(BlockArg)) { 347 S.Diag(BlockArg->getLocStart(), 348 diag::err_opencl_builtin_expected_type) 349 << TheCall->getDirectCallee() << "block"; 350 return true; 351 } 352 return checkOpenCLBlockArgs(S, BlockArg); 353 } 354 355 /// Diagnose integer type and any valid implicit conversion to it. 356 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 357 const QualType &IntType); 358 359 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 360 unsigned Start, unsigned End) { 361 bool IllegalParams = false; 362 for (unsigned I = Start; I <= End; ++I) 363 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 364 S.Context.getSizeType()); 365 return IllegalParams; 366 } 367 368 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 369 /// 'local void*' parameter of passed block. 370 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 371 Expr *BlockArg, 372 unsigned NumNonVarArgs) { 373 const BlockPointerType *BPT = 374 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 375 unsigned NumBlockParams = 376 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 377 unsigned TotalNumArgs = TheCall->getNumArgs(); 378 379 // For each argument passed to the block, a corresponding uint needs to 380 // be passed to describe the size of the local memory. 381 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 382 S.Diag(TheCall->getLocStart(), 383 diag::err_opencl_enqueue_kernel_local_size_args); 384 return true; 385 } 386 387 // Check that the sizes of the local memory are specified by integers. 388 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 389 TotalNumArgs - 1); 390 } 391 392 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 393 /// overload formats specified in Table 6.13.17.1. 394 /// int enqueue_kernel(queue_t queue, 395 /// kernel_enqueue_flags_t flags, 396 /// const ndrange_t ndrange, 397 /// void (^block)(void)) 398 /// int enqueue_kernel(queue_t queue, 399 /// kernel_enqueue_flags_t flags, 400 /// const ndrange_t ndrange, 401 /// uint num_events_in_wait_list, 402 /// clk_event_t *event_wait_list, 403 /// clk_event_t *event_ret, 404 /// void (^block)(void)) 405 /// int enqueue_kernel(queue_t queue, 406 /// kernel_enqueue_flags_t flags, 407 /// const ndrange_t ndrange, 408 /// void (^block)(local void*, ...), 409 /// uint size0, ...) 410 /// int enqueue_kernel(queue_t queue, 411 /// kernel_enqueue_flags_t flags, 412 /// const ndrange_t ndrange, 413 /// uint num_events_in_wait_list, 414 /// clk_event_t *event_wait_list, 415 /// clk_event_t *event_ret, 416 /// void (^block)(local void*, ...), 417 /// uint size0, ...) 418 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 419 unsigned NumArgs = TheCall->getNumArgs(); 420 421 if (NumArgs < 4) { 422 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args); 423 return true; 424 } 425 426 Expr *Arg0 = TheCall->getArg(0); 427 Expr *Arg1 = TheCall->getArg(1); 428 Expr *Arg2 = TheCall->getArg(2); 429 Expr *Arg3 = TheCall->getArg(3); 430 431 // First argument always needs to be a queue_t type. 432 if (!Arg0->getType()->isQueueT()) { 433 S.Diag(TheCall->getArg(0)->getLocStart(), 434 diag::err_opencl_builtin_expected_type) 435 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 436 return true; 437 } 438 439 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 440 if (!Arg1->getType()->isIntegerType()) { 441 S.Diag(TheCall->getArg(1)->getLocStart(), 442 diag::err_opencl_builtin_expected_type) 443 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 444 return true; 445 } 446 447 // Third argument is always an ndrange_t type. 448 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 449 S.Diag(TheCall->getArg(2)->getLocStart(), 450 diag::err_opencl_builtin_expected_type) 451 << TheCall->getDirectCallee() << "'ndrange_t'"; 452 return true; 453 } 454 455 // With four arguments, there is only one form that the function could be 456 // called in: no events and no variable arguments. 457 if (NumArgs == 4) { 458 // check that the last argument is the right block type. 459 if (!isBlockPointer(Arg3)) { 460 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type) 461 << TheCall->getDirectCallee() << "block"; 462 return true; 463 } 464 // we have a block type, check the prototype 465 const BlockPointerType *BPT = 466 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 467 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 468 S.Diag(Arg3->getLocStart(), 469 diag::err_opencl_enqueue_kernel_blocks_no_args); 470 return true; 471 } 472 return false; 473 } 474 // we can have block + varargs. 475 if (isBlockPointer(Arg3)) 476 return (checkOpenCLBlockArgs(S, Arg3) || 477 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 478 // last two cases with either exactly 7 args or 7 args and varargs. 479 if (NumArgs >= 7) { 480 // check common block argument. 481 Expr *Arg6 = TheCall->getArg(6); 482 if (!isBlockPointer(Arg6)) { 483 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type) 484 << TheCall->getDirectCallee() << "block"; 485 return true; 486 } 487 if (checkOpenCLBlockArgs(S, Arg6)) 488 return true; 489 490 // Forth argument has to be any integer type. 491 if (!Arg3->getType()->isIntegerType()) { 492 S.Diag(TheCall->getArg(3)->getLocStart(), 493 diag::err_opencl_builtin_expected_type) 494 << TheCall->getDirectCallee() << "integer"; 495 return true; 496 } 497 // check remaining common arguments. 498 Expr *Arg4 = TheCall->getArg(4); 499 Expr *Arg5 = TheCall->getArg(5); 500 501 // Fifth argument is always passed as a pointer to clk_event_t. 502 if (!Arg4->isNullPointerConstant(S.Context, 503 Expr::NPC_ValueDependentIsNotNull) && 504 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 505 S.Diag(TheCall->getArg(4)->getLocStart(), 506 diag::err_opencl_builtin_expected_type) 507 << TheCall->getDirectCallee() 508 << S.Context.getPointerType(S.Context.OCLClkEventTy); 509 return true; 510 } 511 512 // Sixth argument is always passed as a pointer to clk_event_t. 513 if (!Arg5->isNullPointerConstant(S.Context, 514 Expr::NPC_ValueDependentIsNotNull) && 515 !(Arg5->getType()->isPointerType() && 516 Arg5->getType()->getPointeeType()->isClkEventT())) { 517 S.Diag(TheCall->getArg(5)->getLocStart(), 518 diag::err_opencl_builtin_expected_type) 519 << TheCall->getDirectCallee() 520 << S.Context.getPointerType(S.Context.OCLClkEventTy); 521 return true; 522 } 523 524 if (NumArgs == 7) 525 return false; 526 527 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 528 } 529 530 // None of the specific case has been detected, give generic error 531 S.Diag(TheCall->getLocStart(), 532 diag::err_opencl_enqueue_kernel_incorrect_args); 533 return true; 534 } 535 536 /// Returns OpenCL access qual. 537 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 538 return D->getAttr<OpenCLAccessAttr>(); 539 } 540 541 /// Returns true if pipe element type is different from the pointer. 542 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 543 const Expr *Arg0 = Call->getArg(0); 544 // First argument type should always be pipe. 545 if (!Arg0->getType()->isPipeType()) { 546 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 547 << Call->getDirectCallee() << Arg0->getSourceRange(); 548 return true; 549 } 550 OpenCLAccessAttr *AccessQual = 551 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 552 // Validates the access qualifier is compatible with the call. 553 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 554 // read_only and write_only, and assumed to be read_only if no qualifier is 555 // specified. 556 switch (Call->getDirectCallee()->getBuiltinID()) { 557 case Builtin::BIread_pipe: 558 case Builtin::BIreserve_read_pipe: 559 case Builtin::BIcommit_read_pipe: 560 case Builtin::BIwork_group_reserve_read_pipe: 561 case Builtin::BIsub_group_reserve_read_pipe: 562 case Builtin::BIwork_group_commit_read_pipe: 563 case Builtin::BIsub_group_commit_read_pipe: 564 if (!(!AccessQual || AccessQual->isReadOnly())) { 565 S.Diag(Arg0->getLocStart(), 566 diag::err_opencl_builtin_pipe_invalid_access_modifier) 567 << "read_only" << Arg0->getSourceRange(); 568 return true; 569 } 570 break; 571 case Builtin::BIwrite_pipe: 572 case Builtin::BIreserve_write_pipe: 573 case Builtin::BIcommit_write_pipe: 574 case Builtin::BIwork_group_reserve_write_pipe: 575 case Builtin::BIsub_group_reserve_write_pipe: 576 case Builtin::BIwork_group_commit_write_pipe: 577 case Builtin::BIsub_group_commit_write_pipe: 578 if (!(AccessQual && AccessQual->isWriteOnly())) { 579 S.Diag(Arg0->getLocStart(), 580 diag::err_opencl_builtin_pipe_invalid_access_modifier) 581 << "write_only" << Arg0->getSourceRange(); 582 return true; 583 } 584 break; 585 default: 586 break; 587 } 588 return false; 589 } 590 591 /// Returns true if pipe element type is different from the pointer. 592 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 593 const Expr *Arg0 = Call->getArg(0); 594 const Expr *ArgIdx = Call->getArg(Idx); 595 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 596 const QualType EltTy = PipeTy->getElementType(); 597 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 598 // The Idx argument should be a pointer and the type of the pointer and 599 // the type of pipe element should also be the same. 600 if (!ArgTy || 601 !S.Context.hasSameType( 602 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 603 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 604 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 605 << ArgIdx->getType() << ArgIdx->getSourceRange(); 606 return true; 607 } 608 return false; 609 } 610 611 // \brief Performs semantic analysis for the read/write_pipe call. 612 // \param S Reference to the semantic analyzer. 613 // \param Call A pointer to the builtin call. 614 // \return True if a semantic error has been found, false otherwise. 615 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 616 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 617 // functions have two forms. 618 switch (Call->getNumArgs()) { 619 case 2: { 620 if (checkOpenCLPipeArg(S, Call)) 621 return true; 622 // The call with 2 arguments should be 623 // read/write_pipe(pipe T, T*). 624 // Check packet type T. 625 if (checkOpenCLPipePacketType(S, Call, 1)) 626 return true; 627 } break; 628 629 case 4: { 630 if (checkOpenCLPipeArg(S, Call)) 631 return true; 632 // The call with 4 arguments should be 633 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 634 // Check reserve_id_t. 635 if (!Call->getArg(1)->getType()->isReserveIDT()) { 636 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 637 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 638 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 639 return true; 640 } 641 642 // Check the index. 643 const Expr *Arg2 = Call->getArg(2); 644 if (!Arg2->getType()->isIntegerType() && 645 !Arg2->getType()->isUnsignedIntegerType()) { 646 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 647 << Call->getDirectCallee() << S.Context.UnsignedIntTy 648 << Arg2->getType() << Arg2->getSourceRange(); 649 return true; 650 } 651 652 // Check packet type T. 653 if (checkOpenCLPipePacketType(S, Call, 3)) 654 return true; 655 } break; 656 default: 657 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) 658 << Call->getDirectCallee() << Call->getSourceRange(); 659 return true; 660 } 661 662 return false; 663 } 664 665 // \brief Performs a semantic analysis on the {work_group_/sub_group_ 666 // /_}reserve_{read/write}_pipe 667 // \param S Reference to the semantic analyzer. 668 // \param Call The call to the builtin function to be analyzed. 669 // \return True if a semantic error was found, false otherwise. 670 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 671 if (checkArgCount(S, Call, 2)) 672 return true; 673 674 if (checkOpenCLPipeArg(S, Call)) 675 return true; 676 677 // Check the reserve size. 678 if (!Call->getArg(1)->getType()->isIntegerType() && 679 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 680 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 681 << Call->getDirectCallee() << S.Context.UnsignedIntTy 682 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 683 return true; 684 } 685 686 return false; 687 } 688 689 // \brief Performs a semantic analysis on {work_group_/sub_group_ 690 // /_}commit_{read/write}_pipe 691 // \param S Reference to the semantic analyzer. 692 // \param Call The call to the builtin function to be analyzed. 693 // \return True if a semantic error was found, false otherwise. 694 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 695 if (checkArgCount(S, Call, 2)) 696 return true; 697 698 if (checkOpenCLPipeArg(S, Call)) 699 return true; 700 701 // Check reserve_id_t. 702 if (!Call->getArg(1)->getType()->isReserveIDT()) { 703 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 704 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 705 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 706 return true; 707 } 708 709 return false; 710 } 711 712 // \brief Performs a semantic analysis on the call to built-in Pipe 713 // Query Functions. 714 // \param S Reference to the semantic analyzer. 715 // \param Call The call to the builtin function to be analyzed. 716 // \return True if a semantic error was found, false otherwise. 717 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 718 if (checkArgCount(S, Call, 1)) 719 return true; 720 721 if (!Call->getArg(0)->getType()->isPipeType()) { 722 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 723 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 724 return true; 725 } 726 727 return false; 728 } 729 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions. 730 // \brief Performs semantic analysis for the to_global/local/private call. 731 // \param S Reference to the semantic analyzer. 732 // \param BuiltinID ID of the builtin function. 733 // \param Call A pointer to the builtin call. 734 // \return True if a semantic error has been found, false otherwise. 735 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 736 CallExpr *Call) { 737 if (Call->getNumArgs() != 1) { 738 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 739 << Call->getDirectCallee() << Call->getSourceRange(); 740 return true; 741 } 742 743 auto RT = Call->getArg(0)->getType(); 744 if (!RT->isPointerType() || RT->getPointeeType() 745 .getAddressSpace() == LangAS::opencl_constant) { 746 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 747 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 748 return true; 749 } 750 751 RT = RT->getPointeeType(); 752 auto Qual = RT.getQualifiers(); 753 switch (BuiltinID) { 754 case Builtin::BIto_global: 755 Qual.setAddressSpace(LangAS::opencl_global); 756 break; 757 case Builtin::BIto_local: 758 Qual.setAddressSpace(LangAS::opencl_local); 759 break; 760 default: 761 Qual.removeAddressSpace(); 762 } 763 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 764 RT.getUnqualifiedType(), Qual))); 765 766 return false; 767 } 768 769 ExprResult 770 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 771 CallExpr *TheCall) { 772 ExprResult TheCallResult(TheCall); 773 774 // Find out if any arguments are required to be integer constant expressions. 775 unsigned ICEArguments = 0; 776 ASTContext::GetBuiltinTypeError Error; 777 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 778 if (Error != ASTContext::GE_None) 779 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 780 781 // If any arguments are required to be ICE's, check and diagnose. 782 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 783 // Skip arguments not required to be ICE's. 784 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 785 786 llvm::APSInt Result; 787 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 788 return true; 789 ICEArguments &= ~(1 << ArgNo); 790 } 791 792 switch (BuiltinID) { 793 case Builtin::BI__builtin___CFStringMakeConstantString: 794 assert(TheCall->getNumArgs() == 1 && 795 "Wrong # arguments to builtin CFStringMakeConstantString"); 796 if (CheckObjCString(TheCall->getArg(0))) 797 return ExprError(); 798 break; 799 case Builtin::BI__builtin_ms_va_start: 800 case Builtin::BI__builtin_stdarg_start: 801 case Builtin::BI__builtin_va_start: 802 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 803 return ExprError(); 804 break; 805 case Builtin::BI__va_start: { 806 switch (Context.getTargetInfo().getTriple().getArch()) { 807 case llvm::Triple::arm: 808 case llvm::Triple::thumb: 809 if (SemaBuiltinVAStartARM(TheCall)) 810 return ExprError(); 811 break; 812 default: 813 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 814 return ExprError(); 815 break; 816 } 817 break; 818 } 819 case Builtin::BI__builtin_isgreater: 820 case Builtin::BI__builtin_isgreaterequal: 821 case Builtin::BI__builtin_isless: 822 case Builtin::BI__builtin_islessequal: 823 case Builtin::BI__builtin_islessgreater: 824 case Builtin::BI__builtin_isunordered: 825 if (SemaBuiltinUnorderedCompare(TheCall)) 826 return ExprError(); 827 break; 828 case Builtin::BI__builtin_fpclassify: 829 if (SemaBuiltinFPClassification(TheCall, 6)) 830 return ExprError(); 831 break; 832 case Builtin::BI__builtin_isfinite: 833 case Builtin::BI__builtin_isinf: 834 case Builtin::BI__builtin_isinf_sign: 835 case Builtin::BI__builtin_isnan: 836 case Builtin::BI__builtin_isnormal: 837 if (SemaBuiltinFPClassification(TheCall, 1)) 838 return ExprError(); 839 break; 840 case Builtin::BI__builtin_shufflevector: 841 return SemaBuiltinShuffleVector(TheCall); 842 // TheCall will be freed by the smart pointer here, but that's fine, since 843 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 844 case Builtin::BI__builtin_prefetch: 845 if (SemaBuiltinPrefetch(TheCall)) 846 return ExprError(); 847 break; 848 case Builtin::BI__builtin_alloca_with_align: 849 if (SemaBuiltinAllocaWithAlign(TheCall)) 850 return ExprError(); 851 break; 852 case Builtin::BI__assume: 853 case Builtin::BI__builtin_assume: 854 if (SemaBuiltinAssume(TheCall)) 855 return ExprError(); 856 break; 857 case Builtin::BI__builtin_assume_aligned: 858 if (SemaBuiltinAssumeAligned(TheCall)) 859 return ExprError(); 860 break; 861 case Builtin::BI__builtin_object_size: 862 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 863 return ExprError(); 864 break; 865 case Builtin::BI__builtin_longjmp: 866 if (SemaBuiltinLongjmp(TheCall)) 867 return ExprError(); 868 break; 869 case Builtin::BI__builtin_setjmp: 870 if (SemaBuiltinSetjmp(TheCall)) 871 return ExprError(); 872 break; 873 case Builtin::BI_setjmp: 874 case Builtin::BI_setjmpex: 875 if (checkArgCount(*this, TheCall, 1)) 876 return true; 877 break; 878 879 case Builtin::BI__builtin_classify_type: 880 if (checkArgCount(*this, TheCall, 1)) return true; 881 TheCall->setType(Context.IntTy); 882 break; 883 case Builtin::BI__builtin_constant_p: 884 if (checkArgCount(*this, TheCall, 1)) return true; 885 TheCall->setType(Context.IntTy); 886 break; 887 case Builtin::BI__sync_fetch_and_add: 888 case Builtin::BI__sync_fetch_and_add_1: 889 case Builtin::BI__sync_fetch_and_add_2: 890 case Builtin::BI__sync_fetch_and_add_4: 891 case Builtin::BI__sync_fetch_and_add_8: 892 case Builtin::BI__sync_fetch_and_add_16: 893 case Builtin::BI__sync_fetch_and_sub: 894 case Builtin::BI__sync_fetch_and_sub_1: 895 case Builtin::BI__sync_fetch_and_sub_2: 896 case Builtin::BI__sync_fetch_and_sub_4: 897 case Builtin::BI__sync_fetch_and_sub_8: 898 case Builtin::BI__sync_fetch_and_sub_16: 899 case Builtin::BI__sync_fetch_and_or: 900 case Builtin::BI__sync_fetch_and_or_1: 901 case Builtin::BI__sync_fetch_and_or_2: 902 case Builtin::BI__sync_fetch_and_or_4: 903 case Builtin::BI__sync_fetch_and_or_8: 904 case Builtin::BI__sync_fetch_and_or_16: 905 case Builtin::BI__sync_fetch_and_and: 906 case Builtin::BI__sync_fetch_and_and_1: 907 case Builtin::BI__sync_fetch_and_and_2: 908 case Builtin::BI__sync_fetch_and_and_4: 909 case Builtin::BI__sync_fetch_and_and_8: 910 case Builtin::BI__sync_fetch_and_and_16: 911 case Builtin::BI__sync_fetch_and_xor: 912 case Builtin::BI__sync_fetch_and_xor_1: 913 case Builtin::BI__sync_fetch_and_xor_2: 914 case Builtin::BI__sync_fetch_and_xor_4: 915 case Builtin::BI__sync_fetch_and_xor_8: 916 case Builtin::BI__sync_fetch_and_xor_16: 917 case Builtin::BI__sync_fetch_and_nand: 918 case Builtin::BI__sync_fetch_and_nand_1: 919 case Builtin::BI__sync_fetch_and_nand_2: 920 case Builtin::BI__sync_fetch_and_nand_4: 921 case Builtin::BI__sync_fetch_and_nand_8: 922 case Builtin::BI__sync_fetch_and_nand_16: 923 case Builtin::BI__sync_add_and_fetch: 924 case Builtin::BI__sync_add_and_fetch_1: 925 case Builtin::BI__sync_add_and_fetch_2: 926 case Builtin::BI__sync_add_and_fetch_4: 927 case Builtin::BI__sync_add_and_fetch_8: 928 case Builtin::BI__sync_add_and_fetch_16: 929 case Builtin::BI__sync_sub_and_fetch: 930 case Builtin::BI__sync_sub_and_fetch_1: 931 case Builtin::BI__sync_sub_and_fetch_2: 932 case Builtin::BI__sync_sub_and_fetch_4: 933 case Builtin::BI__sync_sub_and_fetch_8: 934 case Builtin::BI__sync_sub_and_fetch_16: 935 case Builtin::BI__sync_and_and_fetch: 936 case Builtin::BI__sync_and_and_fetch_1: 937 case Builtin::BI__sync_and_and_fetch_2: 938 case Builtin::BI__sync_and_and_fetch_4: 939 case Builtin::BI__sync_and_and_fetch_8: 940 case Builtin::BI__sync_and_and_fetch_16: 941 case Builtin::BI__sync_or_and_fetch: 942 case Builtin::BI__sync_or_and_fetch_1: 943 case Builtin::BI__sync_or_and_fetch_2: 944 case Builtin::BI__sync_or_and_fetch_4: 945 case Builtin::BI__sync_or_and_fetch_8: 946 case Builtin::BI__sync_or_and_fetch_16: 947 case Builtin::BI__sync_xor_and_fetch: 948 case Builtin::BI__sync_xor_and_fetch_1: 949 case Builtin::BI__sync_xor_and_fetch_2: 950 case Builtin::BI__sync_xor_and_fetch_4: 951 case Builtin::BI__sync_xor_and_fetch_8: 952 case Builtin::BI__sync_xor_and_fetch_16: 953 case Builtin::BI__sync_nand_and_fetch: 954 case Builtin::BI__sync_nand_and_fetch_1: 955 case Builtin::BI__sync_nand_and_fetch_2: 956 case Builtin::BI__sync_nand_and_fetch_4: 957 case Builtin::BI__sync_nand_and_fetch_8: 958 case Builtin::BI__sync_nand_and_fetch_16: 959 case Builtin::BI__sync_val_compare_and_swap: 960 case Builtin::BI__sync_val_compare_and_swap_1: 961 case Builtin::BI__sync_val_compare_and_swap_2: 962 case Builtin::BI__sync_val_compare_and_swap_4: 963 case Builtin::BI__sync_val_compare_and_swap_8: 964 case Builtin::BI__sync_val_compare_and_swap_16: 965 case Builtin::BI__sync_bool_compare_and_swap: 966 case Builtin::BI__sync_bool_compare_and_swap_1: 967 case Builtin::BI__sync_bool_compare_and_swap_2: 968 case Builtin::BI__sync_bool_compare_and_swap_4: 969 case Builtin::BI__sync_bool_compare_and_swap_8: 970 case Builtin::BI__sync_bool_compare_and_swap_16: 971 case Builtin::BI__sync_lock_test_and_set: 972 case Builtin::BI__sync_lock_test_and_set_1: 973 case Builtin::BI__sync_lock_test_and_set_2: 974 case Builtin::BI__sync_lock_test_and_set_4: 975 case Builtin::BI__sync_lock_test_and_set_8: 976 case Builtin::BI__sync_lock_test_and_set_16: 977 case Builtin::BI__sync_lock_release: 978 case Builtin::BI__sync_lock_release_1: 979 case Builtin::BI__sync_lock_release_2: 980 case Builtin::BI__sync_lock_release_4: 981 case Builtin::BI__sync_lock_release_8: 982 case Builtin::BI__sync_lock_release_16: 983 case Builtin::BI__sync_swap: 984 case Builtin::BI__sync_swap_1: 985 case Builtin::BI__sync_swap_2: 986 case Builtin::BI__sync_swap_4: 987 case Builtin::BI__sync_swap_8: 988 case Builtin::BI__sync_swap_16: 989 return SemaBuiltinAtomicOverloaded(TheCallResult); 990 case Builtin::BI__builtin_nontemporal_load: 991 case Builtin::BI__builtin_nontemporal_store: 992 return SemaBuiltinNontemporalOverloaded(TheCallResult); 993 #define BUILTIN(ID, TYPE, ATTRS) 994 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 995 case Builtin::BI##ID: \ 996 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 997 #include "clang/Basic/Builtins.def" 998 case Builtin::BI__builtin_annotation: 999 if (SemaBuiltinAnnotation(*this, TheCall)) 1000 return ExprError(); 1001 break; 1002 case Builtin::BI__builtin_addressof: 1003 if (SemaBuiltinAddressof(*this, TheCall)) 1004 return ExprError(); 1005 break; 1006 case Builtin::BI__builtin_add_overflow: 1007 case Builtin::BI__builtin_sub_overflow: 1008 case Builtin::BI__builtin_mul_overflow: 1009 if (SemaBuiltinOverflow(*this, TheCall)) 1010 return ExprError(); 1011 break; 1012 case Builtin::BI__builtin_operator_new: 1013 case Builtin::BI__builtin_operator_delete: 1014 if (!getLangOpts().CPlusPlus) { 1015 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 1016 << (BuiltinID == Builtin::BI__builtin_operator_new 1017 ? "__builtin_operator_new" 1018 : "__builtin_operator_delete") 1019 << "C++"; 1020 return ExprError(); 1021 } 1022 // CodeGen assumes it can find the global new and delete to call, 1023 // so ensure that they are declared. 1024 DeclareGlobalNewDelete(); 1025 break; 1026 1027 // check secure string manipulation functions where overflows 1028 // are detectable at compile time 1029 case Builtin::BI__builtin___memcpy_chk: 1030 case Builtin::BI__builtin___memmove_chk: 1031 case Builtin::BI__builtin___memset_chk: 1032 case Builtin::BI__builtin___strlcat_chk: 1033 case Builtin::BI__builtin___strlcpy_chk: 1034 case Builtin::BI__builtin___strncat_chk: 1035 case Builtin::BI__builtin___strncpy_chk: 1036 case Builtin::BI__builtin___stpncpy_chk: 1037 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 1038 break; 1039 case Builtin::BI__builtin___memccpy_chk: 1040 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 1041 break; 1042 case Builtin::BI__builtin___snprintf_chk: 1043 case Builtin::BI__builtin___vsnprintf_chk: 1044 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 1045 break; 1046 case Builtin::BI__builtin_call_with_static_chain: 1047 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1048 return ExprError(); 1049 break; 1050 case Builtin::BI__exception_code: 1051 case Builtin::BI_exception_code: 1052 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1053 diag::err_seh___except_block)) 1054 return ExprError(); 1055 break; 1056 case Builtin::BI__exception_info: 1057 case Builtin::BI_exception_info: 1058 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1059 diag::err_seh___except_filter)) 1060 return ExprError(); 1061 break; 1062 case Builtin::BI__GetExceptionInfo: 1063 if (checkArgCount(*this, TheCall, 1)) 1064 return ExprError(); 1065 1066 if (CheckCXXThrowOperand( 1067 TheCall->getLocStart(), 1068 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1069 TheCall)) 1070 return ExprError(); 1071 1072 TheCall->setType(Context.VoidPtrTy); 1073 break; 1074 // OpenCL v2.0, s6.13.16 - Pipe functions 1075 case Builtin::BIread_pipe: 1076 case Builtin::BIwrite_pipe: 1077 // Since those two functions are declared with var args, we need a semantic 1078 // check for the argument. 1079 if (SemaBuiltinRWPipe(*this, TheCall)) 1080 return ExprError(); 1081 TheCall->setType(Context.IntTy); 1082 break; 1083 case Builtin::BIreserve_read_pipe: 1084 case Builtin::BIreserve_write_pipe: 1085 case Builtin::BIwork_group_reserve_read_pipe: 1086 case Builtin::BIwork_group_reserve_write_pipe: 1087 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1088 return ExprError(); 1089 // Since return type of reserve_read/write_pipe built-in function is 1090 // reserve_id_t, which is not defined in the builtin def file , we used int 1091 // as return type and need to override the return type of these functions. 1092 TheCall->setType(Context.OCLReserveIDTy); 1093 break; 1094 case Builtin::BIsub_group_reserve_read_pipe: 1095 case Builtin::BIsub_group_reserve_write_pipe: 1096 if (checkOpenCLSubgroupExt(*this, TheCall) || 1097 SemaBuiltinReserveRWPipe(*this, TheCall)) 1098 return ExprError(); 1099 // Since return type of reserve_read/write_pipe built-in function is 1100 // reserve_id_t, which is not defined in the builtin def file , we used int 1101 // as return type and need to override the return type of these functions. 1102 TheCall->setType(Context.OCLReserveIDTy); 1103 break; 1104 case Builtin::BIcommit_read_pipe: 1105 case Builtin::BIcommit_write_pipe: 1106 case Builtin::BIwork_group_commit_read_pipe: 1107 case Builtin::BIwork_group_commit_write_pipe: 1108 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1109 return ExprError(); 1110 break; 1111 case Builtin::BIsub_group_commit_read_pipe: 1112 case Builtin::BIsub_group_commit_write_pipe: 1113 if (checkOpenCLSubgroupExt(*this, TheCall) || 1114 SemaBuiltinCommitRWPipe(*this, TheCall)) 1115 return ExprError(); 1116 break; 1117 case Builtin::BIget_pipe_num_packets: 1118 case Builtin::BIget_pipe_max_packets: 1119 if (SemaBuiltinPipePackets(*this, TheCall)) 1120 return ExprError(); 1121 TheCall->setType(Context.UnsignedIntTy); 1122 break; 1123 case Builtin::BIto_global: 1124 case Builtin::BIto_local: 1125 case Builtin::BIto_private: 1126 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1127 return ExprError(); 1128 break; 1129 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1130 case Builtin::BIenqueue_kernel: 1131 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1132 return ExprError(); 1133 break; 1134 case Builtin::BIget_kernel_work_group_size: 1135 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1136 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1137 return ExprError(); 1138 break; 1139 break; 1140 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1141 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1142 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1143 return ExprError(); 1144 break; 1145 case Builtin::BI__builtin_os_log_format: 1146 case Builtin::BI__builtin_os_log_format_buffer_size: 1147 if (SemaBuiltinOSLogFormat(TheCall)) { 1148 return ExprError(); 1149 } 1150 break; 1151 } 1152 1153 // Since the target specific builtins for each arch overlap, only check those 1154 // of the arch we are compiling for. 1155 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1156 switch (Context.getTargetInfo().getTriple().getArch()) { 1157 case llvm::Triple::arm: 1158 case llvm::Triple::armeb: 1159 case llvm::Triple::thumb: 1160 case llvm::Triple::thumbeb: 1161 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1162 return ExprError(); 1163 break; 1164 case llvm::Triple::aarch64: 1165 case llvm::Triple::aarch64_be: 1166 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1167 return ExprError(); 1168 break; 1169 case llvm::Triple::mips: 1170 case llvm::Triple::mipsel: 1171 case llvm::Triple::mips64: 1172 case llvm::Triple::mips64el: 1173 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1174 return ExprError(); 1175 break; 1176 case llvm::Triple::systemz: 1177 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1178 return ExprError(); 1179 break; 1180 case llvm::Triple::x86: 1181 case llvm::Triple::x86_64: 1182 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1183 return ExprError(); 1184 break; 1185 case llvm::Triple::ppc: 1186 case llvm::Triple::ppc64: 1187 case llvm::Triple::ppc64le: 1188 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1189 return ExprError(); 1190 break; 1191 default: 1192 break; 1193 } 1194 } 1195 1196 return TheCallResult; 1197 } 1198 1199 // Get the valid immediate range for the specified NEON type code. 1200 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1201 NeonTypeFlags Type(t); 1202 int IsQuad = ForceQuad ? true : Type.isQuad(); 1203 switch (Type.getEltType()) { 1204 case NeonTypeFlags::Int8: 1205 case NeonTypeFlags::Poly8: 1206 return shift ? 7 : (8 << IsQuad) - 1; 1207 case NeonTypeFlags::Int16: 1208 case NeonTypeFlags::Poly16: 1209 return shift ? 15 : (4 << IsQuad) - 1; 1210 case NeonTypeFlags::Int32: 1211 return shift ? 31 : (2 << IsQuad) - 1; 1212 case NeonTypeFlags::Int64: 1213 case NeonTypeFlags::Poly64: 1214 return shift ? 63 : (1 << IsQuad) - 1; 1215 case NeonTypeFlags::Poly128: 1216 return shift ? 127 : (1 << IsQuad) - 1; 1217 case NeonTypeFlags::Float16: 1218 assert(!shift && "cannot shift float types!"); 1219 return (4 << IsQuad) - 1; 1220 case NeonTypeFlags::Float32: 1221 assert(!shift && "cannot shift float types!"); 1222 return (2 << IsQuad) - 1; 1223 case NeonTypeFlags::Float64: 1224 assert(!shift && "cannot shift float types!"); 1225 return (1 << IsQuad) - 1; 1226 } 1227 llvm_unreachable("Invalid NeonTypeFlag!"); 1228 } 1229 1230 /// getNeonEltType - Return the QualType corresponding to the elements of 1231 /// the vector type specified by the NeonTypeFlags. This is used to check 1232 /// the pointer arguments for Neon load/store intrinsics. 1233 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1234 bool IsPolyUnsigned, bool IsInt64Long) { 1235 switch (Flags.getEltType()) { 1236 case NeonTypeFlags::Int8: 1237 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1238 case NeonTypeFlags::Int16: 1239 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1240 case NeonTypeFlags::Int32: 1241 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1242 case NeonTypeFlags::Int64: 1243 if (IsInt64Long) 1244 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1245 else 1246 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1247 : Context.LongLongTy; 1248 case NeonTypeFlags::Poly8: 1249 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1250 case NeonTypeFlags::Poly16: 1251 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1252 case NeonTypeFlags::Poly64: 1253 if (IsInt64Long) 1254 return Context.UnsignedLongTy; 1255 else 1256 return Context.UnsignedLongLongTy; 1257 case NeonTypeFlags::Poly128: 1258 break; 1259 case NeonTypeFlags::Float16: 1260 return Context.HalfTy; 1261 case NeonTypeFlags::Float32: 1262 return Context.FloatTy; 1263 case NeonTypeFlags::Float64: 1264 return Context.DoubleTy; 1265 } 1266 llvm_unreachable("Invalid NeonTypeFlag!"); 1267 } 1268 1269 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1270 llvm::APSInt Result; 1271 uint64_t mask = 0; 1272 unsigned TV = 0; 1273 int PtrArgNum = -1; 1274 bool HasConstPtr = false; 1275 switch (BuiltinID) { 1276 #define GET_NEON_OVERLOAD_CHECK 1277 #include "clang/Basic/arm_neon.inc" 1278 #undef GET_NEON_OVERLOAD_CHECK 1279 } 1280 1281 // For NEON intrinsics which are overloaded on vector element type, validate 1282 // the immediate which specifies which variant to emit. 1283 unsigned ImmArg = TheCall->getNumArgs()-1; 1284 if (mask) { 1285 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1286 return true; 1287 1288 TV = Result.getLimitedValue(64); 1289 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1290 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1291 << TheCall->getArg(ImmArg)->getSourceRange(); 1292 } 1293 1294 if (PtrArgNum >= 0) { 1295 // Check that pointer arguments have the specified type. 1296 Expr *Arg = TheCall->getArg(PtrArgNum); 1297 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1298 Arg = ICE->getSubExpr(); 1299 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1300 QualType RHSTy = RHS.get()->getType(); 1301 1302 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1303 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1304 Arch == llvm::Triple::aarch64_be; 1305 bool IsInt64Long = 1306 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1307 QualType EltTy = 1308 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1309 if (HasConstPtr) 1310 EltTy = EltTy.withConst(); 1311 QualType LHSTy = Context.getPointerType(EltTy); 1312 AssignConvertType ConvTy; 1313 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1314 if (RHS.isInvalid()) 1315 return true; 1316 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1317 RHS.get(), AA_Assigning)) 1318 return true; 1319 } 1320 1321 // For NEON intrinsics which take an immediate value as part of the 1322 // instruction, range check them here. 1323 unsigned i = 0, l = 0, u = 0; 1324 switch (BuiltinID) { 1325 default: 1326 return false; 1327 #define GET_NEON_IMMEDIATE_CHECK 1328 #include "clang/Basic/arm_neon.inc" 1329 #undef GET_NEON_IMMEDIATE_CHECK 1330 } 1331 1332 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1333 } 1334 1335 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1336 unsigned MaxWidth) { 1337 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1338 BuiltinID == ARM::BI__builtin_arm_ldaex || 1339 BuiltinID == ARM::BI__builtin_arm_strex || 1340 BuiltinID == ARM::BI__builtin_arm_stlex || 1341 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1342 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1343 BuiltinID == AArch64::BI__builtin_arm_strex || 1344 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1345 "unexpected ARM builtin"); 1346 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1347 BuiltinID == ARM::BI__builtin_arm_ldaex || 1348 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1349 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1350 1351 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1352 1353 // Ensure that we have the proper number of arguments. 1354 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1355 return true; 1356 1357 // Inspect the pointer argument of the atomic builtin. This should always be 1358 // a pointer type, whose element is an integral scalar or pointer type. 1359 // Because it is a pointer type, we don't have to worry about any implicit 1360 // casts here. 1361 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1362 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1363 if (PointerArgRes.isInvalid()) 1364 return true; 1365 PointerArg = PointerArgRes.get(); 1366 1367 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1368 if (!pointerType) { 1369 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1370 << PointerArg->getType() << PointerArg->getSourceRange(); 1371 return true; 1372 } 1373 1374 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1375 // task is to insert the appropriate casts into the AST. First work out just 1376 // what the appropriate type is. 1377 QualType ValType = pointerType->getPointeeType(); 1378 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1379 if (IsLdrex) 1380 AddrType.addConst(); 1381 1382 // Issue a warning if the cast is dodgy. 1383 CastKind CastNeeded = CK_NoOp; 1384 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1385 CastNeeded = CK_BitCast; 1386 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1387 << PointerArg->getType() 1388 << Context.getPointerType(AddrType) 1389 << AA_Passing << PointerArg->getSourceRange(); 1390 } 1391 1392 // Finally, do the cast and replace the argument with the corrected version. 1393 AddrType = Context.getPointerType(AddrType); 1394 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1395 if (PointerArgRes.isInvalid()) 1396 return true; 1397 PointerArg = PointerArgRes.get(); 1398 1399 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1400 1401 // In general, we allow ints, floats and pointers to be loaded and stored. 1402 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1403 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1404 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1405 << PointerArg->getType() << PointerArg->getSourceRange(); 1406 return true; 1407 } 1408 1409 // But ARM doesn't have instructions to deal with 128-bit versions. 1410 if (Context.getTypeSize(ValType) > MaxWidth) { 1411 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1412 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1413 << PointerArg->getType() << PointerArg->getSourceRange(); 1414 return true; 1415 } 1416 1417 switch (ValType.getObjCLifetime()) { 1418 case Qualifiers::OCL_None: 1419 case Qualifiers::OCL_ExplicitNone: 1420 // okay 1421 break; 1422 1423 case Qualifiers::OCL_Weak: 1424 case Qualifiers::OCL_Strong: 1425 case Qualifiers::OCL_Autoreleasing: 1426 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1427 << ValType << PointerArg->getSourceRange(); 1428 return true; 1429 } 1430 1431 if (IsLdrex) { 1432 TheCall->setType(ValType); 1433 return false; 1434 } 1435 1436 // Initialize the argument to be stored. 1437 ExprResult ValArg = TheCall->getArg(0); 1438 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1439 Context, ValType, /*consume*/ false); 1440 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1441 if (ValArg.isInvalid()) 1442 return true; 1443 TheCall->setArg(0, ValArg.get()); 1444 1445 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1446 // but the custom checker bypasses all default analysis. 1447 TheCall->setType(Context.IntTy); 1448 return false; 1449 } 1450 1451 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1452 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1453 BuiltinID == ARM::BI__builtin_arm_ldaex || 1454 BuiltinID == ARM::BI__builtin_arm_strex || 1455 BuiltinID == ARM::BI__builtin_arm_stlex) { 1456 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1457 } 1458 1459 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1460 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1461 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1462 } 1463 1464 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1465 BuiltinID == ARM::BI__builtin_arm_wsr64) 1466 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1467 1468 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1469 BuiltinID == ARM::BI__builtin_arm_rsrp || 1470 BuiltinID == ARM::BI__builtin_arm_wsr || 1471 BuiltinID == ARM::BI__builtin_arm_wsrp) 1472 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1473 1474 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1475 return true; 1476 1477 // For intrinsics which take an immediate value as part of the instruction, 1478 // range check them here. 1479 unsigned i = 0, l = 0, u = 0; 1480 switch (BuiltinID) { 1481 default: return false; 1482 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 1483 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 1484 case ARM::BI__builtin_arm_vcvtr_f: 1485 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 1486 case ARM::BI__builtin_arm_dmb: 1487 case ARM::BI__builtin_arm_dsb: 1488 case ARM::BI__builtin_arm_isb: 1489 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break; 1490 } 1491 1492 // FIXME: VFP Intrinsics should error if VFP not present. 1493 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1494 } 1495 1496 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1497 CallExpr *TheCall) { 1498 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1499 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1500 BuiltinID == AArch64::BI__builtin_arm_strex || 1501 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1502 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1503 } 1504 1505 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1506 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1507 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1508 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1509 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1510 } 1511 1512 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1513 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1514 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1515 1516 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1517 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1518 BuiltinID == AArch64::BI__builtin_arm_wsr || 1519 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1520 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1521 1522 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1523 return true; 1524 1525 // For intrinsics which take an immediate value as part of the instruction, 1526 // range check them here. 1527 unsigned i = 0, l = 0, u = 0; 1528 switch (BuiltinID) { 1529 default: return false; 1530 case AArch64::BI__builtin_arm_dmb: 1531 case AArch64::BI__builtin_arm_dsb: 1532 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1533 } 1534 1535 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1536 } 1537 1538 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1539 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1540 // ordering for DSP is unspecified. MSA is ordered by the data format used 1541 // by the underlying instruction i.e., df/m, df/n and then by size. 1542 // 1543 // FIXME: The size tests here should instead be tablegen'd along with the 1544 // definitions from include/clang/Basic/BuiltinsMips.def. 1545 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1546 // be too. 1547 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1548 unsigned i = 0, l = 0, u = 0, m = 0; 1549 switch (BuiltinID) { 1550 default: return false; 1551 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1552 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1553 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1554 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1555 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1556 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1557 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1558 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1559 // df/m field. 1560 // These intrinsics take an unsigned 3 bit immediate. 1561 case Mips::BI__builtin_msa_bclri_b: 1562 case Mips::BI__builtin_msa_bnegi_b: 1563 case Mips::BI__builtin_msa_bseti_b: 1564 case Mips::BI__builtin_msa_sat_s_b: 1565 case Mips::BI__builtin_msa_sat_u_b: 1566 case Mips::BI__builtin_msa_slli_b: 1567 case Mips::BI__builtin_msa_srai_b: 1568 case Mips::BI__builtin_msa_srari_b: 1569 case Mips::BI__builtin_msa_srli_b: 1570 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1571 case Mips::BI__builtin_msa_binsli_b: 1572 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1573 // These intrinsics take an unsigned 4 bit immediate. 1574 case Mips::BI__builtin_msa_bclri_h: 1575 case Mips::BI__builtin_msa_bnegi_h: 1576 case Mips::BI__builtin_msa_bseti_h: 1577 case Mips::BI__builtin_msa_sat_s_h: 1578 case Mips::BI__builtin_msa_sat_u_h: 1579 case Mips::BI__builtin_msa_slli_h: 1580 case Mips::BI__builtin_msa_srai_h: 1581 case Mips::BI__builtin_msa_srari_h: 1582 case Mips::BI__builtin_msa_srli_h: 1583 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1584 case Mips::BI__builtin_msa_binsli_h: 1585 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 1586 // These intrinsics take an unsigned 5 bit immedate. 1587 // The first block of intrinsics actually have an unsigned 5 bit field, 1588 // not a df/n field. 1589 case Mips::BI__builtin_msa_clei_u_b: 1590 case Mips::BI__builtin_msa_clei_u_h: 1591 case Mips::BI__builtin_msa_clei_u_w: 1592 case Mips::BI__builtin_msa_clei_u_d: 1593 case Mips::BI__builtin_msa_clti_u_b: 1594 case Mips::BI__builtin_msa_clti_u_h: 1595 case Mips::BI__builtin_msa_clti_u_w: 1596 case Mips::BI__builtin_msa_clti_u_d: 1597 case Mips::BI__builtin_msa_maxi_u_b: 1598 case Mips::BI__builtin_msa_maxi_u_h: 1599 case Mips::BI__builtin_msa_maxi_u_w: 1600 case Mips::BI__builtin_msa_maxi_u_d: 1601 case Mips::BI__builtin_msa_mini_u_b: 1602 case Mips::BI__builtin_msa_mini_u_h: 1603 case Mips::BI__builtin_msa_mini_u_w: 1604 case Mips::BI__builtin_msa_mini_u_d: 1605 case Mips::BI__builtin_msa_addvi_b: 1606 case Mips::BI__builtin_msa_addvi_h: 1607 case Mips::BI__builtin_msa_addvi_w: 1608 case Mips::BI__builtin_msa_addvi_d: 1609 case Mips::BI__builtin_msa_bclri_w: 1610 case Mips::BI__builtin_msa_bnegi_w: 1611 case Mips::BI__builtin_msa_bseti_w: 1612 case Mips::BI__builtin_msa_sat_s_w: 1613 case Mips::BI__builtin_msa_sat_u_w: 1614 case Mips::BI__builtin_msa_slli_w: 1615 case Mips::BI__builtin_msa_srai_w: 1616 case Mips::BI__builtin_msa_srari_w: 1617 case Mips::BI__builtin_msa_srli_w: 1618 case Mips::BI__builtin_msa_srlri_w: 1619 case Mips::BI__builtin_msa_subvi_b: 1620 case Mips::BI__builtin_msa_subvi_h: 1621 case Mips::BI__builtin_msa_subvi_w: 1622 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 1623 case Mips::BI__builtin_msa_binsli_w: 1624 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 1625 // These intrinsics take an unsigned 6 bit immediate. 1626 case Mips::BI__builtin_msa_bclri_d: 1627 case Mips::BI__builtin_msa_bnegi_d: 1628 case Mips::BI__builtin_msa_bseti_d: 1629 case Mips::BI__builtin_msa_sat_s_d: 1630 case Mips::BI__builtin_msa_sat_u_d: 1631 case Mips::BI__builtin_msa_slli_d: 1632 case Mips::BI__builtin_msa_srai_d: 1633 case Mips::BI__builtin_msa_srari_d: 1634 case Mips::BI__builtin_msa_srli_d: 1635 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 1636 case Mips::BI__builtin_msa_binsli_d: 1637 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 1638 // These intrinsics take a signed 5 bit immediate. 1639 case Mips::BI__builtin_msa_ceqi_b: 1640 case Mips::BI__builtin_msa_ceqi_h: 1641 case Mips::BI__builtin_msa_ceqi_w: 1642 case Mips::BI__builtin_msa_ceqi_d: 1643 case Mips::BI__builtin_msa_clti_s_b: 1644 case Mips::BI__builtin_msa_clti_s_h: 1645 case Mips::BI__builtin_msa_clti_s_w: 1646 case Mips::BI__builtin_msa_clti_s_d: 1647 case Mips::BI__builtin_msa_clei_s_b: 1648 case Mips::BI__builtin_msa_clei_s_h: 1649 case Mips::BI__builtin_msa_clei_s_w: 1650 case Mips::BI__builtin_msa_clei_s_d: 1651 case Mips::BI__builtin_msa_maxi_s_b: 1652 case Mips::BI__builtin_msa_maxi_s_h: 1653 case Mips::BI__builtin_msa_maxi_s_w: 1654 case Mips::BI__builtin_msa_maxi_s_d: 1655 case Mips::BI__builtin_msa_mini_s_b: 1656 case Mips::BI__builtin_msa_mini_s_h: 1657 case Mips::BI__builtin_msa_mini_s_w: 1658 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 1659 // These intrinsics take an unsigned 8 bit immediate. 1660 case Mips::BI__builtin_msa_andi_b: 1661 case Mips::BI__builtin_msa_nori_b: 1662 case Mips::BI__builtin_msa_ori_b: 1663 case Mips::BI__builtin_msa_shf_b: 1664 case Mips::BI__builtin_msa_shf_h: 1665 case Mips::BI__builtin_msa_shf_w: 1666 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 1667 case Mips::BI__builtin_msa_bseli_b: 1668 case Mips::BI__builtin_msa_bmnzi_b: 1669 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 1670 // df/n format 1671 // These intrinsics take an unsigned 4 bit immediate. 1672 case Mips::BI__builtin_msa_copy_s_b: 1673 case Mips::BI__builtin_msa_copy_u_b: 1674 case Mips::BI__builtin_msa_insve_b: 1675 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 1676 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 1677 // These intrinsics take an unsigned 3 bit immediate. 1678 case Mips::BI__builtin_msa_copy_s_h: 1679 case Mips::BI__builtin_msa_copy_u_h: 1680 case Mips::BI__builtin_msa_insve_h: 1681 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 1682 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 1683 // These intrinsics take an unsigned 2 bit immediate. 1684 case Mips::BI__builtin_msa_copy_s_w: 1685 case Mips::BI__builtin_msa_copy_u_w: 1686 case Mips::BI__builtin_msa_insve_w: 1687 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 1688 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 1689 // These intrinsics take an unsigned 1 bit immediate. 1690 case Mips::BI__builtin_msa_copy_s_d: 1691 case Mips::BI__builtin_msa_copy_u_d: 1692 case Mips::BI__builtin_msa_insve_d: 1693 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 1694 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 1695 // Memory offsets and immediate loads. 1696 // These intrinsics take a signed 10 bit immediate. 1697 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 1698 case Mips::BI__builtin_msa_ldi_h: 1699 case Mips::BI__builtin_msa_ldi_w: 1700 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 1701 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 1702 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 1703 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 1704 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 1705 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 1706 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 1707 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 1708 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 1709 } 1710 1711 if (!m) 1712 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1713 1714 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 1715 SemaBuiltinConstantArgMultiple(TheCall, i, m); 1716 } 1717 1718 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1719 unsigned i = 0, l = 0, u = 0; 1720 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 1721 BuiltinID == PPC::BI__builtin_divdeu || 1722 BuiltinID == PPC::BI__builtin_bpermd; 1723 bool IsTarget64Bit = Context.getTargetInfo() 1724 .getTypeWidth(Context 1725 .getTargetInfo() 1726 .getIntPtrType()) == 64; 1727 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 1728 BuiltinID == PPC::BI__builtin_divweu || 1729 BuiltinID == PPC::BI__builtin_divde || 1730 BuiltinID == PPC::BI__builtin_divdeu; 1731 1732 if (Is64BitBltin && !IsTarget64Bit) 1733 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 1734 << TheCall->getSourceRange(); 1735 1736 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 1737 (BuiltinID == PPC::BI__builtin_bpermd && 1738 !Context.getTargetInfo().hasFeature("bpermd"))) 1739 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 1740 << TheCall->getSourceRange(); 1741 1742 switch (BuiltinID) { 1743 default: return false; 1744 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 1745 case PPC::BI__builtin_altivec_crypto_vshasigmad: 1746 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1747 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1748 case PPC::BI__builtin_tbegin: 1749 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 1750 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 1751 case PPC::BI__builtin_tabortwc: 1752 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 1753 case PPC::BI__builtin_tabortwci: 1754 case PPC::BI__builtin_tabortdci: 1755 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 1756 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 1757 case PPC::BI__builtin_vsx_xxpermdi: 1758 case PPC::BI__builtin_vsx_xxsldwi: 1759 return SemaBuiltinVSX(TheCall); 1760 } 1761 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1762 } 1763 1764 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 1765 CallExpr *TheCall) { 1766 if (BuiltinID == SystemZ::BI__builtin_tabort) { 1767 Expr *Arg = TheCall->getArg(0); 1768 llvm::APSInt AbortCode(32); 1769 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 1770 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 1771 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 1772 << Arg->getSourceRange(); 1773 } 1774 1775 // For intrinsics which take an immediate value as part of the instruction, 1776 // range check them here. 1777 unsigned i = 0, l = 0, u = 0; 1778 switch (BuiltinID) { 1779 default: return false; 1780 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 1781 case SystemZ::BI__builtin_s390_verimb: 1782 case SystemZ::BI__builtin_s390_verimh: 1783 case SystemZ::BI__builtin_s390_verimf: 1784 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 1785 case SystemZ::BI__builtin_s390_vfaeb: 1786 case SystemZ::BI__builtin_s390_vfaeh: 1787 case SystemZ::BI__builtin_s390_vfaef: 1788 case SystemZ::BI__builtin_s390_vfaebs: 1789 case SystemZ::BI__builtin_s390_vfaehs: 1790 case SystemZ::BI__builtin_s390_vfaefs: 1791 case SystemZ::BI__builtin_s390_vfaezb: 1792 case SystemZ::BI__builtin_s390_vfaezh: 1793 case SystemZ::BI__builtin_s390_vfaezf: 1794 case SystemZ::BI__builtin_s390_vfaezbs: 1795 case SystemZ::BI__builtin_s390_vfaezhs: 1796 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 1797 case SystemZ::BI__builtin_s390_vfisb: 1798 case SystemZ::BI__builtin_s390_vfidb: 1799 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 1800 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1801 case SystemZ::BI__builtin_s390_vftcisb: 1802 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 1803 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 1804 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 1805 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 1806 case SystemZ::BI__builtin_s390_vstrcb: 1807 case SystemZ::BI__builtin_s390_vstrch: 1808 case SystemZ::BI__builtin_s390_vstrcf: 1809 case SystemZ::BI__builtin_s390_vstrczb: 1810 case SystemZ::BI__builtin_s390_vstrczh: 1811 case SystemZ::BI__builtin_s390_vstrczf: 1812 case SystemZ::BI__builtin_s390_vstrcbs: 1813 case SystemZ::BI__builtin_s390_vstrchs: 1814 case SystemZ::BI__builtin_s390_vstrcfs: 1815 case SystemZ::BI__builtin_s390_vstrczbs: 1816 case SystemZ::BI__builtin_s390_vstrczhs: 1817 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 1818 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 1819 case SystemZ::BI__builtin_s390_vfminsb: 1820 case SystemZ::BI__builtin_s390_vfmaxsb: 1821 case SystemZ::BI__builtin_s390_vfmindb: 1822 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 1823 } 1824 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1825 } 1826 1827 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 1828 /// This checks that the target supports __builtin_cpu_supports and 1829 /// that the string argument is constant and valid. 1830 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 1831 Expr *Arg = TheCall->getArg(0); 1832 1833 // Check if the argument is a string literal. 1834 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1835 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1836 << Arg->getSourceRange(); 1837 1838 // Check the contents of the string. 1839 StringRef Feature = 1840 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1841 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 1842 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 1843 << Arg->getSourceRange(); 1844 return false; 1845 } 1846 1847 // Check if the rounding mode is legal. 1848 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 1849 // Indicates if this instruction has rounding control or just SAE. 1850 bool HasRC = false; 1851 1852 unsigned ArgNum = 0; 1853 switch (BuiltinID) { 1854 default: 1855 return false; 1856 case X86::BI__builtin_ia32_vcvttsd2si32: 1857 case X86::BI__builtin_ia32_vcvttsd2si64: 1858 case X86::BI__builtin_ia32_vcvttsd2usi32: 1859 case X86::BI__builtin_ia32_vcvttsd2usi64: 1860 case X86::BI__builtin_ia32_vcvttss2si32: 1861 case X86::BI__builtin_ia32_vcvttss2si64: 1862 case X86::BI__builtin_ia32_vcvttss2usi32: 1863 case X86::BI__builtin_ia32_vcvttss2usi64: 1864 ArgNum = 1; 1865 break; 1866 case X86::BI__builtin_ia32_cvtps2pd512_mask: 1867 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 1868 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 1869 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 1870 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 1871 case X86::BI__builtin_ia32_cvttps2dq512_mask: 1872 case X86::BI__builtin_ia32_cvttps2qq512_mask: 1873 case X86::BI__builtin_ia32_cvttps2udq512_mask: 1874 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 1875 case X86::BI__builtin_ia32_exp2pd_mask: 1876 case X86::BI__builtin_ia32_exp2ps_mask: 1877 case X86::BI__builtin_ia32_getexppd512_mask: 1878 case X86::BI__builtin_ia32_getexpps512_mask: 1879 case X86::BI__builtin_ia32_rcp28pd_mask: 1880 case X86::BI__builtin_ia32_rcp28ps_mask: 1881 case X86::BI__builtin_ia32_rsqrt28pd_mask: 1882 case X86::BI__builtin_ia32_rsqrt28ps_mask: 1883 case X86::BI__builtin_ia32_vcomisd: 1884 case X86::BI__builtin_ia32_vcomiss: 1885 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 1886 ArgNum = 3; 1887 break; 1888 case X86::BI__builtin_ia32_cmppd512_mask: 1889 case X86::BI__builtin_ia32_cmpps512_mask: 1890 case X86::BI__builtin_ia32_cmpsd_mask: 1891 case X86::BI__builtin_ia32_cmpss_mask: 1892 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 1893 case X86::BI__builtin_ia32_getexpsd128_round_mask: 1894 case X86::BI__builtin_ia32_getexpss128_round_mask: 1895 case X86::BI__builtin_ia32_maxpd512_mask: 1896 case X86::BI__builtin_ia32_maxps512_mask: 1897 case X86::BI__builtin_ia32_maxsd_round_mask: 1898 case X86::BI__builtin_ia32_maxss_round_mask: 1899 case X86::BI__builtin_ia32_minpd512_mask: 1900 case X86::BI__builtin_ia32_minps512_mask: 1901 case X86::BI__builtin_ia32_minsd_round_mask: 1902 case X86::BI__builtin_ia32_minss_round_mask: 1903 case X86::BI__builtin_ia32_rcp28sd_round_mask: 1904 case X86::BI__builtin_ia32_rcp28ss_round_mask: 1905 case X86::BI__builtin_ia32_reducepd512_mask: 1906 case X86::BI__builtin_ia32_reduceps512_mask: 1907 case X86::BI__builtin_ia32_rndscalepd_mask: 1908 case X86::BI__builtin_ia32_rndscaleps_mask: 1909 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 1910 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 1911 ArgNum = 4; 1912 break; 1913 case X86::BI__builtin_ia32_fixupimmpd512_mask: 1914 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 1915 case X86::BI__builtin_ia32_fixupimmps512_mask: 1916 case X86::BI__builtin_ia32_fixupimmps512_maskz: 1917 case X86::BI__builtin_ia32_fixupimmsd_mask: 1918 case X86::BI__builtin_ia32_fixupimmsd_maskz: 1919 case X86::BI__builtin_ia32_fixupimmss_mask: 1920 case X86::BI__builtin_ia32_fixupimmss_maskz: 1921 case X86::BI__builtin_ia32_rangepd512_mask: 1922 case X86::BI__builtin_ia32_rangeps512_mask: 1923 case X86::BI__builtin_ia32_rangesd128_round_mask: 1924 case X86::BI__builtin_ia32_rangess128_round_mask: 1925 case X86::BI__builtin_ia32_reducesd_mask: 1926 case X86::BI__builtin_ia32_reducess_mask: 1927 case X86::BI__builtin_ia32_rndscalesd_round_mask: 1928 case X86::BI__builtin_ia32_rndscaless_round_mask: 1929 ArgNum = 5; 1930 break; 1931 case X86::BI__builtin_ia32_vcvtsd2si64: 1932 case X86::BI__builtin_ia32_vcvtsd2si32: 1933 case X86::BI__builtin_ia32_vcvtsd2usi32: 1934 case X86::BI__builtin_ia32_vcvtsd2usi64: 1935 case X86::BI__builtin_ia32_vcvtss2si32: 1936 case X86::BI__builtin_ia32_vcvtss2si64: 1937 case X86::BI__builtin_ia32_vcvtss2usi32: 1938 case X86::BI__builtin_ia32_vcvtss2usi64: 1939 ArgNum = 1; 1940 HasRC = true; 1941 break; 1942 case X86::BI__builtin_ia32_cvtsi2sd64: 1943 case X86::BI__builtin_ia32_cvtsi2ss32: 1944 case X86::BI__builtin_ia32_cvtsi2ss64: 1945 case X86::BI__builtin_ia32_cvtusi2sd64: 1946 case X86::BI__builtin_ia32_cvtusi2ss32: 1947 case X86::BI__builtin_ia32_cvtusi2ss64: 1948 ArgNum = 2; 1949 HasRC = true; 1950 break; 1951 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 1952 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 1953 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 1954 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 1955 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 1956 case X86::BI__builtin_ia32_cvtps2qq512_mask: 1957 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 1958 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 1959 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 1960 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 1961 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 1962 case X86::BI__builtin_ia32_sqrtpd512_mask: 1963 case X86::BI__builtin_ia32_sqrtps512_mask: 1964 ArgNum = 3; 1965 HasRC = true; 1966 break; 1967 case X86::BI__builtin_ia32_addpd512_mask: 1968 case X86::BI__builtin_ia32_addps512_mask: 1969 case X86::BI__builtin_ia32_divpd512_mask: 1970 case X86::BI__builtin_ia32_divps512_mask: 1971 case X86::BI__builtin_ia32_mulpd512_mask: 1972 case X86::BI__builtin_ia32_mulps512_mask: 1973 case X86::BI__builtin_ia32_subpd512_mask: 1974 case X86::BI__builtin_ia32_subps512_mask: 1975 case X86::BI__builtin_ia32_addss_round_mask: 1976 case X86::BI__builtin_ia32_addsd_round_mask: 1977 case X86::BI__builtin_ia32_divss_round_mask: 1978 case X86::BI__builtin_ia32_divsd_round_mask: 1979 case X86::BI__builtin_ia32_mulss_round_mask: 1980 case X86::BI__builtin_ia32_mulsd_round_mask: 1981 case X86::BI__builtin_ia32_subss_round_mask: 1982 case X86::BI__builtin_ia32_subsd_round_mask: 1983 case X86::BI__builtin_ia32_scalefpd512_mask: 1984 case X86::BI__builtin_ia32_scalefps512_mask: 1985 case X86::BI__builtin_ia32_scalefsd_round_mask: 1986 case X86::BI__builtin_ia32_scalefss_round_mask: 1987 case X86::BI__builtin_ia32_getmantpd512_mask: 1988 case X86::BI__builtin_ia32_getmantps512_mask: 1989 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 1990 case X86::BI__builtin_ia32_sqrtsd_round_mask: 1991 case X86::BI__builtin_ia32_sqrtss_round_mask: 1992 case X86::BI__builtin_ia32_vfmaddpd512_mask: 1993 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 1994 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 1995 case X86::BI__builtin_ia32_vfmaddps512_mask: 1996 case X86::BI__builtin_ia32_vfmaddps512_mask3: 1997 case X86::BI__builtin_ia32_vfmaddps512_maskz: 1998 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 1999 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 2000 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 2001 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 2002 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 2003 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 2004 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 2005 case X86::BI__builtin_ia32_vfmsubps512_mask3: 2006 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 2007 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 2008 case X86::BI__builtin_ia32_vfnmaddpd512_mask: 2009 case X86::BI__builtin_ia32_vfnmaddps512_mask: 2010 case X86::BI__builtin_ia32_vfnmsubpd512_mask: 2011 case X86::BI__builtin_ia32_vfnmsubpd512_mask3: 2012 case X86::BI__builtin_ia32_vfnmsubps512_mask: 2013 case X86::BI__builtin_ia32_vfnmsubps512_mask3: 2014 case X86::BI__builtin_ia32_vfmaddsd3_mask: 2015 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 2016 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 2017 case X86::BI__builtin_ia32_vfmaddss3_mask: 2018 case X86::BI__builtin_ia32_vfmaddss3_maskz: 2019 case X86::BI__builtin_ia32_vfmaddss3_mask3: 2020 ArgNum = 4; 2021 HasRC = true; 2022 break; 2023 case X86::BI__builtin_ia32_getmantsd_round_mask: 2024 case X86::BI__builtin_ia32_getmantss_round_mask: 2025 ArgNum = 5; 2026 HasRC = true; 2027 break; 2028 } 2029 2030 llvm::APSInt Result; 2031 2032 // We can't check the value of a dependent argument. 2033 Expr *Arg = TheCall->getArg(ArgNum); 2034 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2035 return false; 2036 2037 // Check constant-ness first. 2038 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2039 return true; 2040 2041 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 2042 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 2043 // combined with ROUND_NO_EXC. 2044 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 2045 Result == 8/*ROUND_NO_EXC*/ || 2046 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 2047 return false; 2048 2049 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 2050 << Arg->getSourceRange(); 2051 } 2052 2053 // Check if the gather/scatter scale is legal. 2054 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 2055 CallExpr *TheCall) { 2056 unsigned ArgNum = 0; 2057 switch (BuiltinID) { 2058 default: 2059 return false; 2060 case X86::BI__builtin_ia32_gatherpfdpd: 2061 case X86::BI__builtin_ia32_gatherpfdps: 2062 case X86::BI__builtin_ia32_gatherpfqpd: 2063 case X86::BI__builtin_ia32_gatherpfqps: 2064 case X86::BI__builtin_ia32_scatterpfdpd: 2065 case X86::BI__builtin_ia32_scatterpfdps: 2066 case X86::BI__builtin_ia32_scatterpfqpd: 2067 case X86::BI__builtin_ia32_scatterpfqps: 2068 ArgNum = 3; 2069 break; 2070 case X86::BI__builtin_ia32_gatherd_pd: 2071 case X86::BI__builtin_ia32_gatherd_pd256: 2072 case X86::BI__builtin_ia32_gatherq_pd: 2073 case X86::BI__builtin_ia32_gatherq_pd256: 2074 case X86::BI__builtin_ia32_gatherd_ps: 2075 case X86::BI__builtin_ia32_gatherd_ps256: 2076 case X86::BI__builtin_ia32_gatherq_ps: 2077 case X86::BI__builtin_ia32_gatherq_ps256: 2078 case X86::BI__builtin_ia32_gatherd_q: 2079 case X86::BI__builtin_ia32_gatherd_q256: 2080 case X86::BI__builtin_ia32_gatherq_q: 2081 case X86::BI__builtin_ia32_gatherq_q256: 2082 case X86::BI__builtin_ia32_gatherd_d: 2083 case X86::BI__builtin_ia32_gatherd_d256: 2084 case X86::BI__builtin_ia32_gatherq_d: 2085 case X86::BI__builtin_ia32_gatherq_d256: 2086 case X86::BI__builtin_ia32_gather3div2df: 2087 case X86::BI__builtin_ia32_gather3div2di: 2088 case X86::BI__builtin_ia32_gather3div4df: 2089 case X86::BI__builtin_ia32_gather3div4di: 2090 case X86::BI__builtin_ia32_gather3div4sf: 2091 case X86::BI__builtin_ia32_gather3div4si: 2092 case X86::BI__builtin_ia32_gather3div8sf: 2093 case X86::BI__builtin_ia32_gather3div8si: 2094 case X86::BI__builtin_ia32_gather3siv2df: 2095 case X86::BI__builtin_ia32_gather3siv2di: 2096 case X86::BI__builtin_ia32_gather3siv4df: 2097 case X86::BI__builtin_ia32_gather3siv4di: 2098 case X86::BI__builtin_ia32_gather3siv4sf: 2099 case X86::BI__builtin_ia32_gather3siv4si: 2100 case X86::BI__builtin_ia32_gather3siv8sf: 2101 case X86::BI__builtin_ia32_gather3siv8si: 2102 case X86::BI__builtin_ia32_gathersiv8df: 2103 case X86::BI__builtin_ia32_gathersiv16sf: 2104 case X86::BI__builtin_ia32_gatherdiv8df: 2105 case X86::BI__builtin_ia32_gatherdiv16sf: 2106 case X86::BI__builtin_ia32_gathersiv8di: 2107 case X86::BI__builtin_ia32_gathersiv16si: 2108 case X86::BI__builtin_ia32_gatherdiv8di: 2109 case X86::BI__builtin_ia32_gatherdiv16si: 2110 case X86::BI__builtin_ia32_scatterdiv2df: 2111 case X86::BI__builtin_ia32_scatterdiv2di: 2112 case X86::BI__builtin_ia32_scatterdiv4df: 2113 case X86::BI__builtin_ia32_scatterdiv4di: 2114 case X86::BI__builtin_ia32_scatterdiv4sf: 2115 case X86::BI__builtin_ia32_scatterdiv4si: 2116 case X86::BI__builtin_ia32_scatterdiv8sf: 2117 case X86::BI__builtin_ia32_scatterdiv8si: 2118 case X86::BI__builtin_ia32_scattersiv2df: 2119 case X86::BI__builtin_ia32_scattersiv2di: 2120 case X86::BI__builtin_ia32_scattersiv4df: 2121 case X86::BI__builtin_ia32_scattersiv4di: 2122 case X86::BI__builtin_ia32_scattersiv4sf: 2123 case X86::BI__builtin_ia32_scattersiv4si: 2124 case X86::BI__builtin_ia32_scattersiv8sf: 2125 case X86::BI__builtin_ia32_scattersiv8si: 2126 case X86::BI__builtin_ia32_scattersiv8df: 2127 case X86::BI__builtin_ia32_scattersiv16sf: 2128 case X86::BI__builtin_ia32_scatterdiv8df: 2129 case X86::BI__builtin_ia32_scatterdiv16sf: 2130 case X86::BI__builtin_ia32_scattersiv8di: 2131 case X86::BI__builtin_ia32_scattersiv16si: 2132 case X86::BI__builtin_ia32_scatterdiv8di: 2133 case X86::BI__builtin_ia32_scatterdiv16si: 2134 ArgNum = 4; 2135 break; 2136 } 2137 2138 llvm::APSInt Result; 2139 2140 // We can't check the value of a dependent argument. 2141 Expr *Arg = TheCall->getArg(ArgNum); 2142 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2143 return false; 2144 2145 // Check constant-ness first. 2146 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2147 return true; 2148 2149 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 2150 return false; 2151 2152 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale) 2153 << Arg->getSourceRange(); 2154 } 2155 2156 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2157 if (BuiltinID == X86::BI__builtin_cpu_supports) 2158 return SemaBuiltinCpuSupports(*this, TheCall); 2159 2160 // If the intrinsic has rounding or SAE make sure its valid. 2161 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 2162 return true; 2163 2164 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 2165 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 2166 return true; 2167 2168 // For intrinsics which take an immediate value as part of the instruction, 2169 // range check them here. 2170 int i = 0, l = 0, u = 0; 2171 switch (BuiltinID) { 2172 default: 2173 return false; 2174 case X86::BI_mm_prefetch: 2175 i = 1; l = 0; u = 3; 2176 break; 2177 case X86::BI__builtin_ia32_sha1rnds4: 2178 case X86::BI__builtin_ia32_shuf_f32x4_256_mask: 2179 case X86::BI__builtin_ia32_shuf_f64x2_256_mask: 2180 case X86::BI__builtin_ia32_shuf_i32x4_256_mask: 2181 case X86::BI__builtin_ia32_shuf_i64x2_256_mask: 2182 i = 2; l = 0; u = 3; 2183 break; 2184 case X86::BI__builtin_ia32_vpermil2pd: 2185 case X86::BI__builtin_ia32_vpermil2pd256: 2186 case X86::BI__builtin_ia32_vpermil2ps: 2187 case X86::BI__builtin_ia32_vpermil2ps256: 2188 i = 3; l = 0; u = 3; 2189 break; 2190 case X86::BI__builtin_ia32_cmpb128_mask: 2191 case X86::BI__builtin_ia32_cmpw128_mask: 2192 case X86::BI__builtin_ia32_cmpd128_mask: 2193 case X86::BI__builtin_ia32_cmpq128_mask: 2194 case X86::BI__builtin_ia32_cmpb256_mask: 2195 case X86::BI__builtin_ia32_cmpw256_mask: 2196 case X86::BI__builtin_ia32_cmpd256_mask: 2197 case X86::BI__builtin_ia32_cmpq256_mask: 2198 case X86::BI__builtin_ia32_cmpb512_mask: 2199 case X86::BI__builtin_ia32_cmpw512_mask: 2200 case X86::BI__builtin_ia32_cmpd512_mask: 2201 case X86::BI__builtin_ia32_cmpq512_mask: 2202 case X86::BI__builtin_ia32_ucmpb128_mask: 2203 case X86::BI__builtin_ia32_ucmpw128_mask: 2204 case X86::BI__builtin_ia32_ucmpd128_mask: 2205 case X86::BI__builtin_ia32_ucmpq128_mask: 2206 case X86::BI__builtin_ia32_ucmpb256_mask: 2207 case X86::BI__builtin_ia32_ucmpw256_mask: 2208 case X86::BI__builtin_ia32_ucmpd256_mask: 2209 case X86::BI__builtin_ia32_ucmpq256_mask: 2210 case X86::BI__builtin_ia32_ucmpb512_mask: 2211 case X86::BI__builtin_ia32_ucmpw512_mask: 2212 case X86::BI__builtin_ia32_ucmpd512_mask: 2213 case X86::BI__builtin_ia32_ucmpq512_mask: 2214 case X86::BI__builtin_ia32_vpcomub: 2215 case X86::BI__builtin_ia32_vpcomuw: 2216 case X86::BI__builtin_ia32_vpcomud: 2217 case X86::BI__builtin_ia32_vpcomuq: 2218 case X86::BI__builtin_ia32_vpcomb: 2219 case X86::BI__builtin_ia32_vpcomw: 2220 case X86::BI__builtin_ia32_vpcomd: 2221 case X86::BI__builtin_ia32_vpcomq: 2222 i = 2; l = 0; u = 7; 2223 break; 2224 case X86::BI__builtin_ia32_roundps: 2225 case X86::BI__builtin_ia32_roundpd: 2226 case X86::BI__builtin_ia32_roundps256: 2227 case X86::BI__builtin_ia32_roundpd256: 2228 i = 1; l = 0; u = 15; 2229 break; 2230 case X86::BI__builtin_ia32_roundss: 2231 case X86::BI__builtin_ia32_roundsd: 2232 case X86::BI__builtin_ia32_rangepd128_mask: 2233 case X86::BI__builtin_ia32_rangepd256_mask: 2234 case X86::BI__builtin_ia32_rangepd512_mask: 2235 case X86::BI__builtin_ia32_rangeps128_mask: 2236 case X86::BI__builtin_ia32_rangeps256_mask: 2237 case X86::BI__builtin_ia32_rangeps512_mask: 2238 case X86::BI__builtin_ia32_getmantsd_round_mask: 2239 case X86::BI__builtin_ia32_getmantss_round_mask: 2240 i = 2; l = 0; u = 15; 2241 break; 2242 case X86::BI__builtin_ia32_cmpps: 2243 case X86::BI__builtin_ia32_cmpss: 2244 case X86::BI__builtin_ia32_cmppd: 2245 case X86::BI__builtin_ia32_cmpsd: 2246 case X86::BI__builtin_ia32_cmpps256: 2247 case X86::BI__builtin_ia32_cmppd256: 2248 case X86::BI__builtin_ia32_cmpps128_mask: 2249 case X86::BI__builtin_ia32_cmppd128_mask: 2250 case X86::BI__builtin_ia32_cmpps256_mask: 2251 case X86::BI__builtin_ia32_cmppd256_mask: 2252 case X86::BI__builtin_ia32_cmpps512_mask: 2253 case X86::BI__builtin_ia32_cmppd512_mask: 2254 case X86::BI__builtin_ia32_cmpsd_mask: 2255 case X86::BI__builtin_ia32_cmpss_mask: 2256 i = 2; l = 0; u = 31; 2257 break; 2258 case X86::BI__builtin_ia32_xabort: 2259 i = 0; l = -128; u = 255; 2260 break; 2261 case X86::BI__builtin_ia32_pshufw: 2262 case X86::BI__builtin_ia32_aeskeygenassist128: 2263 i = 1; l = -128; u = 255; 2264 break; 2265 case X86::BI__builtin_ia32_vcvtps2ph: 2266 case X86::BI__builtin_ia32_vcvtps2ph256: 2267 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2268 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2269 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2270 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2271 case X86::BI__builtin_ia32_rndscaleps_mask: 2272 case X86::BI__builtin_ia32_rndscalepd_mask: 2273 case X86::BI__builtin_ia32_reducepd128_mask: 2274 case X86::BI__builtin_ia32_reducepd256_mask: 2275 case X86::BI__builtin_ia32_reducepd512_mask: 2276 case X86::BI__builtin_ia32_reduceps128_mask: 2277 case X86::BI__builtin_ia32_reduceps256_mask: 2278 case X86::BI__builtin_ia32_reduceps512_mask: 2279 case X86::BI__builtin_ia32_prold512_mask: 2280 case X86::BI__builtin_ia32_prolq512_mask: 2281 case X86::BI__builtin_ia32_prold128_mask: 2282 case X86::BI__builtin_ia32_prold256_mask: 2283 case X86::BI__builtin_ia32_prolq128_mask: 2284 case X86::BI__builtin_ia32_prolq256_mask: 2285 case X86::BI__builtin_ia32_prord128_mask: 2286 case X86::BI__builtin_ia32_prord256_mask: 2287 case X86::BI__builtin_ia32_prorq128_mask: 2288 case X86::BI__builtin_ia32_prorq256_mask: 2289 case X86::BI__builtin_ia32_fpclasspd128_mask: 2290 case X86::BI__builtin_ia32_fpclasspd256_mask: 2291 case X86::BI__builtin_ia32_fpclassps128_mask: 2292 case X86::BI__builtin_ia32_fpclassps256_mask: 2293 case X86::BI__builtin_ia32_fpclassps512_mask: 2294 case X86::BI__builtin_ia32_fpclasspd512_mask: 2295 case X86::BI__builtin_ia32_fpclasssd_mask: 2296 case X86::BI__builtin_ia32_fpclassss_mask: 2297 i = 1; l = 0; u = 255; 2298 break; 2299 case X86::BI__builtin_ia32_palignr: 2300 case X86::BI__builtin_ia32_insertps128: 2301 case X86::BI__builtin_ia32_dpps: 2302 case X86::BI__builtin_ia32_dppd: 2303 case X86::BI__builtin_ia32_dpps256: 2304 case X86::BI__builtin_ia32_mpsadbw128: 2305 case X86::BI__builtin_ia32_mpsadbw256: 2306 case X86::BI__builtin_ia32_pcmpistrm128: 2307 case X86::BI__builtin_ia32_pcmpistri128: 2308 case X86::BI__builtin_ia32_pcmpistria128: 2309 case X86::BI__builtin_ia32_pcmpistric128: 2310 case X86::BI__builtin_ia32_pcmpistrio128: 2311 case X86::BI__builtin_ia32_pcmpistris128: 2312 case X86::BI__builtin_ia32_pcmpistriz128: 2313 case X86::BI__builtin_ia32_pclmulqdq128: 2314 case X86::BI__builtin_ia32_vperm2f128_pd256: 2315 case X86::BI__builtin_ia32_vperm2f128_ps256: 2316 case X86::BI__builtin_ia32_vperm2f128_si256: 2317 case X86::BI__builtin_ia32_permti256: 2318 i = 2; l = -128; u = 255; 2319 break; 2320 case X86::BI__builtin_ia32_palignr128: 2321 case X86::BI__builtin_ia32_palignr256: 2322 case X86::BI__builtin_ia32_palignr512_mask: 2323 case X86::BI__builtin_ia32_vcomisd: 2324 case X86::BI__builtin_ia32_vcomiss: 2325 case X86::BI__builtin_ia32_shuf_f32x4_mask: 2326 case X86::BI__builtin_ia32_shuf_f64x2_mask: 2327 case X86::BI__builtin_ia32_shuf_i32x4_mask: 2328 case X86::BI__builtin_ia32_shuf_i64x2_mask: 2329 case X86::BI__builtin_ia32_dbpsadbw128_mask: 2330 case X86::BI__builtin_ia32_dbpsadbw256_mask: 2331 case X86::BI__builtin_ia32_dbpsadbw512_mask: 2332 i = 2; l = 0; u = 255; 2333 break; 2334 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2335 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2336 case X86::BI__builtin_ia32_fixupimmps512_mask: 2337 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2338 case X86::BI__builtin_ia32_fixupimmsd_mask: 2339 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2340 case X86::BI__builtin_ia32_fixupimmss_mask: 2341 case X86::BI__builtin_ia32_fixupimmss_maskz: 2342 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2343 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2344 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2345 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2346 case X86::BI__builtin_ia32_fixupimmps128_mask: 2347 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2348 case X86::BI__builtin_ia32_fixupimmps256_mask: 2349 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2350 case X86::BI__builtin_ia32_pternlogd512_mask: 2351 case X86::BI__builtin_ia32_pternlogd512_maskz: 2352 case X86::BI__builtin_ia32_pternlogq512_mask: 2353 case X86::BI__builtin_ia32_pternlogq512_maskz: 2354 case X86::BI__builtin_ia32_pternlogd128_mask: 2355 case X86::BI__builtin_ia32_pternlogd128_maskz: 2356 case X86::BI__builtin_ia32_pternlogd256_mask: 2357 case X86::BI__builtin_ia32_pternlogd256_maskz: 2358 case X86::BI__builtin_ia32_pternlogq128_mask: 2359 case X86::BI__builtin_ia32_pternlogq128_maskz: 2360 case X86::BI__builtin_ia32_pternlogq256_mask: 2361 case X86::BI__builtin_ia32_pternlogq256_maskz: 2362 i = 3; l = 0; u = 255; 2363 break; 2364 case X86::BI__builtin_ia32_gatherpfdpd: 2365 case X86::BI__builtin_ia32_gatherpfdps: 2366 case X86::BI__builtin_ia32_gatherpfqpd: 2367 case X86::BI__builtin_ia32_gatherpfqps: 2368 case X86::BI__builtin_ia32_scatterpfdpd: 2369 case X86::BI__builtin_ia32_scatterpfdps: 2370 case X86::BI__builtin_ia32_scatterpfqpd: 2371 case X86::BI__builtin_ia32_scatterpfqps: 2372 i = 4; l = 2; u = 3; 2373 break; 2374 case X86::BI__builtin_ia32_pcmpestrm128: 2375 case X86::BI__builtin_ia32_pcmpestri128: 2376 case X86::BI__builtin_ia32_pcmpestria128: 2377 case X86::BI__builtin_ia32_pcmpestric128: 2378 case X86::BI__builtin_ia32_pcmpestrio128: 2379 case X86::BI__builtin_ia32_pcmpestris128: 2380 case X86::BI__builtin_ia32_pcmpestriz128: 2381 i = 4; l = -128; u = 255; 2382 break; 2383 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2384 case X86::BI__builtin_ia32_rndscaless_round_mask: 2385 i = 4; l = 0; u = 255; 2386 break; 2387 } 2388 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2389 } 2390 2391 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2392 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2393 /// Returns true when the format fits the function and the FormatStringInfo has 2394 /// been populated. 2395 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2396 FormatStringInfo *FSI) { 2397 FSI->HasVAListArg = Format->getFirstArg() == 0; 2398 FSI->FormatIdx = Format->getFormatIdx() - 1; 2399 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2400 2401 // The way the format attribute works in GCC, the implicit this argument 2402 // of member functions is counted. However, it doesn't appear in our own 2403 // lists, so decrement format_idx in that case. 2404 if (IsCXXMember) { 2405 if(FSI->FormatIdx == 0) 2406 return false; 2407 --FSI->FormatIdx; 2408 if (FSI->FirstDataArg != 0) 2409 --FSI->FirstDataArg; 2410 } 2411 return true; 2412 } 2413 2414 /// Checks if a the given expression evaluates to null. 2415 /// 2416 /// \brief Returns true if the value evaluates to null. 2417 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2418 // If the expression has non-null type, it doesn't evaluate to null. 2419 if (auto nullability 2420 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2421 if (*nullability == NullabilityKind::NonNull) 2422 return false; 2423 } 2424 2425 // As a special case, transparent unions initialized with zero are 2426 // considered null for the purposes of the nonnull attribute. 2427 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2428 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2429 if (const CompoundLiteralExpr *CLE = 2430 dyn_cast<CompoundLiteralExpr>(Expr)) 2431 if (const InitListExpr *ILE = 2432 dyn_cast<InitListExpr>(CLE->getInitializer())) 2433 Expr = ILE->getInit(0); 2434 } 2435 2436 bool Result; 2437 return (!Expr->isValueDependent() && 2438 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2439 !Result); 2440 } 2441 2442 static void CheckNonNullArgument(Sema &S, 2443 const Expr *ArgExpr, 2444 SourceLocation CallSiteLoc) { 2445 if (CheckNonNullExpr(S, ArgExpr)) 2446 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2447 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2448 } 2449 2450 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2451 FormatStringInfo FSI; 2452 if ((GetFormatStringType(Format) == FST_NSString) && 2453 getFormatStringInfo(Format, false, &FSI)) { 2454 Idx = FSI.FormatIdx; 2455 return true; 2456 } 2457 return false; 2458 } 2459 /// \brief Diagnose use of %s directive in an NSString which is being passed 2460 /// as formatting string to formatting method. 2461 static void 2462 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 2463 const NamedDecl *FDecl, 2464 Expr **Args, 2465 unsigned NumArgs) { 2466 unsigned Idx = 0; 2467 bool Format = false; 2468 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 2469 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 2470 Idx = 2; 2471 Format = true; 2472 } 2473 else 2474 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2475 if (S.GetFormatNSStringIdx(I, Idx)) { 2476 Format = true; 2477 break; 2478 } 2479 } 2480 if (!Format || NumArgs <= Idx) 2481 return; 2482 const Expr *FormatExpr = Args[Idx]; 2483 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2484 FormatExpr = CSCE->getSubExpr(); 2485 const StringLiteral *FormatString; 2486 if (const ObjCStringLiteral *OSL = 2487 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2488 FormatString = OSL->getString(); 2489 else 2490 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2491 if (!FormatString) 2492 return; 2493 if (S.FormatStringHasSArg(FormatString)) { 2494 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2495 << "%s" << 1 << 1; 2496 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2497 << FDecl->getDeclName(); 2498 } 2499 } 2500 2501 /// Determine whether the given type has a non-null nullability annotation. 2502 static bool isNonNullType(ASTContext &ctx, QualType type) { 2503 if (auto nullability = type->getNullability(ctx)) 2504 return *nullability == NullabilityKind::NonNull; 2505 2506 return false; 2507 } 2508 2509 static void CheckNonNullArguments(Sema &S, 2510 const NamedDecl *FDecl, 2511 const FunctionProtoType *Proto, 2512 ArrayRef<const Expr *> Args, 2513 SourceLocation CallSiteLoc) { 2514 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2515 2516 // Check the attributes attached to the method/function itself. 2517 llvm::SmallBitVector NonNullArgs; 2518 if (FDecl) { 2519 // Handle the nonnull attribute on the function/method declaration itself. 2520 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2521 if (!NonNull->args_size()) { 2522 // Easy case: all pointer arguments are nonnull. 2523 for (const auto *Arg : Args) 2524 if (S.isValidPointerAttrType(Arg->getType())) 2525 CheckNonNullArgument(S, Arg, CallSiteLoc); 2526 return; 2527 } 2528 2529 for (unsigned Val : NonNull->args()) { 2530 if (Val >= Args.size()) 2531 continue; 2532 if (NonNullArgs.empty()) 2533 NonNullArgs.resize(Args.size()); 2534 NonNullArgs.set(Val); 2535 } 2536 } 2537 } 2538 2539 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2540 // Handle the nonnull attribute on the parameters of the 2541 // function/method. 2542 ArrayRef<ParmVarDecl*> parms; 2543 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2544 parms = FD->parameters(); 2545 else 2546 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2547 2548 unsigned ParamIndex = 0; 2549 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2550 I != E; ++I, ++ParamIndex) { 2551 const ParmVarDecl *PVD = *I; 2552 if (PVD->hasAttr<NonNullAttr>() || 2553 isNonNullType(S.Context, PVD->getType())) { 2554 if (NonNullArgs.empty()) 2555 NonNullArgs.resize(Args.size()); 2556 2557 NonNullArgs.set(ParamIndex); 2558 } 2559 } 2560 } else { 2561 // If we have a non-function, non-method declaration but no 2562 // function prototype, try to dig out the function prototype. 2563 if (!Proto) { 2564 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2565 QualType type = VD->getType().getNonReferenceType(); 2566 if (auto pointerType = type->getAs<PointerType>()) 2567 type = pointerType->getPointeeType(); 2568 else if (auto blockType = type->getAs<BlockPointerType>()) 2569 type = blockType->getPointeeType(); 2570 // FIXME: data member pointers? 2571 2572 // Dig out the function prototype, if there is one. 2573 Proto = type->getAs<FunctionProtoType>(); 2574 } 2575 } 2576 2577 // Fill in non-null argument information from the nullability 2578 // information on the parameter types (if we have them). 2579 if (Proto) { 2580 unsigned Index = 0; 2581 for (auto paramType : Proto->getParamTypes()) { 2582 if (isNonNullType(S.Context, paramType)) { 2583 if (NonNullArgs.empty()) 2584 NonNullArgs.resize(Args.size()); 2585 2586 NonNullArgs.set(Index); 2587 } 2588 2589 ++Index; 2590 } 2591 } 2592 } 2593 2594 // Check for non-null arguments. 2595 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2596 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2597 if (NonNullArgs[ArgIndex]) 2598 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2599 } 2600 } 2601 2602 /// Handles the checks for format strings, non-POD arguments to vararg 2603 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 2604 /// attributes. 2605 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2606 const Expr *ThisArg, ArrayRef<const Expr *> Args, 2607 bool IsMemberFunction, SourceLocation Loc, 2608 SourceRange Range, VariadicCallType CallType) { 2609 // FIXME: We should check as much as we can in the template definition. 2610 if (CurContext->isDependentContext()) 2611 return; 2612 2613 // Printf and scanf checking. 2614 llvm::SmallBitVector CheckedVarArgs; 2615 if (FDecl) { 2616 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2617 // Only create vector if there are format attributes. 2618 CheckedVarArgs.resize(Args.size()); 2619 2620 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2621 CheckedVarArgs); 2622 } 2623 } 2624 2625 // Refuse POD arguments that weren't caught by the format string 2626 // checks above. 2627 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 2628 if (CallType != VariadicDoesNotApply && 2629 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 2630 unsigned NumParams = Proto ? Proto->getNumParams() 2631 : FDecl && isa<FunctionDecl>(FDecl) 2632 ? cast<FunctionDecl>(FDecl)->getNumParams() 2633 : FDecl && isa<ObjCMethodDecl>(FDecl) 2634 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2635 : 0; 2636 2637 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2638 // Args[ArgIdx] can be null in malformed code. 2639 if (const Expr *Arg = Args[ArgIdx]) { 2640 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 2641 checkVariadicArgument(Arg, CallType); 2642 } 2643 } 2644 } 2645 2646 if (FDecl || Proto) { 2647 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 2648 2649 // Type safety checking. 2650 if (FDecl) { 2651 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 2652 CheckArgumentWithTypeTag(I, Args.data()); 2653 } 2654 } 2655 2656 if (FD) 2657 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 2658 } 2659 2660 /// CheckConstructorCall - Check a constructor call for correctness and safety 2661 /// properties not enforced by the C type system. 2662 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 2663 ArrayRef<const Expr *> Args, 2664 const FunctionProtoType *Proto, 2665 SourceLocation Loc) { 2666 VariadicCallType CallType = 2667 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 2668 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 2669 Loc, SourceRange(), CallType); 2670 } 2671 2672 /// CheckFunctionCall - Check a direct function call for various correctness 2673 /// and safety properties not strictly enforced by the C type system. 2674 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2675 const FunctionProtoType *Proto) { 2676 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 2677 isa<CXXMethodDecl>(FDecl); 2678 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 2679 IsMemberOperatorCall; 2680 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 2681 TheCall->getCallee()); 2682 Expr** Args = TheCall->getArgs(); 2683 unsigned NumArgs = TheCall->getNumArgs(); 2684 2685 Expr *ImplicitThis = nullptr; 2686 if (IsMemberOperatorCall) { 2687 // If this is a call to a member operator, hide the first argument 2688 // from checkCall. 2689 // FIXME: Our choice of AST representation here is less than ideal. 2690 ImplicitThis = Args[0]; 2691 ++Args; 2692 --NumArgs; 2693 } else if (IsMemberFunction) 2694 ImplicitThis = 2695 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 2696 2697 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 2698 IsMemberFunction, TheCall->getRParenLoc(), 2699 TheCall->getCallee()->getSourceRange(), CallType); 2700 2701 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 2702 // None of the checks below are needed for functions that don't have 2703 // simple names (e.g., C++ conversion functions). 2704 if (!FnInfo) 2705 return false; 2706 2707 CheckAbsoluteValueFunction(TheCall, FDecl); 2708 CheckMaxUnsignedZero(TheCall, FDecl); 2709 2710 if (getLangOpts().ObjC1) 2711 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 2712 2713 unsigned CMId = FDecl->getMemoryFunctionKind(); 2714 if (CMId == 0) 2715 return false; 2716 2717 // Handle memory setting and copying functions. 2718 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 2719 CheckStrlcpycatArguments(TheCall, FnInfo); 2720 else if (CMId == Builtin::BIstrncat) 2721 CheckStrncatArguments(TheCall, FnInfo); 2722 else 2723 CheckMemaccessArguments(TheCall, CMId, FnInfo); 2724 2725 return false; 2726 } 2727 2728 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 2729 ArrayRef<const Expr *> Args) { 2730 VariadicCallType CallType = 2731 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 2732 2733 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 2734 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 2735 CallType); 2736 2737 return false; 2738 } 2739 2740 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2741 const FunctionProtoType *Proto) { 2742 QualType Ty; 2743 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 2744 Ty = V->getType().getNonReferenceType(); 2745 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 2746 Ty = F->getType().getNonReferenceType(); 2747 else 2748 return false; 2749 2750 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 2751 !Ty->isFunctionProtoType()) 2752 return false; 2753 2754 VariadicCallType CallType; 2755 if (!Proto || !Proto->isVariadic()) { 2756 CallType = VariadicDoesNotApply; 2757 } else if (Ty->isBlockPointerType()) { 2758 CallType = VariadicBlock; 2759 } else { // Ty->isFunctionPointerType() 2760 CallType = VariadicFunction; 2761 } 2762 2763 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 2764 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2765 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2766 TheCall->getCallee()->getSourceRange(), CallType); 2767 2768 return false; 2769 } 2770 2771 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2772 /// such as function pointers returned from functions. 2773 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 2774 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 2775 TheCall->getCallee()); 2776 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 2777 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2778 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2779 TheCall->getCallee()->getSourceRange(), CallType); 2780 2781 return false; 2782 } 2783 2784 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 2785 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 2786 return false; 2787 2788 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 2789 switch (Op) { 2790 case AtomicExpr::AO__c11_atomic_init: 2791 case AtomicExpr::AO__opencl_atomic_init: 2792 llvm_unreachable("There is no ordering argument for an init"); 2793 2794 case AtomicExpr::AO__c11_atomic_load: 2795 case AtomicExpr::AO__opencl_atomic_load: 2796 case AtomicExpr::AO__atomic_load_n: 2797 case AtomicExpr::AO__atomic_load: 2798 return OrderingCABI != llvm::AtomicOrderingCABI::release && 2799 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2800 2801 case AtomicExpr::AO__c11_atomic_store: 2802 case AtomicExpr::AO__opencl_atomic_store: 2803 case AtomicExpr::AO__atomic_store: 2804 case AtomicExpr::AO__atomic_store_n: 2805 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 2806 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 2807 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2808 2809 default: 2810 return true; 2811 } 2812 } 2813 2814 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 2815 AtomicExpr::AtomicOp Op) { 2816 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 2817 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2818 2819 // All the non-OpenCL operations take one of the following forms. 2820 // The OpenCL operations take the __c11 forms with one extra argument for 2821 // synchronization scope. 2822 enum { 2823 // C __c11_atomic_init(A *, C) 2824 Init, 2825 // C __c11_atomic_load(A *, int) 2826 Load, 2827 // void __atomic_load(A *, CP, int) 2828 LoadCopy, 2829 // void __atomic_store(A *, CP, int) 2830 Copy, 2831 // C __c11_atomic_add(A *, M, int) 2832 Arithmetic, 2833 // C __atomic_exchange_n(A *, CP, int) 2834 Xchg, 2835 // void __atomic_exchange(A *, C *, CP, int) 2836 GNUXchg, 2837 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 2838 C11CmpXchg, 2839 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 2840 GNUCmpXchg 2841 } Form = Init; 2842 const unsigned NumForm = GNUCmpXchg + 1; 2843 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 2844 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 2845 // where: 2846 // C is an appropriate type, 2847 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 2848 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 2849 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 2850 // the int parameters are for orderings. 2851 2852 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 2853 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 2854 "need to update code for modified forms"); 2855 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 2856 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 2857 AtomicExpr::AO__atomic_load, 2858 "need to update code for modified C11 atomics"); 2859 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 2860 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 2861 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 2862 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 2863 IsOpenCL; 2864 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 2865 Op == AtomicExpr::AO__atomic_store_n || 2866 Op == AtomicExpr::AO__atomic_exchange_n || 2867 Op == AtomicExpr::AO__atomic_compare_exchange_n; 2868 bool IsAddSub = false; 2869 2870 switch (Op) { 2871 case AtomicExpr::AO__c11_atomic_init: 2872 case AtomicExpr::AO__opencl_atomic_init: 2873 Form = Init; 2874 break; 2875 2876 case AtomicExpr::AO__c11_atomic_load: 2877 case AtomicExpr::AO__opencl_atomic_load: 2878 case AtomicExpr::AO__atomic_load_n: 2879 Form = Load; 2880 break; 2881 2882 case AtomicExpr::AO__atomic_load: 2883 Form = LoadCopy; 2884 break; 2885 2886 case AtomicExpr::AO__c11_atomic_store: 2887 case AtomicExpr::AO__opencl_atomic_store: 2888 case AtomicExpr::AO__atomic_store: 2889 case AtomicExpr::AO__atomic_store_n: 2890 Form = Copy; 2891 break; 2892 2893 case AtomicExpr::AO__c11_atomic_fetch_add: 2894 case AtomicExpr::AO__c11_atomic_fetch_sub: 2895 case AtomicExpr::AO__opencl_atomic_fetch_add: 2896 case AtomicExpr::AO__opencl_atomic_fetch_sub: 2897 case AtomicExpr::AO__opencl_atomic_fetch_min: 2898 case AtomicExpr::AO__opencl_atomic_fetch_max: 2899 case AtomicExpr::AO__atomic_fetch_add: 2900 case AtomicExpr::AO__atomic_fetch_sub: 2901 case AtomicExpr::AO__atomic_add_fetch: 2902 case AtomicExpr::AO__atomic_sub_fetch: 2903 IsAddSub = true; 2904 // Fall through. 2905 case AtomicExpr::AO__c11_atomic_fetch_and: 2906 case AtomicExpr::AO__c11_atomic_fetch_or: 2907 case AtomicExpr::AO__c11_atomic_fetch_xor: 2908 case AtomicExpr::AO__opencl_atomic_fetch_and: 2909 case AtomicExpr::AO__opencl_atomic_fetch_or: 2910 case AtomicExpr::AO__opencl_atomic_fetch_xor: 2911 case AtomicExpr::AO__atomic_fetch_and: 2912 case AtomicExpr::AO__atomic_fetch_or: 2913 case AtomicExpr::AO__atomic_fetch_xor: 2914 case AtomicExpr::AO__atomic_fetch_nand: 2915 case AtomicExpr::AO__atomic_and_fetch: 2916 case AtomicExpr::AO__atomic_or_fetch: 2917 case AtomicExpr::AO__atomic_xor_fetch: 2918 case AtomicExpr::AO__atomic_nand_fetch: 2919 Form = Arithmetic; 2920 break; 2921 2922 case AtomicExpr::AO__c11_atomic_exchange: 2923 case AtomicExpr::AO__opencl_atomic_exchange: 2924 case AtomicExpr::AO__atomic_exchange_n: 2925 Form = Xchg; 2926 break; 2927 2928 case AtomicExpr::AO__atomic_exchange: 2929 Form = GNUXchg; 2930 break; 2931 2932 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 2933 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 2934 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 2935 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 2936 Form = C11CmpXchg; 2937 break; 2938 2939 case AtomicExpr::AO__atomic_compare_exchange: 2940 case AtomicExpr::AO__atomic_compare_exchange_n: 2941 Form = GNUCmpXchg; 2942 break; 2943 } 2944 2945 unsigned AdjustedNumArgs = NumArgs[Form]; 2946 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 2947 ++AdjustedNumArgs; 2948 // Check we have the right number of arguments. 2949 if (TheCall->getNumArgs() < AdjustedNumArgs) { 2950 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 2951 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 2952 << TheCall->getCallee()->getSourceRange(); 2953 return ExprError(); 2954 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 2955 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(), 2956 diag::err_typecheck_call_too_many_args) 2957 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 2958 << TheCall->getCallee()->getSourceRange(); 2959 return ExprError(); 2960 } 2961 2962 // Inspect the first argument of the atomic operation. 2963 Expr *Ptr = TheCall->getArg(0); 2964 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 2965 if (ConvertedPtr.isInvalid()) 2966 return ExprError(); 2967 2968 Ptr = ConvertedPtr.get(); 2969 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 2970 if (!pointerType) { 2971 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 2972 << Ptr->getType() << Ptr->getSourceRange(); 2973 return ExprError(); 2974 } 2975 2976 // For a __c11 builtin, this should be a pointer to an _Atomic type. 2977 QualType AtomTy = pointerType->getPointeeType(); // 'A' 2978 QualType ValType = AtomTy; // 'C' 2979 if (IsC11) { 2980 if (!AtomTy->isAtomicType()) { 2981 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 2982 << Ptr->getType() << Ptr->getSourceRange(); 2983 return ExprError(); 2984 } 2985 if (AtomTy.isConstQualified() || 2986 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 2987 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 2988 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 2989 << Ptr->getSourceRange(); 2990 return ExprError(); 2991 } 2992 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 2993 } else if (Form != Load && Form != LoadCopy) { 2994 if (ValType.isConstQualified()) { 2995 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 2996 << Ptr->getType() << Ptr->getSourceRange(); 2997 return ExprError(); 2998 } 2999 } 3000 3001 // For an arithmetic operation, the implied arithmetic must be well-formed. 3002 if (Form == Arithmetic) { 3003 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 3004 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 3005 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3006 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3007 return ExprError(); 3008 } 3009 if (!IsAddSub && !ValType->isIntegerType()) { 3010 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 3011 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3012 return ExprError(); 3013 } 3014 if (IsC11 && ValType->isPointerType() && 3015 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 3016 diag::err_incomplete_type)) { 3017 return ExprError(); 3018 } 3019 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 3020 // For __atomic_*_n operations, the value type must be a scalar integral or 3021 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 3022 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3023 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3024 return ExprError(); 3025 } 3026 3027 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 3028 !AtomTy->isScalarType()) { 3029 // For GNU atomics, require a trivially-copyable type. This is not part of 3030 // the GNU atomics specification, but we enforce it for sanity. 3031 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 3032 << Ptr->getType() << Ptr->getSourceRange(); 3033 return ExprError(); 3034 } 3035 3036 switch (ValType.getObjCLifetime()) { 3037 case Qualifiers::OCL_None: 3038 case Qualifiers::OCL_ExplicitNone: 3039 // okay 3040 break; 3041 3042 case Qualifiers::OCL_Weak: 3043 case Qualifiers::OCL_Strong: 3044 case Qualifiers::OCL_Autoreleasing: 3045 // FIXME: Can this happen? By this point, ValType should be known 3046 // to be trivially copyable. 3047 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3048 << ValType << Ptr->getSourceRange(); 3049 return ExprError(); 3050 } 3051 3052 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 3053 // volatile-ness of the pointee-type inject itself into the result or the 3054 // other operands. Similarly atomic_load can take a pointer to a const 'A'. 3055 ValType.removeLocalVolatile(); 3056 ValType.removeLocalConst(); 3057 QualType ResultType = ValType; 3058 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 3059 Form == Init) 3060 ResultType = Context.VoidTy; 3061 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 3062 ResultType = Context.BoolTy; 3063 3064 // The type of a parameter passed 'by value'. In the GNU atomics, such 3065 // arguments are actually passed as pointers. 3066 QualType ByValType = ValType; // 'CP' 3067 if (!IsC11 && !IsN) 3068 ByValType = Ptr->getType(); 3069 3070 // The first argument --- the pointer --- has a fixed type; we 3071 // deduce the types of the rest of the arguments accordingly. Walk 3072 // the remaining arguments, converting them to the deduced value type. 3073 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) { 3074 QualType Ty; 3075 if (i < NumVals[Form] + 1) { 3076 switch (i) { 3077 case 1: 3078 // The second argument is the non-atomic operand. For arithmetic, this 3079 // is always passed by value, and for a compare_exchange it is always 3080 // passed by address. For the rest, GNU uses by-address and C11 uses 3081 // by-value. 3082 assert(Form != Load); 3083 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 3084 Ty = ValType; 3085 else if (Form == Copy || Form == Xchg) 3086 Ty = ByValType; 3087 else if (Form == Arithmetic) 3088 Ty = Context.getPointerDiffType(); 3089 else { 3090 Expr *ValArg = TheCall->getArg(i); 3091 // Treat this argument as _Nonnull as we want to show a warning if 3092 // NULL is passed into it. 3093 CheckNonNullArgument(*this, ValArg, DRE->getLocStart()); 3094 unsigned AS = 0; 3095 // Keep address space of non-atomic pointer type. 3096 if (const PointerType *PtrTy = 3097 ValArg->getType()->getAs<PointerType>()) { 3098 AS = PtrTy->getPointeeType().getAddressSpace(); 3099 } 3100 Ty = Context.getPointerType( 3101 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 3102 } 3103 break; 3104 case 2: 3105 // The third argument to compare_exchange / GNU exchange is a 3106 // (pointer to a) desired value. 3107 Ty = ByValType; 3108 break; 3109 case 3: 3110 // The fourth argument to GNU compare_exchange is a 'weak' flag. 3111 Ty = Context.BoolTy; 3112 break; 3113 } 3114 } else { 3115 // The order(s) and scope are always converted to int. 3116 Ty = Context.IntTy; 3117 } 3118 3119 InitializedEntity Entity = 3120 InitializedEntity::InitializeParameter(Context, Ty, false); 3121 ExprResult Arg = TheCall->getArg(i); 3122 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3123 if (Arg.isInvalid()) 3124 return true; 3125 TheCall->setArg(i, Arg.get()); 3126 } 3127 3128 Expr *Scope; 3129 if (Form != Init) { 3130 if (IsOpenCL) { 3131 Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 3132 llvm::APSInt Result(32); 3133 if (!Scope->isIntegerConstantExpr(Result, Context)) 3134 Diag(Scope->getLocStart(), 3135 diag::err_atomic_op_has_non_constant_synch_scope) 3136 << Scope->getSourceRange(); 3137 else if (!isValidSyncScopeValue(Result.getZExtValue())) 3138 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope) 3139 << Scope->getSourceRange(); 3140 } else { 3141 Scope = IntegerLiteral::Create( 3142 Context, 3143 llvm::APInt(Context.getTypeSize(Context.IntTy), 3144 static_cast<unsigned>(SyncScope::OpenCLAllSVMDevices)), 3145 Context.IntTy, SourceLocation()); 3146 } 3147 } 3148 3149 // Permute the arguments into a 'consistent' order. 3150 SmallVector<Expr*, 5> SubExprs; 3151 SubExprs.push_back(Ptr); 3152 switch (Form) { 3153 case Init: 3154 // Note, AtomicExpr::getVal1() has a special case for this atomic. 3155 SubExprs.push_back(TheCall->getArg(1)); // Val1 3156 break; 3157 case Load: 3158 SubExprs.push_back(TheCall->getArg(1)); // Order 3159 SubExprs.push_back(Scope); // Scope 3160 break; 3161 case LoadCopy: 3162 case Copy: 3163 case Arithmetic: 3164 case Xchg: 3165 SubExprs.push_back(TheCall->getArg(2)); // Order 3166 SubExprs.push_back(Scope); // Scope 3167 SubExprs.push_back(TheCall->getArg(1)); // Val1 3168 break; 3169 case GNUXchg: 3170 // Note, AtomicExpr::getVal2() has a special case for this atomic. 3171 SubExprs.push_back(TheCall->getArg(3)); // Order 3172 SubExprs.push_back(Scope); // Scope 3173 SubExprs.push_back(TheCall->getArg(1)); // Val1 3174 SubExprs.push_back(TheCall->getArg(2)); // Val2 3175 break; 3176 case C11CmpXchg: 3177 SubExprs.push_back(TheCall->getArg(3)); // Order 3178 SubExprs.push_back(Scope); // Scope 3179 SubExprs.push_back(TheCall->getArg(1)); // Val1 3180 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 3181 SubExprs.push_back(TheCall->getArg(2)); // Val2 3182 break; 3183 case GNUCmpXchg: 3184 SubExprs.push_back(TheCall->getArg(4)); // Order 3185 SubExprs.push_back(Scope); // Scope 3186 SubExprs.push_back(TheCall->getArg(1)); // Val1 3187 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 3188 SubExprs.push_back(TheCall->getArg(2)); // Val2 3189 SubExprs.push_back(TheCall->getArg(3)); // Weak 3190 break; 3191 } 3192 3193 if (SubExprs.size() >= 2 && Form != Init) { 3194 llvm::APSInt Result(32); 3195 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 3196 !isValidOrderingForOp(Result.getSExtValue(), Op)) 3197 Diag(SubExprs[1]->getLocStart(), 3198 diag::warn_atomic_op_has_invalid_memory_order) 3199 << SubExprs[1]->getSourceRange(); 3200 } 3201 3202 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 3203 SubExprs, ResultType, Op, 3204 TheCall->getRParenLoc()); 3205 3206 if ((Op == AtomicExpr::AO__c11_atomic_load || 3207 Op == AtomicExpr::AO__c11_atomic_store || 3208 Op == AtomicExpr::AO__opencl_atomic_load || 3209 Op == AtomicExpr::AO__opencl_atomic_store ) && 3210 Context.AtomicUsesUnsupportedLibcall(AE)) 3211 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) 3212 << ((Op == AtomicExpr::AO__c11_atomic_load || 3213 Op == AtomicExpr::AO__opencl_atomic_load) 3214 ? 0 : 1); 3215 3216 return AE; 3217 } 3218 3219 /// checkBuiltinArgument - Given a call to a builtin function, perform 3220 /// normal type-checking on the given argument, updating the call in 3221 /// place. This is useful when a builtin function requires custom 3222 /// type-checking for some of its arguments but not necessarily all of 3223 /// them. 3224 /// 3225 /// Returns true on error. 3226 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 3227 FunctionDecl *Fn = E->getDirectCallee(); 3228 assert(Fn && "builtin call without direct callee!"); 3229 3230 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 3231 InitializedEntity Entity = 3232 InitializedEntity::InitializeParameter(S.Context, Param); 3233 3234 ExprResult Arg = E->getArg(0); 3235 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 3236 if (Arg.isInvalid()) 3237 return true; 3238 3239 E->setArg(ArgIndex, Arg.get()); 3240 return false; 3241 } 3242 3243 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 3244 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 3245 /// type of its first argument. The main ActOnCallExpr routines have already 3246 /// promoted the types of arguments because all of these calls are prototyped as 3247 /// void(...). 3248 /// 3249 /// This function goes through and does final semantic checking for these 3250 /// builtins, 3251 ExprResult 3252 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3253 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3254 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3255 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3256 3257 // Ensure that we have at least one argument to do type inference from. 3258 if (TheCall->getNumArgs() < 1) { 3259 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3260 << 0 << 1 << TheCall->getNumArgs() 3261 << TheCall->getCallee()->getSourceRange(); 3262 return ExprError(); 3263 } 3264 3265 // Inspect the first argument of the atomic builtin. This should always be 3266 // a pointer type, whose element is an integral scalar or pointer type. 3267 // Because it is a pointer type, we don't have to worry about any implicit 3268 // casts here. 3269 // FIXME: We don't allow floating point scalars as input. 3270 Expr *FirstArg = TheCall->getArg(0); 3271 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3272 if (FirstArgResult.isInvalid()) 3273 return ExprError(); 3274 FirstArg = FirstArgResult.get(); 3275 TheCall->setArg(0, FirstArg); 3276 3277 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3278 if (!pointerType) { 3279 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3280 << FirstArg->getType() << FirstArg->getSourceRange(); 3281 return ExprError(); 3282 } 3283 3284 QualType ValType = pointerType->getPointeeType(); 3285 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3286 !ValType->isBlockPointerType()) { 3287 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3288 << FirstArg->getType() << FirstArg->getSourceRange(); 3289 return ExprError(); 3290 } 3291 3292 switch (ValType.getObjCLifetime()) { 3293 case Qualifiers::OCL_None: 3294 case Qualifiers::OCL_ExplicitNone: 3295 // okay 3296 break; 3297 3298 case Qualifiers::OCL_Weak: 3299 case Qualifiers::OCL_Strong: 3300 case Qualifiers::OCL_Autoreleasing: 3301 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3302 << ValType << FirstArg->getSourceRange(); 3303 return ExprError(); 3304 } 3305 3306 // Strip any qualifiers off ValType. 3307 ValType = ValType.getUnqualifiedType(); 3308 3309 // The majority of builtins return a value, but a few have special return 3310 // types, so allow them to override appropriately below. 3311 QualType ResultType = ValType; 3312 3313 // We need to figure out which concrete builtin this maps onto. For example, 3314 // __sync_fetch_and_add with a 2 byte object turns into 3315 // __sync_fetch_and_add_2. 3316 #define BUILTIN_ROW(x) \ 3317 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3318 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3319 3320 static const unsigned BuiltinIndices[][5] = { 3321 BUILTIN_ROW(__sync_fetch_and_add), 3322 BUILTIN_ROW(__sync_fetch_and_sub), 3323 BUILTIN_ROW(__sync_fetch_and_or), 3324 BUILTIN_ROW(__sync_fetch_and_and), 3325 BUILTIN_ROW(__sync_fetch_and_xor), 3326 BUILTIN_ROW(__sync_fetch_and_nand), 3327 3328 BUILTIN_ROW(__sync_add_and_fetch), 3329 BUILTIN_ROW(__sync_sub_and_fetch), 3330 BUILTIN_ROW(__sync_and_and_fetch), 3331 BUILTIN_ROW(__sync_or_and_fetch), 3332 BUILTIN_ROW(__sync_xor_and_fetch), 3333 BUILTIN_ROW(__sync_nand_and_fetch), 3334 3335 BUILTIN_ROW(__sync_val_compare_and_swap), 3336 BUILTIN_ROW(__sync_bool_compare_and_swap), 3337 BUILTIN_ROW(__sync_lock_test_and_set), 3338 BUILTIN_ROW(__sync_lock_release), 3339 BUILTIN_ROW(__sync_swap) 3340 }; 3341 #undef BUILTIN_ROW 3342 3343 // Determine the index of the size. 3344 unsigned SizeIndex; 3345 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3346 case 1: SizeIndex = 0; break; 3347 case 2: SizeIndex = 1; break; 3348 case 4: SizeIndex = 2; break; 3349 case 8: SizeIndex = 3; break; 3350 case 16: SizeIndex = 4; break; 3351 default: 3352 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3353 << FirstArg->getType() << FirstArg->getSourceRange(); 3354 return ExprError(); 3355 } 3356 3357 // Each of these builtins has one pointer argument, followed by some number of 3358 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3359 // that we ignore. Find out which row of BuiltinIndices to read from as well 3360 // as the number of fixed args. 3361 unsigned BuiltinID = FDecl->getBuiltinID(); 3362 unsigned BuiltinIndex, NumFixed = 1; 3363 bool WarnAboutSemanticsChange = false; 3364 switch (BuiltinID) { 3365 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3366 case Builtin::BI__sync_fetch_and_add: 3367 case Builtin::BI__sync_fetch_and_add_1: 3368 case Builtin::BI__sync_fetch_and_add_2: 3369 case Builtin::BI__sync_fetch_and_add_4: 3370 case Builtin::BI__sync_fetch_and_add_8: 3371 case Builtin::BI__sync_fetch_and_add_16: 3372 BuiltinIndex = 0; 3373 break; 3374 3375 case Builtin::BI__sync_fetch_and_sub: 3376 case Builtin::BI__sync_fetch_and_sub_1: 3377 case Builtin::BI__sync_fetch_and_sub_2: 3378 case Builtin::BI__sync_fetch_and_sub_4: 3379 case Builtin::BI__sync_fetch_and_sub_8: 3380 case Builtin::BI__sync_fetch_and_sub_16: 3381 BuiltinIndex = 1; 3382 break; 3383 3384 case Builtin::BI__sync_fetch_and_or: 3385 case Builtin::BI__sync_fetch_and_or_1: 3386 case Builtin::BI__sync_fetch_and_or_2: 3387 case Builtin::BI__sync_fetch_and_or_4: 3388 case Builtin::BI__sync_fetch_and_or_8: 3389 case Builtin::BI__sync_fetch_and_or_16: 3390 BuiltinIndex = 2; 3391 break; 3392 3393 case Builtin::BI__sync_fetch_and_and: 3394 case Builtin::BI__sync_fetch_and_and_1: 3395 case Builtin::BI__sync_fetch_and_and_2: 3396 case Builtin::BI__sync_fetch_and_and_4: 3397 case Builtin::BI__sync_fetch_and_and_8: 3398 case Builtin::BI__sync_fetch_and_and_16: 3399 BuiltinIndex = 3; 3400 break; 3401 3402 case Builtin::BI__sync_fetch_and_xor: 3403 case Builtin::BI__sync_fetch_and_xor_1: 3404 case Builtin::BI__sync_fetch_and_xor_2: 3405 case Builtin::BI__sync_fetch_and_xor_4: 3406 case Builtin::BI__sync_fetch_and_xor_8: 3407 case Builtin::BI__sync_fetch_and_xor_16: 3408 BuiltinIndex = 4; 3409 break; 3410 3411 case Builtin::BI__sync_fetch_and_nand: 3412 case Builtin::BI__sync_fetch_and_nand_1: 3413 case Builtin::BI__sync_fetch_and_nand_2: 3414 case Builtin::BI__sync_fetch_and_nand_4: 3415 case Builtin::BI__sync_fetch_and_nand_8: 3416 case Builtin::BI__sync_fetch_and_nand_16: 3417 BuiltinIndex = 5; 3418 WarnAboutSemanticsChange = true; 3419 break; 3420 3421 case Builtin::BI__sync_add_and_fetch: 3422 case Builtin::BI__sync_add_and_fetch_1: 3423 case Builtin::BI__sync_add_and_fetch_2: 3424 case Builtin::BI__sync_add_and_fetch_4: 3425 case Builtin::BI__sync_add_and_fetch_8: 3426 case Builtin::BI__sync_add_and_fetch_16: 3427 BuiltinIndex = 6; 3428 break; 3429 3430 case Builtin::BI__sync_sub_and_fetch: 3431 case Builtin::BI__sync_sub_and_fetch_1: 3432 case Builtin::BI__sync_sub_and_fetch_2: 3433 case Builtin::BI__sync_sub_and_fetch_4: 3434 case Builtin::BI__sync_sub_and_fetch_8: 3435 case Builtin::BI__sync_sub_and_fetch_16: 3436 BuiltinIndex = 7; 3437 break; 3438 3439 case Builtin::BI__sync_and_and_fetch: 3440 case Builtin::BI__sync_and_and_fetch_1: 3441 case Builtin::BI__sync_and_and_fetch_2: 3442 case Builtin::BI__sync_and_and_fetch_4: 3443 case Builtin::BI__sync_and_and_fetch_8: 3444 case Builtin::BI__sync_and_and_fetch_16: 3445 BuiltinIndex = 8; 3446 break; 3447 3448 case Builtin::BI__sync_or_and_fetch: 3449 case Builtin::BI__sync_or_and_fetch_1: 3450 case Builtin::BI__sync_or_and_fetch_2: 3451 case Builtin::BI__sync_or_and_fetch_4: 3452 case Builtin::BI__sync_or_and_fetch_8: 3453 case Builtin::BI__sync_or_and_fetch_16: 3454 BuiltinIndex = 9; 3455 break; 3456 3457 case Builtin::BI__sync_xor_and_fetch: 3458 case Builtin::BI__sync_xor_and_fetch_1: 3459 case Builtin::BI__sync_xor_and_fetch_2: 3460 case Builtin::BI__sync_xor_and_fetch_4: 3461 case Builtin::BI__sync_xor_and_fetch_8: 3462 case Builtin::BI__sync_xor_and_fetch_16: 3463 BuiltinIndex = 10; 3464 break; 3465 3466 case Builtin::BI__sync_nand_and_fetch: 3467 case Builtin::BI__sync_nand_and_fetch_1: 3468 case Builtin::BI__sync_nand_and_fetch_2: 3469 case Builtin::BI__sync_nand_and_fetch_4: 3470 case Builtin::BI__sync_nand_and_fetch_8: 3471 case Builtin::BI__sync_nand_and_fetch_16: 3472 BuiltinIndex = 11; 3473 WarnAboutSemanticsChange = true; 3474 break; 3475 3476 case Builtin::BI__sync_val_compare_and_swap: 3477 case Builtin::BI__sync_val_compare_and_swap_1: 3478 case Builtin::BI__sync_val_compare_and_swap_2: 3479 case Builtin::BI__sync_val_compare_and_swap_4: 3480 case Builtin::BI__sync_val_compare_and_swap_8: 3481 case Builtin::BI__sync_val_compare_and_swap_16: 3482 BuiltinIndex = 12; 3483 NumFixed = 2; 3484 break; 3485 3486 case Builtin::BI__sync_bool_compare_and_swap: 3487 case Builtin::BI__sync_bool_compare_and_swap_1: 3488 case Builtin::BI__sync_bool_compare_and_swap_2: 3489 case Builtin::BI__sync_bool_compare_and_swap_4: 3490 case Builtin::BI__sync_bool_compare_and_swap_8: 3491 case Builtin::BI__sync_bool_compare_and_swap_16: 3492 BuiltinIndex = 13; 3493 NumFixed = 2; 3494 ResultType = Context.BoolTy; 3495 break; 3496 3497 case Builtin::BI__sync_lock_test_and_set: 3498 case Builtin::BI__sync_lock_test_and_set_1: 3499 case Builtin::BI__sync_lock_test_and_set_2: 3500 case Builtin::BI__sync_lock_test_and_set_4: 3501 case Builtin::BI__sync_lock_test_and_set_8: 3502 case Builtin::BI__sync_lock_test_and_set_16: 3503 BuiltinIndex = 14; 3504 break; 3505 3506 case Builtin::BI__sync_lock_release: 3507 case Builtin::BI__sync_lock_release_1: 3508 case Builtin::BI__sync_lock_release_2: 3509 case Builtin::BI__sync_lock_release_4: 3510 case Builtin::BI__sync_lock_release_8: 3511 case Builtin::BI__sync_lock_release_16: 3512 BuiltinIndex = 15; 3513 NumFixed = 0; 3514 ResultType = Context.VoidTy; 3515 break; 3516 3517 case Builtin::BI__sync_swap: 3518 case Builtin::BI__sync_swap_1: 3519 case Builtin::BI__sync_swap_2: 3520 case Builtin::BI__sync_swap_4: 3521 case Builtin::BI__sync_swap_8: 3522 case Builtin::BI__sync_swap_16: 3523 BuiltinIndex = 16; 3524 break; 3525 } 3526 3527 // Now that we know how many fixed arguments we expect, first check that we 3528 // have at least that many. 3529 if (TheCall->getNumArgs() < 1+NumFixed) { 3530 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3531 << 0 << 1+NumFixed << TheCall->getNumArgs() 3532 << TheCall->getCallee()->getSourceRange(); 3533 return ExprError(); 3534 } 3535 3536 if (WarnAboutSemanticsChange) { 3537 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 3538 << TheCall->getCallee()->getSourceRange(); 3539 } 3540 3541 // Get the decl for the concrete builtin from this, we can tell what the 3542 // concrete integer type we should convert to is. 3543 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 3544 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 3545 FunctionDecl *NewBuiltinDecl; 3546 if (NewBuiltinID == BuiltinID) 3547 NewBuiltinDecl = FDecl; 3548 else { 3549 // Perform builtin lookup to avoid redeclaring it. 3550 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3551 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3552 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3553 assert(Res.getFoundDecl()); 3554 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3555 if (!NewBuiltinDecl) 3556 return ExprError(); 3557 } 3558 3559 // The first argument --- the pointer --- has a fixed type; we 3560 // deduce the types of the rest of the arguments accordingly. Walk 3561 // the remaining arguments, converting them to the deduced value type. 3562 for (unsigned i = 0; i != NumFixed; ++i) { 3563 ExprResult Arg = TheCall->getArg(i+1); 3564 3565 // GCC does an implicit conversion to the pointer or integer ValType. This 3566 // can fail in some cases (1i -> int**), check for this error case now. 3567 // Initialize the argument. 3568 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3569 ValType, /*consume*/ false); 3570 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3571 if (Arg.isInvalid()) 3572 return ExprError(); 3573 3574 // Okay, we have something that *can* be converted to the right type. Check 3575 // to see if there is a potentially weird extension going on here. This can 3576 // happen when you do an atomic operation on something like an char* and 3577 // pass in 42. The 42 gets converted to char. This is even more strange 3578 // for things like 45.123 -> char, etc. 3579 // FIXME: Do this check. 3580 TheCall->setArg(i+1, Arg.get()); 3581 } 3582 3583 ASTContext& Context = this->getASTContext(); 3584 3585 // Create a new DeclRefExpr to refer to the new decl. 3586 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3587 Context, 3588 DRE->getQualifierLoc(), 3589 SourceLocation(), 3590 NewBuiltinDecl, 3591 /*enclosing*/ false, 3592 DRE->getLocation(), 3593 Context.BuiltinFnTy, 3594 DRE->getValueKind()); 3595 3596 // Set the callee in the CallExpr. 3597 // FIXME: This loses syntactic information. 3598 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3599 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3600 CK_BuiltinFnToFnPtr); 3601 TheCall->setCallee(PromotedCall.get()); 3602 3603 // Change the result type of the call to match the original value type. This 3604 // is arbitrary, but the codegen for these builtins ins design to handle it 3605 // gracefully. 3606 TheCall->setType(ResultType); 3607 3608 return TheCallResult; 3609 } 3610 3611 /// SemaBuiltinNontemporalOverloaded - We have a call to 3612 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 3613 /// overloaded function based on the pointer type of its last argument. 3614 /// 3615 /// This function goes through and does final semantic checking for these 3616 /// builtins. 3617 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 3618 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3619 DeclRefExpr *DRE = 3620 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3621 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3622 unsigned BuiltinID = FDecl->getBuiltinID(); 3623 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 3624 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 3625 "Unexpected nontemporal load/store builtin!"); 3626 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 3627 unsigned numArgs = isStore ? 2 : 1; 3628 3629 // Ensure that we have the proper number of arguments. 3630 if (checkArgCount(*this, TheCall, numArgs)) 3631 return ExprError(); 3632 3633 // Inspect the last argument of the nontemporal builtin. This should always 3634 // be a pointer type, from which we imply the type of the memory access. 3635 // Because it is a pointer type, we don't have to worry about any implicit 3636 // casts here. 3637 Expr *PointerArg = TheCall->getArg(numArgs - 1); 3638 ExprResult PointerArgResult = 3639 DefaultFunctionArrayLvalueConversion(PointerArg); 3640 3641 if (PointerArgResult.isInvalid()) 3642 return ExprError(); 3643 PointerArg = PointerArgResult.get(); 3644 TheCall->setArg(numArgs - 1, PointerArg); 3645 3646 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3647 if (!pointerType) { 3648 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 3649 << PointerArg->getType() << PointerArg->getSourceRange(); 3650 return ExprError(); 3651 } 3652 3653 QualType ValType = pointerType->getPointeeType(); 3654 3655 // Strip any qualifiers off ValType. 3656 ValType = ValType.getUnqualifiedType(); 3657 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3658 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 3659 !ValType->isVectorType()) { 3660 Diag(DRE->getLocStart(), 3661 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 3662 << PointerArg->getType() << PointerArg->getSourceRange(); 3663 return ExprError(); 3664 } 3665 3666 if (!isStore) { 3667 TheCall->setType(ValType); 3668 return TheCallResult; 3669 } 3670 3671 ExprResult ValArg = TheCall->getArg(0); 3672 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3673 Context, ValType, /*consume*/ false); 3674 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3675 if (ValArg.isInvalid()) 3676 return ExprError(); 3677 3678 TheCall->setArg(0, ValArg.get()); 3679 TheCall->setType(Context.VoidTy); 3680 return TheCallResult; 3681 } 3682 3683 /// CheckObjCString - Checks that the argument to the builtin 3684 /// CFString constructor is correct 3685 /// Note: It might also make sense to do the UTF-16 conversion here (would 3686 /// simplify the backend). 3687 bool Sema::CheckObjCString(Expr *Arg) { 3688 Arg = Arg->IgnoreParenCasts(); 3689 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 3690 3691 if (!Literal || !Literal->isAscii()) { 3692 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 3693 << Arg->getSourceRange(); 3694 return true; 3695 } 3696 3697 if (Literal->containsNonAsciiOrNull()) { 3698 StringRef String = Literal->getString(); 3699 unsigned NumBytes = String.size(); 3700 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 3701 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 3702 llvm::UTF16 *ToPtr = &ToBuf[0]; 3703 3704 llvm::ConversionResult Result = 3705 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 3706 ToPtr + NumBytes, llvm::strictConversion); 3707 // Check for conversion failure. 3708 if (Result != llvm::conversionOK) 3709 Diag(Arg->getLocStart(), 3710 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 3711 } 3712 return false; 3713 } 3714 3715 /// CheckObjCString - Checks that the format string argument to the os_log() 3716 /// and os_trace() functions is correct, and converts it to const char *. 3717 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 3718 Arg = Arg->IgnoreParenCasts(); 3719 auto *Literal = dyn_cast<StringLiteral>(Arg); 3720 if (!Literal) { 3721 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 3722 Literal = ObjcLiteral->getString(); 3723 } 3724 } 3725 3726 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 3727 return ExprError( 3728 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 3729 << Arg->getSourceRange()); 3730 } 3731 3732 ExprResult Result(Literal); 3733 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 3734 InitializedEntity Entity = 3735 InitializedEntity::InitializeParameter(Context, ResultTy, false); 3736 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 3737 return Result; 3738 } 3739 3740 /// Check that the user is calling the appropriate va_start builtin for the 3741 /// target and calling convention. 3742 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 3743 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 3744 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 3745 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 3746 bool IsWindows = TT.isOSWindows(); 3747 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 3748 if (IsX64 || IsAArch64) { 3749 clang::CallingConv CC = CC_C; 3750 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 3751 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3752 if (IsMSVAStart) { 3753 // Don't allow this in System V ABI functions. 3754 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 3755 return S.Diag(Fn->getLocStart(), 3756 diag::err_ms_va_start_used_in_sysv_function); 3757 } else { 3758 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 3759 // On x64 Windows, don't allow this in System V ABI functions. 3760 // (Yes, that means there's no corresponding way to support variadic 3761 // System V ABI functions on Windows.) 3762 if ((IsWindows && CC == CC_X86_64SysV) || 3763 (!IsWindows && CC == CC_Win64)) 3764 return S.Diag(Fn->getLocStart(), 3765 diag::err_va_start_used_in_wrong_abi_function) 3766 << !IsWindows; 3767 } 3768 return false; 3769 } 3770 3771 if (IsMSVAStart) 3772 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only); 3773 return false; 3774 } 3775 3776 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 3777 ParmVarDecl **LastParam = nullptr) { 3778 // Determine whether the current function, block, or obj-c method is variadic 3779 // and get its parameter list. 3780 bool IsVariadic = false; 3781 ArrayRef<ParmVarDecl *> Params; 3782 DeclContext *Caller = S.CurContext; 3783 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 3784 IsVariadic = Block->isVariadic(); 3785 Params = Block->parameters(); 3786 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 3787 IsVariadic = FD->isVariadic(); 3788 Params = FD->parameters(); 3789 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 3790 IsVariadic = MD->isVariadic(); 3791 // FIXME: This isn't correct for methods (results in bogus warning). 3792 Params = MD->parameters(); 3793 } else if (isa<CapturedDecl>(Caller)) { 3794 // We don't support va_start in a CapturedDecl. 3795 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt); 3796 return true; 3797 } else { 3798 // This must be some other declcontext that parses exprs. 3799 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function); 3800 return true; 3801 } 3802 3803 if (!IsVariadic) { 3804 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function); 3805 return true; 3806 } 3807 3808 if (LastParam) 3809 *LastParam = Params.empty() ? nullptr : Params.back(); 3810 3811 return false; 3812 } 3813 3814 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 3815 /// for validity. Emit an error and return true on failure; return false 3816 /// on success. 3817 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 3818 Expr *Fn = TheCall->getCallee(); 3819 3820 if (checkVAStartABI(*this, BuiltinID, Fn)) 3821 return true; 3822 3823 if (TheCall->getNumArgs() > 2) { 3824 Diag(TheCall->getArg(2)->getLocStart(), 3825 diag::err_typecheck_call_too_many_args) 3826 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3827 << Fn->getSourceRange() 3828 << SourceRange(TheCall->getArg(2)->getLocStart(), 3829 (*(TheCall->arg_end()-1))->getLocEnd()); 3830 return true; 3831 } 3832 3833 if (TheCall->getNumArgs() < 2) { 3834 return Diag(TheCall->getLocEnd(), 3835 diag::err_typecheck_call_too_few_args_at_least) 3836 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 3837 } 3838 3839 // Type-check the first argument normally. 3840 if (checkBuiltinArgument(*this, TheCall, 0)) 3841 return true; 3842 3843 // Check that the current function is variadic, and get its last parameter. 3844 ParmVarDecl *LastParam; 3845 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 3846 return true; 3847 3848 // Verify that the second argument to the builtin is the last argument of the 3849 // current function or method. 3850 bool SecondArgIsLastNamedArgument = false; 3851 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 3852 3853 // These are valid if SecondArgIsLastNamedArgument is false after the next 3854 // block. 3855 QualType Type; 3856 SourceLocation ParamLoc; 3857 bool IsCRegister = false; 3858 3859 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 3860 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 3861 SecondArgIsLastNamedArgument = PV == LastParam; 3862 3863 Type = PV->getType(); 3864 ParamLoc = PV->getLocation(); 3865 IsCRegister = 3866 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 3867 } 3868 } 3869 3870 if (!SecondArgIsLastNamedArgument) 3871 Diag(TheCall->getArg(1)->getLocStart(), 3872 diag::warn_second_arg_of_va_start_not_last_named_param); 3873 else if (IsCRegister || Type->isReferenceType() || 3874 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 3875 // Promotable integers are UB, but enumerations need a bit of 3876 // extra checking to see what their promotable type actually is. 3877 if (!Type->isPromotableIntegerType()) 3878 return false; 3879 if (!Type->isEnumeralType()) 3880 return true; 3881 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 3882 return !(ED && 3883 Context.typesAreCompatible(ED->getPromotionType(), Type)); 3884 }()) { 3885 unsigned Reason = 0; 3886 if (Type->isReferenceType()) Reason = 1; 3887 else if (IsCRegister) Reason = 2; 3888 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 3889 Diag(ParamLoc, diag::note_parameter_type) << Type; 3890 } 3891 3892 TheCall->setType(Context.VoidTy); 3893 return false; 3894 } 3895 3896 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) { 3897 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 3898 // const char *named_addr); 3899 3900 Expr *Func = Call->getCallee(); 3901 3902 if (Call->getNumArgs() < 3) 3903 return Diag(Call->getLocEnd(), 3904 diag::err_typecheck_call_too_few_args_at_least) 3905 << 0 /*function call*/ << 3 << Call->getNumArgs(); 3906 3907 // Type-check the first argument normally. 3908 if (checkBuiltinArgument(*this, Call, 0)) 3909 return true; 3910 3911 // Check that the current function is variadic. 3912 if (checkVAStartIsInVariadicFunction(*this, Func)) 3913 return true; 3914 3915 const struct { 3916 unsigned ArgNo; 3917 QualType Type; 3918 } ArgumentTypes[] = { 3919 { 1, Context.getPointerType(Context.CharTy.withConst()) }, 3920 { 2, Context.getSizeType() }, 3921 }; 3922 3923 for (const auto &AT : ArgumentTypes) { 3924 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens(); 3925 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType()) 3926 continue; 3927 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible) 3928 << Arg->getType() << AT.Type << 1 /* different class */ 3929 << 0 /* qualifier difference */ << 3 /* parameter mismatch */ 3930 << AT.ArgNo + 1 << Arg->getType() << AT.Type; 3931 } 3932 3933 return false; 3934 } 3935 3936 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 3937 /// friends. This is declared to take (...), so we have to check everything. 3938 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 3939 if (TheCall->getNumArgs() < 2) 3940 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3941 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 3942 if (TheCall->getNumArgs() > 2) 3943 return Diag(TheCall->getArg(2)->getLocStart(), 3944 diag::err_typecheck_call_too_many_args) 3945 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3946 << SourceRange(TheCall->getArg(2)->getLocStart(), 3947 (*(TheCall->arg_end()-1))->getLocEnd()); 3948 3949 ExprResult OrigArg0 = TheCall->getArg(0); 3950 ExprResult OrigArg1 = TheCall->getArg(1); 3951 3952 // Do standard promotions between the two arguments, returning their common 3953 // type. 3954 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 3955 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 3956 return true; 3957 3958 // Make sure any conversions are pushed back into the call; this is 3959 // type safe since unordered compare builtins are declared as "_Bool 3960 // foo(...)". 3961 TheCall->setArg(0, OrigArg0.get()); 3962 TheCall->setArg(1, OrigArg1.get()); 3963 3964 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 3965 return false; 3966 3967 // If the common type isn't a real floating type, then the arguments were 3968 // invalid for this operation. 3969 if (Res.isNull() || !Res->isRealFloatingType()) 3970 return Diag(OrigArg0.get()->getLocStart(), 3971 diag::err_typecheck_call_invalid_ordered_compare) 3972 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 3973 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 3974 3975 return false; 3976 } 3977 3978 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 3979 /// __builtin_isnan and friends. This is declared to take (...), so we have 3980 /// to check everything. We expect the last argument to be a floating point 3981 /// value. 3982 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 3983 if (TheCall->getNumArgs() < NumArgs) 3984 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3985 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 3986 if (TheCall->getNumArgs() > NumArgs) 3987 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 3988 diag::err_typecheck_call_too_many_args) 3989 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 3990 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 3991 (*(TheCall->arg_end()-1))->getLocEnd()); 3992 3993 Expr *OrigArg = TheCall->getArg(NumArgs-1); 3994 3995 if (OrigArg->isTypeDependent()) 3996 return false; 3997 3998 // This operation requires a non-_Complex floating-point number. 3999 if (!OrigArg->getType()->isRealFloatingType()) 4000 return Diag(OrigArg->getLocStart(), 4001 diag::err_typecheck_call_invalid_unary_fp) 4002 << OrigArg->getType() << OrigArg->getSourceRange(); 4003 4004 // If this is an implicit conversion from float -> float or double, remove it. 4005 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 4006 // Only remove standard FloatCasts, leaving other casts inplace 4007 if (Cast->getCastKind() == CK_FloatingCast) { 4008 Expr *CastArg = Cast->getSubExpr(); 4009 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 4010 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 4011 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) && 4012 "promotion from float to either float or double is the only expected cast here"); 4013 Cast->setSubExpr(nullptr); 4014 TheCall->setArg(NumArgs-1, CastArg); 4015 } 4016 } 4017 } 4018 4019 return false; 4020 } 4021 4022 // Customized Sema Checking for VSX builtins that have the following signature: 4023 // vector [...] builtinName(vector [...], vector [...], const int); 4024 // Which takes the same type of vectors (any legal vector type) for the first 4025 // two arguments and takes compile time constant for the third argument. 4026 // Example builtins are : 4027 // vector double vec_xxpermdi(vector double, vector double, int); 4028 // vector short vec_xxsldwi(vector short, vector short, int); 4029 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 4030 unsigned ExpectedNumArgs = 3; 4031 if (TheCall->getNumArgs() < ExpectedNumArgs) 4032 return Diag(TheCall->getLocEnd(), 4033 diag::err_typecheck_call_too_few_args_at_least) 4034 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4035 << TheCall->getSourceRange(); 4036 4037 if (TheCall->getNumArgs() > ExpectedNumArgs) 4038 return Diag(TheCall->getLocEnd(), 4039 diag::err_typecheck_call_too_many_args_at_most) 4040 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4041 << TheCall->getSourceRange(); 4042 4043 // Check the third argument is a compile time constant 4044 llvm::APSInt Value; 4045 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 4046 return Diag(TheCall->getLocStart(), 4047 diag::err_vsx_builtin_nonconstant_argument) 4048 << 3 /* argument index */ << TheCall->getDirectCallee() 4049 << SourceRange(TheCall->getArg(2)->getLocStart(), 4050 TheCall->getArg(2)->getLocEnd()); 4051 4052 QualType Arg1Ty = TheCall->getArg(0)->getType(); 4053 QualType Arg2Ty = TheCall->getArg(1)->getType(); 4054 4055 // Check the type of argument 1 and argument 2 are vectors. 4056 SourceLocation BuiltinLoc = TheCall->getLocStart(); 4057 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 4058 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 4059 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 4060 << TheCall->getDirectCallee() 4061 << SourceRange(TheCall->getArg(0)->getLocStart(), 4062 TheCall->getArg(1)->getLocEnd()); 4063 } 4064 4065 // Check the first two arguments are the same type. 4066 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 4067 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 4068 << TheCall->getDirectCallee() 4069 << SourceRange(TheCall->getArg(0)->getLocStart(), 4070 TheCall->getArg(1)->getLocEnd()); 4071 } 4072 4073 // When default clang type checking is turned off and the customized type 4074 // checking is used, the returning type of the function must be explicitly 4075 // set. Otherwise it is _Bool by default. 4076 TheCall->setType(Arg1Ty); 4077 4078 return false; 4079 } 4080 4081 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 4082 // This is declared to take (...), so we have to check everything. 4083 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 4084 if (TheCall->getNumArgs() < 2) 4085 return ExprError(Diag(TheCall->getLocEnd(), 4086 diag::err_typecheck_call_too_few_args_at_least) 4087 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4088 << TheCall->getSourceRange()); 4089 4090 // Determine which of the following types of shufflevector we're checking: 4091 // 1) unary, vector mask: (lhs, mask) 4092 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 4093 QualType resType = TheCall->getArg(0)->getType(); 4094 unsigned numElements = 0; 4095 4096 if (!TheCall->getArg(0)->isTypeDependent() && 4097 !TheCall->getArg(1)->isTypeDependent()) { 4098 QualType LHSType = TheCall->getArg(0)->getType(); 4099 QualType RHSType = TheCall->getArg(1)->getType(); 4100 4101 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 4102 return ExprError(Diag(TheCall->getLocStart(), 4103 diag::err_vec_builtin_non_vector) 4104 << TheCall->getDirectCallee() 4105 << SourceRange(TheCall->getArg(0)->getLocStart(), 4106 TheCall->getArg(1)->getLocEnd())); 4107 4108 numElements = LHSType->getAs<VectorType>()->getNumElements(); 4109 unsigned numResElements = TheCall->getNumArgs() - 2; 4110 4111 // Check to see if we have a call with 2 vector arguments, the unary shuffle 4112 // with mask. If so, verify that RHS is an integer vector type with the 4113 // same number of elts as lhs. 4114 if (TheCall->getNumArgs() == 2) { 4115 if (!RHSType->hasIntegerRepresentation() || 4116 RHSType->getAs<VectorType>()->getNumElements() != numElements) 4117 return ExprError(Diag(TheCall->getLocStart(), 4118 diag::err_vec_builtin_incompatible_vector) 4119 << TheCall->getDirectCallee() 4120 << SourceRange(TheCall->getArg(1)->getLocStart(), 4121 TheCall->getArg(1)->getLocEnd())); 4122 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 4123 return ExprError(Diag(TheCall->getLocStart(), 4124 diag::err_vec_builtin_incompatible_vector) 4125 << TheCall->getDirectCallee() 4126 << SourceRange(TheCall->getArg(0)->getLocStart(), 4127 TheCall->getArg(1)->getLocEnd())); 4128 } else if (numElements != numResElements) { 4129 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 4130 resType = Context.getVectorType(eltType, numResElements, 4131 VectorType::GenericVector); 4132 } 4133 } 4134 4135 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 4136 if (TheCall->getArg(i)->isTypeDependent() || 4137 TheCall->getArg(i)->isValueDependent()) 4138 continue; 4139 4140 llvm::APSInt Result(32); 4141 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 4142 return ExprError(Diag(TheCall->getLocStart(), 4143 diag::err_shufflevector_nonconstant_argument) 4144 << TheCall->getArg(i)->getSourceRange()); 4145 4146 // Allow -1 which will be translated to undef in the IR. 4147 if (Result.isSigned() && Result.isAllOnesValue()) 4148 continue; 4149 4150 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 4151 return ExprError(Diag(TheCall->getLocStart(), 4152 diag::err_shufflevector_argument_too_large) 4153 << TheCall->getArg(i)->getSourceRange()); 4154 } 4155 4156 SmallVector<Expr*, 32> exprs; 4157 4158 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 4159 exprs.push_back(TheCall->getArg(i)); 4160 TheCall->setArg(i, nullptr); 4161 } 4162 4163 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 4164 TheCall->getCallee()->getLocStart(), 4165 TheCall->getRParenLoc()); 4166 } 4167 4168 /// SemaConvertVectorExpr - Handle __builtin_convertvector 4169 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 4170 SourceLocation BuiltinLoc, 4171 SourceLocation RParenLoc) { 4172 ExprValueKind VK = VK_RValue; 4173 ExprObjectKind OK = OK_Ordinary; 4174 QualType DstTy = TInfo->getType(); 4175 QualType SrcTy = E->getType(); 4176 4177 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 4178 return ExprError(Diag(BuiltinLoc, 4179 diag::err_convertvector_non_vector) 4180 << E->getSourceRange()); 4181 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 4182 return ExprError(Diag(BuiltinLoc, 4183 diag::err_convertvector_non_vector_type)); 4184 4185 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 4186 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 4187 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 4188 if (SrcElts != DstElts) 4189 return ExprError(Diag(BuiltinLoc, 4190 diag::err_convertvector_incompatible_vector) 4191 << E->getSourceRange()); 4192 } 4193 4194 return new (Context) 4195 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4196 } 4197 4198 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 4199 // This is declared to take (const void*, ...) and can take two 4200 // optional constant int args. 4201 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 4202 unsigned NumArgs = TheCall->getNumArgs(); 4203 4204 if (NumArgs > 3) 4205 return Diag(TheCall->getLocEnd(), 4206 diag::err_typecheck_call_too_many_args_at_most) 4207 << 0 /*function call*/ << 3 << NumArgs 4208 << TheCall->getSourceRange(); 4209 4210 // Argument 0 is checked for us and the remaining arguments must be 4211 // constant integers. 4212 for (unsigned i = 1; i != NumArgs; ++i) 4213 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 4214 return true; 4215 4216 return false; 4217 } 4218 4219 /// SemaBuiltinAssume - Handle __assume (MS Extension). 4220 // __assume does not evaluate its arguments, and should warn if its argument 4221 // has side effects. 4222 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 4223 Expr *Arg = TheCall->getArg(0); 4224 if (Arg->isInstantiationDependent()) return false; 4225 4226 if (Arg->HasSideEffects(Context)) 4227 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 4228 << Arg->getSourceRange() 4229 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 4230 4231 return false; 4232 } 4233 4234 /// Handle __builtin_alloca_with_align. This is declared 4235 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 4236 /// than 8. 4237 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 4238 // The alignment must be a constant integer. 4239 Expr *Arg = TheCall->getArg(1); 4240 4241 // We can't check the value of a dependent argument. 4242 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4243 if (const auto *UE = 4244 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 4245 if (UE->getKind() == UETT_AlignOf) 4246 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 4247 << Arg->getSourceRange(); 4248 4249 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 4250 4251 if (!Result.isPowerOf2()) 4252 return Diag(TheCall->getLocStart(), 4253 diag::err_alignment_not_power_of_two) 4254 << Arg->getSourceRange(); 4255 4256 if (Result < Context.getCharWidth()) 4257 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 4258 << (unsigned)Context.getCharWidth() 4259 << Arg->getSourceRange(); 4260 4261 if (Result > INT32_MAX) 4262 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 4263 << INT32_MAX 4264 << Arg->getSourceRange(); 4265 } 4266 4267 return false; 4268 } 4269 4270 /// Handle __builtin_assume_aligned. This is declared 4271 /// as (const void*, size_t, ...) and can take one optional constant int arg. 4272 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 4273 unsigned NumArgs = TheCall->getNumArgs(); 4274 4275 if (NumArgs > 3) 4276 return Diag(TheCall->getLocEnd(), 4277 diag::err_typecheck_call_too_many_args_at_most) 4278 << 0 /*function call*/ << 3 << NumArgs 4279 << TheCall->getSourceRange(); 4280 4281 // The alignment must be a constant integer. 4282 Expr *Arg = TheCall->getArg(1); 4283 4284 // We can't check the value of a dependent argument. 4285 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4286 llvm::APSInt Result; 4287 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4288 return true; 4289 4290 if (!Result.isPowerOf2()) 4291 return Diag(TheCall->getLocStart(), 4292 diag::err_alignment_not_power_of_two) 4293 << Arg->getSourceRange(); 4294 } 4295 4296 if (NumArgs > 2) { 4297 ExprResult Arg(TheCall->getArg(2)); 4298 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4299 Context.getSizeType(), false); 4300 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4301 if (Arg.isInvalid()) return true; 4302 TheCall->setArg(2, Arg.get()); 4303 } 4304 4305 return false; 4306 } 4307 4308 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 4309 unsigned BuiltinID = 4310 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 4311 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 4312 4313 unsigned NumArgs = TheCall->getNumArgs(); 4314 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 4315 if (NumArgs < NumRequiredArgs) { 4316 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4317 << 0 /* function call */ << NumRequiredArgs << NumArgs 4318 << TheCall->getSourceRange(); 4319 } 4320 if (NumArgs >= NumRequiredArgs + 0x100) { 4321 return Diag(TheCall->getLocEnd(), 4322 diag::err_typecheck_call_too_many_args_at_most) 4323 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 4324 << TheCall->getSourceRange(); 4325 } 4326 unsigned i = 0; 4327 4328 // For formatting call, check buffer arg. 4329 if (!IsSizeCall) { 4330 ExprResult Arg(TheCall->getArg(i)); 4331 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4332 Context, Context.VoidPtrTy, false); 4333 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4334 if (Arg.isInvalid()) 4335 return true; 4336 TheCall->setArg(i, Arg.get()); 4337 i++; 4338 } 4339 4340 // Check string literal arg. 4341 unsigned FormatIdx = i; 4342 { 4343 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4344 if (Arg.isInvalid()) 4345 return true; 4346 TheCall->setArg(i, Arg.get()); 4347 i++; 4348 } 4349 4350 // Make sure variadic args are scalar. 4351 unsigned FirstDataArg = i; 4352 while (i < NumArgs) { 4353 ExprResult Arg = DefaultVariadicArgumentPromotion( 4354 TheCall->getArg(i), VariadicFunction, nullptr); 4355 if (Arg.isInvalid()) 4356 return true; 4357 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4358 if (ArgSize.getQuantity() >= 0x100) { 4359 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4360 << i << (int)ArgSize.getQuantity() << 0xff 4361 << TheCall->getSourceRange(); 4362 } 4363 TheCall->setArg(i, Arg.get()); 4364 i++; 4365 } 4366 4367 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4368 // call to avoid duplicate diagnostics. 4369 if (!IsSizeCall) { 4370 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4371 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4372 bool Success = CheckFormatArguments( 4373 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4374 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4375 CheckedVarArgs); 4376 if (!Success) 4377 return true; 4378 } 4379 4380 if (IsSizeCall) { 4381 TheCall->setType(Context.getSizeType()); 4382 } else { 4383 TheCall->setType(Context.VoidPtrTy); 4384 } 4385 return false; 4386 } 4387 4388 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4389 /// TheCall is a constant expression. 4390 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4391 llvm::APSInt &Result) { 4392 Expr *Arg = TheCall->getArg(ArgNum); 4393 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4394 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4395 4396 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4397 4398 if (!Arg->isIntegerConstantExpr(Result, Context)) 4399 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 4400 << FDecl->getDeclName() << Arg->getSourceRange(); 4401 4402 return false; 4403 } 4404 4405 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 4406 /// TheCall is a constant expression in the range [Low, High]. 4407 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 4408 int Low, int High) { 4409 llvm::APSInt Result; 4410 4411 // We can't check the value of a dependent argument. 4412 Expr *Arg = TheCall->getArg(ArgNum); 4413 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4414 return false; 4415 4416 // Check constant-ness first. 4417 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4418 return true; 4419 4420 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 4421 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 4422 << Low << High << Arg->getSourceRange(); 4423 4424 return false; 4425 } 4426 4427 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 4428 /// TheCall is a constant expression is a multiple of Num.. 4429 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 4430 unsigned Num) { 4431 llvm::APSInt Result; 4432 4433 // We can't check the value of a dependent argument. 4434 Expr *Arg = TheCall->getArg(ArgNum); 4435 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4436 return false; 4437 4438 // Check constant-ness first. 4439 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4440 return true; 4441 4442 if (Result.getSExtValue() % Num != 0) 4443 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 4444 << Num << Arg->getSourceRange(); 4445 4446 return false; 4447 } 4448 4449 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 4450 /// TheCall is an ARM/AArch64 special register string literal. 4451 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 4452 int ArgNum, unsigned ExpectedFieldNum, 4453 bool AllowName) { 4454 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 4455 BuiltinID == ARM::BI__builtin_arm_wsr64 || 4456 BuiltinID == ARM::BI__builtin_arm_rsr || 4457 BuiltinID == ARM::BI__builtin_arm_rsrp || 4458 BuiltinID == ARM::BI__builtin_arm_wsr || 4459 BuiltinID == ARM::BI__builtin_arm_wsrp; 4460 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 4461 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 4462 BuiltinID == AArch64::BI__builtin_arm_rsr || 4463 BuiltinID == AArch64::BI__builtin_arm_rsrp || 4464 BuiltinID == AArch64::BI__builtin_arm_wsr || 4465 BuiltinID == AArch64::BI__builtin_arm_wsrp; 4466 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 4467 4468 // We can't check the value of a dependent argument. 4469 Expr *Arg = TheCall->getArg(ArgNum); 4470 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4471 return false; 4472 4473 // Check if the argument is a string literal. 4474 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4475 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 4476 << Arg->getSourceRange(); 4477 4478 // Check the type of special register given. 4479 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4480 SmallVector<StringRef, 6> Fields; 4481 Reg.split(Fields, ":"); 4482 4483 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 4484 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4485 << Arg->getSourceRange(); 4486 4487 // If the string is the name of a register then we cannot check that it is 4488 // valid here but if the string is of one the forms described in ACLE then we 4489 // can check that the supplied fields are integers and within the valid 4490 // ranges. 4491 if (Fields.size() > 1) { 4492 bool FiveFields = Fields.size() == 5; 4493 4494 bool ValidString = true; 4495 if (IsARMBuiltin) { 4496 ValidString &= Fields[0].startswith_lower("cp") || 4497 Fields[0].startswith_lower("p"); 4498 if (ValidString) 4499 Fields[0] = 4500 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 4501 4502 ValidString &= Fields[2].startswith_lower("c"); 4503 if (ValidString) 4504 Fields[2] = Fields[2].drop_front(1); 4505 4506 if (FiveFields) { 4507 ValidString &= Fields[3].startswith_lower("c"); 4508 if (ValidString) 4509 Fields[3] = Fields[3].drop_front(1); 4510 } 4511 } 4512 4513 SmallVector<int, 5> Ranges; 4514 if (FiveFields) 4515 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 4516 else 4517 Ranges.append({15, 7, 15}); 4518 4519 for (unsigned i=0; i<Fields.size(); ++i) { 4520 int IntField; 4521 ValidString &= !Fields[i].getAsInteger(10, IntField); 4522 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 4523 } 4524 4525 if (!ValidString) 4526 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4527 << Arg->getSourceRange(); 4528 4529 } else if (IsAArch64Builtin && Fields.size() == 1) { 4530 // If the register name is one of those that appear in the condition below 4531 // and the special register builtin being used is one of the write builtins, 4532 // then we require that the argument provided for writing to the register 4533 // is an integer constant expression. This is because it will be lowered to 4534 // an MSR (immediate) instruction, so we need to know the immediate at 4535 // compile time. 4536 if (TheCall->getNumArgs() != 2) 4537 return false; 4538 4539 std::string RegLower = Reg.lower(); 4540 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 4541 RegLower != "pan" && RegLower != "uao") 4542 return false; 4543 4544 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4545 } 4546 4547 return false; 4548 } 4549 4550 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 4551 /// This checks that the target supports __builtin_longjmp and 4552 /// that val is a constant 1. 4553 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 4554 if (!Context.getTargetInfo().hasSjLjLowering()) 4555 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 4556 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4557 4558 Expr *Arg = TheCall->getArg(1); 4559 llvm::APSInt Result; 4560 4561 // TODO: This is less than ideal. Overload this to take a value. 4562 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4563 return true; 4564 4565 if (Result != 1) 4566 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 4567 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 4568 4569 return false; 4570 } 4571 4572 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 4573 /// This checks that the target supports __builtin_setjmp. 4574 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 4575 if (!Context.getTargetInfo().hasSjLjLowering()) 4576 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 4577 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4578 return false; 4579 } 4580 4581 namespace { 4582 class UncoveredArgHandler { 4583 enum { Unknown = -1, AllCovered = -2 }; 4584 signed FirstUncoveredArg; 4585 SmallVector<const Expr *, 4> DiagnosticExprs; 4586 4587 public: 4588 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { } 4589 4590 bool hasUncoveredArg() const { 4591 return (FirstUncoveredArg >= 0); 4592 } 4593 4594 unsigned getUncoveredArg() const { 4595 assert(hasUncoveredArg() && "no uncovered argument"); 4596 return FirstUncoveredArg; 4597 } 4598 4599 void setAllCovered() { 4600 // A string has been found with all arguments covered, so clear out 4601 // the diagnostics. 4602 DiagnosticExprs.clear(); 4603 FirstUncoveredArg = AllCovered; 4604 } 4605 4606 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 4607 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 4608 4609 // Don't update if a previous string covers all arguments. 4610 if (FirstUncoveredArg == AllCovered) 4611 return; 4612 4613 // UncoveredArgHandler tracks the highest uncovered argument index 4614 // and with it all the strings that match this index. 4615 if (NewFirstUncoveredArg == FirstUncoveredArg) 4616 DiagnosticExprs.push_back(StrExpr); 4617 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 4618 DiagnosticExprs.clear(); 4619 DiagnosticExprs.push_back(StrExpr); 4620 FirstUncoveredArg = NewFirstUncoveredArg; 4621 } 4622 } 4623 4624 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 4625 }; 4626 4627 enum StringLiteralCheckType { 4628 SLCT_NotALiteral, 4629 SLCT_UncheckedLiteral, 4630 SLCT_CheckedLiteral 4631 }; 4632 } // end anonymous namespace 4633 4634 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 4635 BinaryOperatorKind BinOpKind, 4636 bool AddendIsRight) { 4637 unsigned BitWidth = Offset.getBitWidth(); 4638 unsigned AddendBitWidth = Addend.getBitWidth(); 4639 // There might be negative interim results. 4640 if (Addend.isUnsigned()) { 4641 Addend = Addend.zext(++AddendBitWidth); 4642 Addend.setIsSigned(true); 4643 } 4644 // Adjust the bit width of the APSInts. 4645 if (AddendBitWidth > BitWidth) { 4646 Offset = Offset.sext(AddendBitWidth); 4647 BitWidth = AddendBitWidth; 4648 } else if (BitWidth > AddendBitWidth) { 4649 Addend = Addend.sext(BitWidth); 4650 } 4651 4652 bool Ov = false; 4653 llvm::APSInt ResOffset = Offset; 4654 if (BinOpKind == BO_Add) 4655 ResOffset = Offset.sadd_ov(Addend, Ov); 4656 else { 4657 assert(AddendIsRight && BinOpKind == BO_Sub && 4658 "operator must be add or sub with addend on the right"); 4659 ResOffset = Offset.ssub_ov(Addend, Ov); 4660 } 4661 4662 // We add an offset to a pointer here so we should support an offset as big as 4663 // possible. 4664 if (Ov) { 4665 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big"); 4666 Offset = Offset.sext(2 * BitWidth); 4667 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 4668 return; 4669 } 4670 4671 Offset = ResOffset; 4672 } 4673 4674 namespace { 4675 // This is a wrapper class around StringLiteral to support offsetted string 4676 // literals as format strings. It takes the offset into account when returning 4677 // the string and its length or the source locations to display notes correctly. 4678 class FormatStringLiteral { 4679 const StringLiteral *FExpr; 4680 int64_t Offset; 4681 4682 public: 4683 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 4684 : FExpr(fexpr), Offset(Offset) {} 4685 4686 StringRef getString() const { 4687 return FExpr->getString().drop_front(Offset); 4688 } 4689 4690 unsigned getByteLength() const { 4691 return FExpr->getByteLength() - getCharByteWidth() * Offset; 4692 } 4693 unsigned getLength() const { return FExpr->getLength() - Offset; } 4694 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 4695 4696 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 4697 4698 QualType getType() const { return FExpr->getType(); } 4699 4700 bool isAscii() const { return FExpr->isAscii(); } 4701 bool isWide() const { return FExpr->isWide(); } 4702 bool isUTF8() const { return FExpr->isUTF8(); } 4703 bool isUTF16() const { return FExpr->isUTF16(); } 4704 bool isUTF32() const { return FExpr->isUTF32(); } 4705 bool isPascal() const { return FExpr->isPascal(); } 4706 4707 SourceLocation getLocationOfByte( 4708 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 4709 const TargetInfo &Target, unsigned *StartToken = nullptr, 4710 unsigned *StartTokenByteOffset = nullptr) const { 4711 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 4712 StartToken, StartTokenByteOffset); 4713 } 4714 4715 SourceLocation getLocStart() const LLVM_READONLY { 4716 return FExpr->getLocStart().getLocWithOffset(Offset); 4717 } 4718 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 4719 }; 4720 } // end anonymous namespace 4721 4722 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 4723 const Expr *OrigFormatExpr, 4724 ArrayRef<const Expr *> Args, 4725 bool HasVAListArg, unsigned format_idx, 4726 unsigned firstDataArg, 4727 Sema::FormatStringType Type, 4728 bool inFunctionCall, 4729 Sema::VariadicCallType CallType, 4730 llvm::SmallBitVector &CheckedVarArgs, 4731 UncoveredArgHandler &UncoveredArg); 4732 4733 // Determine if an expression is a string literal or constant string. 4734 // If this function returns false on the arguments to a function expecting a 4735 // format string, we will usually need to emit a warning. 4736 // True string literals are then checked by CheckFormatString. 4737 static StringLiteralCheckType 4738 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 4739 bool HasVAListArg, unsigned format_idx, 4740 unsigned firstDataArg, Sema::FormatStringType Type, 4741 Sema::VariadicCallType CallType, bool InFunctionCall, 4742 llvm::SmallBitVector &CheckedVarArgs, 4743 UncoveredArgHandler &UncoveredArg, 4744 llvm::APSInt Offset) { 4745 tryAgain: 4746 assert(Offset.isSigned() && "invalid offset"); 4747 4748 if (E->isTypeDependent() || E->isValueDependent()) 4749 return SLCT_NotALiteral; 4750 4751 E = E->IgnoreParenCasts(); 4752 4753 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 4754 // Technically -Wformat-nonliteral does not warn about this case. 4755 // The behavior of printf and friends in this case is implementation 4756 // dependent. Ideally if the format string cannot be null then 4757 // it should have a 'nonnull' attribute in the function prototype. 4758 return SLCT_UncheckedLiteral; 4759 4760 switch (E->getStmtClass()) { 4761 case Stmt::BinaryConditionalOperatorClass: 4762 case Stmt::ConditionalOperatorClass: { 4763 // The expression is a literal if both sub-expressions were, and it was 4764 // completely checked only if both sub-expressions were checked. 4765 const AbstractConditionalOperator *C = 4766 cast<AbstractConditionalOperator>(E); 4767 4768 // Determine whether it is necessary to check both sub-expressions, for 4769 // example, because the condition expression is a constant that can be 4770 // evaluated at compile time. 4771 bool CheckLeft = true, CheckRight = true; 4772 4773 bool Cond; 4774 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 4775 if (Cond) 4776 CheckRight = false; 4777 else 4778 CheckLeft = false; 4779 } 4780 4781 // We need to maintain the offsets for the right and the left hand side 4782 // separately to check if every possible indexed expression is a valid 4783 // string literal. They might have different offsets for different string 4784 // literals in the end. 4785 StringLiteralCheckType Left; 4786 if (!CheckLeft) 4787 Left = SLCT_UncheckedLiteral; 4788 else { 4789 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 4790 HasVAListArg, format_idx, firstDataArg, 4791 Type, CallType, InFunctionCall, 4792 CheckedVarArgs, UncoveredArg, Offset); 4793 if (Left == SLCT_NotALiteral || !CheckRight) { 4794 return Left; 4795 } 4796 } 4797 4798 StringLiteralCheckType Right = 4799 checkFormatStringExpr(S, C->getFalseExpr(), Args, 4800 HasVAListArg, format_idx, firstDataArg, 4801 Type, CallType, InFunctionCall, CheckedVarArgs, 4802 UncoveredArg, Offset); 4803 4804 return (CheckLeft && Left < Right) ? Left : Right; 4805 } 4806 4807 case Stmt::ImplicitCastExprClass: { 4808 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4809 goto tryAgain; 4810 } 4811 4812 case Stmt::OpaqueValueExprClass: 4813 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 4814 E = src; 4815 goto tryAgain; 4816 } 4817 return SLCT_NotALiteral; 4818 4819 case Stmt::PredefinedExprClass: 4820 // While __func__, etc., are technically not string literals, they 4821 // cannot contain format specifiers and thus are not a security 4822 // liability. 4823 return SLCT_UncheckedLiteral; 4824 4825 case Stmt::DeclRefExprClass: { 4826 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 4827 4828 // As an exception, do not flag errors for variables binding to 4829 // const string literals. 4830 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 4831 bool isConstant = false; 4832 QualType T = DR->getType(); 4833 4834 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 4835 isConstant = AT->getElementType().isConstant(S.Context); 4836 } else if (const PointerType *PT = T->getAs<PointerType>()) { 4837 isConstant = T.isConstant(S.Context) && 4838 PT->getPointeeType().isConstant(S.Context); 4839 } else if (T->isObjCObjectPointerType()) { 4840 // In ObjC, there is usually no "const ObjectPointer" type, 4841 // so don't check if the pointee type is constant. 4842 isConstant = T.isConstant(S.Context); 4843 } 4844 4845 if (isConstant) { 4846 if (const Expr *Init = VD->getAnyInitializer()) { 4847 // Look through initializers like const char c[] = { "foo" } 4848 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4849 if (InitList->isStringLiteralInit()) 4850 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 4851 } 4852 return checkFormatStringExpr(S, Init, Args, 4853 HasVAListArg, format_idx, 4854 firstDataArg, Type, CallType, 4855 /*InFunctionCall*/ false, CheckedVarArgs, 4856 UncoveredArg, Offset); 4857 } 4858 } 4859 4860 // For vprintf* functions (i.e., HasVAListArg==true), we add a 4861 // special check to see if the format string is a function parameter 4862 // of the function calling the printf function. If the function 4863 // has an attribute indicating it is a printf-like function, then we 4864 // should suppress warnings concerning non-literals being used in a call 4865 // to a vprintf function. For example: 4866 // 4867 // void 4868 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 4869 // va_list ap; 4870 // va_start(ap, fmt); 4871 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 4872 // ... 4873 // } 4874 if (HasVAListArg) { 4875 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 4876 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 4877 int PVIndex = PV->getFunctionScopeIndex() + 1; 4878 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 4879 // adjust for implicit parameter 4880 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4881 if (MD->isInstance()) 4882 ++PVIndex; 4883 // We also check if the formats are compatible. 4884 // We can't pass a 'scanf' string to a 'printf' function. 4885 if (PVIndex == PVFormat->getFormatIdx() && 4886 Type == S.GetFormatStringType(PVFormat)) 4887 return SLCT_UncheckedLiteral; 4888 } 4889 } 4890 } 4891 } 4892 } 4893 4894 return SLCT_NotALiteral; 4895 } 4896 4897 case Stmt::CallExprClass: 4898 case Stmt::CXXMemberCallExprClass: { 4899 const CallExpr *CE = cast<CallExpr>(E); 4900 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 4901 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 4902 unsigned ArgIndex = FA->getFormatIdx(); 4903 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4904 if (MD->isInstance()) 4905 --ArgIndex; 4906 const Expr *Arg = CE->getArg(ArgIndex - 1); 4907 4908 return checkFormatStringExpr(S, Arg, Args, 4909 HasVAListArg, format_idx, firstDataArg, 4910 Type, CallType, InFunctionCall, 4911 CheckedVarArgs, UncoveredArg, Offset); 4912 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 4913 unsigned BuiltinID = FD->getBuiltinID(); 4914 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 4915 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 4916 const Expr *Arg = CE->getArg(0); 4917 return checkFormatStringExpr(S, Arg, Args, 4918 HasVAListArg, format_idx, 4919 firstDataArg, Type, CallType, 4920 InFunctionCall, CheckedVarArgs, 4921 UncoveredArg, Offset); 4922 } 4923 } 4924 } 4925 4926 return SLCT_NotALiteral; 4927 } 4928 case Stmt::ObjCMessageExprClass: { 4929 const auto *ME = cast<ObjCMessageExpr>(E); 4930 if (const auto *ND = ME->getMethodDecl()) { 4931 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 4932 unsigned ArgIndex = FA->getFormatIdx(); 4933 const Expr *Arg = ME->getArg(ArgIndex - 1); 4934 return checkFormatStringExpr( 4935 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 4936 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 4937 } 4938 } 4939 4940 return SLCT_NotALiteral; 4941 } 4942 case Stmt::ObjCStringLiteralClass: 4943 case Stmt::StringLiteralClass: { 4944 const StringLiteral *StrE = nullptr; 4945 4946 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 4947 StrE = ObjCFExpr->getString(); 4948 else 4949 StrE = cast<StringLiteral>(E); 4950 4951 if (StrE) { 4952 if (Offset.isNegative() || Offset > StrE->getLength()) { 4953 // TODO: It would be better to have an explicit warning for out of 4954 // bounds literals. 4955 return SLCT_NotALiteral; 4956 } 4957 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 4958 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 4959 firstDataArg, Type, InFunctionCall, CallType, 4960 CheckedVarArgs, UncoveredArg); 4961 return SLCT_CheckedLiteral; 4962 } 4963 4964 return SLCT_NotALiteral; 4965 } 4966 case Stmt::BinaryOperatorClass: { 4967 llvm::APSInt LResult; 4968 llvm::APSInt RResult; 4969 4970 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 4971 4972 // A string literal + an int offset is still a string literal. 4973 if (BinOp->isAdditiveOp()) { 4974 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 4975 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 4976 4977 if (LIsInt != RIsInt) { 4978 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 4979 4980 if (LIsInt) { 4981 if (BinOpKind == BO_Add) { 4982 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 4983 E = BinOp->getRHS(); 4984 goto tryAgain; 4985 } 4986 } else { 4987 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 4988 E = BinOp->getLHS(); 4989 goto tryAgain; 4990 } 4991 } 4992 } 4993 4994 return SLCT_NotALiteral; 4995 } 4996 case Stmt::UnaryOperatorClass: { 4997 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 4998 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 4999 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) { 5000 llvm::APSInt IndexResult; 5001 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 5002 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 5003 E = ASE->getBase(); 5004 goto tryAgain; 5005 } 5006 } 5007 5008 return SLCT_NotALiteral; 5009 } 5010 5011 default: 5012 return SLCT_NotALiteral; 5013 } 5014 } 5015 5016 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 5017 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 5018 .Case("scanf", FST_Scanf) 5019 .Cases("printf", "printf0", FST_Printf) 5020 .Cases("NSString", "CFString", FST_NSString) 5021 .Case("strftime", FST_Strftime) 5022 .Case("strfmon", FST_Strfmon) 5023 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 5024 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 5025 .Case("os_trace", FST_OSLog) 5026 .Case("os_log", FST_OSLog) 5027 .Default(FST_Unknown); 5028 } 5029 5030 /// CheckFormatArguments - Check calls to printf and scanf (and similar 5031 /// functions) for correct use of format strings. 5032 /// Returns true if a format string has been fully checked. 5033 bool Sema::CheckFormatArguments(const FormatAttr *Format, 5034 ArrayRef<const Expr *> Args, 5035 bool IsCXXMember, 5036 VariadicCallType CallType, 5037 SourceLocation Loc, SourceRange Range, 5038 llvm::SmallBitVector &CheckedVarArgs) { 5039 FormatStringInfo FSI; 5040 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 5041 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 5042 FSI.FirstDataArg, GetFormatStringType(Format), 5043 CallType, Loc, Range, CheckedVarArgs); 5044 return false; 5045 } 5046 5047 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 5048 bool HasVAListArg, unsigned format_idx, 5049 unsigned firstDataArg, FormatStringType Type, 5050 VariadicCallType CallType, 5051 SourceLocation Loc, SourceRange Range, 5052 llvm::SmallBitVector &CheckedVarArgs) { 5053 // CHECK: printf/scanf-like function is called with no format string. 5054 if (format_idx >= Args.size()) { 5055 Diag(Loc, diag::warn_missing_format_string) << Range; 5056 return false; 5057 } 5058 5059 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 5060 5061 // CHECK: format string is not a string literal. 5062 // 5063 // Dynamically generated format strings are difficult to 5064 // automatically vet at compile time. Requiring that format strings 5065 // are string literals: (1) permits the checking of format strings by 5066 // the compiler and thereby (2) can practically remove the source of 5067 // many format string exploits. 5068 5069 // Format string can be either ObjC string (e.g. @"%d") or 5070 // C string (e.g. "%d") 5071 // ObjC string uses the same format specifiers as C string, so we can use 5072 // the same format string checking logic for both ObjC and C strings. 5073 UncoveredArgHandler UncoveredArg; 5074 StringLiteralCheckType CT = 5075 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 5076 format_idx, firstDataArg, Type, CallType, 5077 /*IsFunctionCall*/ true, CheckedVarArgs, 5078 UncoveredArg, 5079 /*no string offset*/ llvm::APSInt(64, false) = 0); 5080 5081 // Generate a diagnostic where an uncovered argument is detected. 5082 if (UncoveredArg.hasUncoveredArg()) { 5083 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 5084 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 5085 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 5086 } 5087 5088 if (CT != SLCT_NotALiteral) 5089 // Literal format string found, check done! 5090 return CT == SLCT_CheckedLiteral; 5091 5092 // Strftime is particular as it always uses a single 'time' argument, 5093 // so it is safe to pass a non-literal string. 5094 if (Type == FST_Strftime) 5095 return false; 5096 5097 // Do not emit diag when the string param is a macro expansion and the 5098 // format is either NSString or CFString. This is a hack to prevent 5099 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 5100 // which are usually used in place of NS and CF string literals. 5101 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 5102 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 5103 return false; 5104 5105 // If there are no arguments specified, warn with -Wformat-security, otherwise 5106 // warn only with -Wformat-nonliteral. 5107 if (Args.size() == firstDataArg) { 5108 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 5109 << OrigFormatExpr->getSourceRange(); 5110 switch (Type) { 5111 default: 5112 break; 5113 case FST_Kprintf: 5114 case FST_FreeBSDKPrintf: 5115 case FST_Printf: 5116 Diag(FormatLoc, diag::note_format_security_fixit) 5117 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 5118 break; 5119 case FST_NSString: 5120 Diag(FormatLoc, diag::note_format_security_fixit) 5121 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 5122 break; 5123 } 5124 } else { 5125 Diag(FormatLoc, diag::warn_format_nonliteral) 5126 << OrigFormatExpr->getSourceRange(); 5127 } 5128 return false; 5129 } 5130 5131 namespace { 5132 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 5133 protected: 5134 Sema &S; 5135 const FormatStringLiteral *FExpr; 5136 const Expr *OrigFormatExpr; 5137 const Sema::FormatStringType FSType; 5138 const unsigned FirstDataArg; 5139 const unsigned NumDataArgs; 5140 const char *Beg; // Start of format string. 5141 const bool HasVAListArg; 5142 ArrayRef<const Expr *> Args; 5143 unsigned FormatIdx; 5144 llvm::SmallBitVector CoveredArgs; 5145 bool usesPositionalArgs; 5146 bool atFirstArg; 5147 bool inFunctionCall; 5148 Sema::VariadicCallType CallType; 5149 llvm::SmallBitVector &CheckedVarArgs; 5150 UncoveredArgHandler &UncoveredArg; 5151 5152 public: 5153 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 5154 const Expr *origFormatExpr, 5155 const Sema::FormatStringType type, unsigned firstDataArg, 5156 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5157 ArrayRef<const Expr *> Args, unsigned formatIdx, 5158 bool inFunctionCall, Sema::VariadicCallType callType, 5159 llvm::SmallBitVector &CheckedVarArgs, 5160 UncoveredArgHandler &UncoveredArg) 5161 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 5162 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 5163 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 5164 usesPositionalArgs(false), atFirstArg(true), 5165 inFunctionCall(inFunctionCall), CallType(callType), 5166 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 5167 CoveredArgs.resize(numDataArgs); 5168 CoveredArgs.reset(); 5169 } 5170 5171 void DoneProcessing(); 5172 5173 void HandleIncompleteSpecifier(const char *startSpecifier, 5174 unsigned specifierLen) override; 5175 5176 void HandleInvalidLengthModifier( 5177 const analyze_format_string::FormatSpecifier &FS, 5178 const analyze_format_string::ConversionSpecifier &CS, 5179 const char *startSpecifier, unsigned specifierLen, 5180 unsigned DiagID); 5181 5182 void HandleNonStandardLengthModifier( 5183 const analyze_format_string::FormatSpecifier &FS, 5184 const char *startSpecifier, unsigned specifierLen); 5185 5186 void HandleNonStandardConversionSpecifier( 5187 const analyze_format_string::ConversionSpecifier &CS, 5188 const char *startSpecifier, unsigned specifierLen); 5189 5190 void HandlePosition(const char *startPos, unsigned posLen) override; 5191 5192 void HandleInvalidPosition(const char *startSpecifier, 5193 unsigned specifierLen, 5194 analyze_format_string::PositionContext p) override; 5195 5196 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 5197 5198 void HandleNullChar(const char *nullCharacter) override; 5199 5200 template <typename Range> 5201 static void 5202 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 5203 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 5204 bool IsStringLocation, Range StringRange, 5205 ArrayRef<FixItHint> Fixit = None); 5206 5207 protected: 5208 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 5209 const char *startSpec, 5210 unsigned specifierLen, 5211 const char *csStart, unsigned csLen); 5212 5213 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 5214 const char *startSpec, 5215 unsigned specifierLen); 5216 5217 SourceRange getFormatStringRange(); 5218 CharSourceRange getSpecifierRange(const char *startSpecifier, 5219 unsigned specifierLen); 5220 SourceLocation getLocationOfByte(const char *x); 5221 5222 const Expr *getDataArg(unsigned i) const; 5223 5224 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 5225 const analyze_format_string::ConversionSpecifier &CS, 5226 const char *startSpecifier, unsigned specifierLen, 5227 unsigned argIndex); 5228 5229 template <typename Range> 5230 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5231 bool IsStringLocation, Range StringRange, 5232 ArrayRef<FixItHint> Fixit = None); 5233 }; 5234 } // end anonymous namespace 5235 5236 SourceRange CheckFormatHandler::getFormatStringRange() { 5237 return OrigFormatExpr->getSourceRange(); 5238 } 5239 5240 CharSourceRange CheckFormatHandler:: 5241 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 5242 SourceLocation Start = getLocationOfByte(startSpecifier); 5243 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 5244 5245 // Advance the end SourceLocation by one due to half-open ranges. 5246 End = End.getLocWithOffset(1); 5247 5248 return CharSourceRange::getCharRange(Start, End); 5249 } 5250 5251 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 5252 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 5253 S.getLangOpts(), S.Context.getTargetInfo()); 5254 } 5255 5256 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 5257 unsigned specifierLen){ 5258 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 5259 getLocationOfByte(startSpecifier), 5260 /*IsStringLocation*/true, 5261 getSpecifierRange(startSpecifier, specifierLen)); 5262 } 5263 5264 void CheckFormatHandler::HandleInvalidLengthModifier( 5265 const analyze_format_string::FormatSpecifier &FS, 5266 const analyze_format_string::ConversionSpecifier &CS, 5267 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 5268 using namespace analyze_format_string; 5269 5270 const LengthModifier &LM = FS.getLengthModifier(); 5271 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5272 5273 // See if we know how to fix this length modifier. 5274 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5275 if (FixedLM) { 5276 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5277 getLocationOfByte(LM.getStart()), 5278 /*IsStringLocation*/true, 5279 getSpecifierRange(startSpecifier, specifierLen)); 5280 5281 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5282 << FixedLM->toString() 5283 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5284 5285 } else { 5286 FixItHint Hint; 5287 if (DiagID == diag::warn_format_nonsensical_length) 5288 Hint = FixItHint::CreateRemoval(LMRange); 5289 5290 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5291 getLocationOfByte(LM.getStart()), 5292 /*IsStringLocation*/true, 5293 getSpecifierRange(startSpecifier, specifierLen), 5294 Hint); 5295 } 5296 } 5297 5298 void CheckFormatHandler::HandleNonStandardLengthModifier( 5299 const analyze_format_string::FormatSpecifier &FS, 5300 const char *startSpecifier, unsigned specifierLen) { 5301 using namespace analyze_format_string; 5302 5303 const LengthModifier &LM = FS.getLengthModifier(); 5304 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5305 5306 // See if we know how to fix this length modifier. 5307 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5308 if (FixedLM) { 5309 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5310 << LM.toString() << 0, 5311 getLocationOfByte(LM.getStart()), 5312 /*IsStringLocation*/true, 5313 getSpecifierRange(startSpecifier, specifierLen)); 5314 5315 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5316 << FixedLM->toString() 5317 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5318 5319 } else { 5320 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5321 << LM.toString() << 0, 5322 getLocationOfByte(LM.getStart()), 5323 /*IsStringLocation*/true, 5324 getSpecifierRange(startSpecifier, specifierLen)); 5325 } 5326 } 5327 5328 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5329 const analyze_format_string::ConversionSpecifier &CS, 5330 const char *startSpecifier, unsigned specifierLen) { 5331 using namespace analyze_format_string; 5332 5333 // See if we know how to fix this conversion specifier. 5334 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5335 if (FixedCS) { 5336 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5337 << CS.toString() << /*conversion specifier*/1, 5338 getLocationOfByte(CS.getStart()), 5339 /*IsStringLocation*/true, 5340 getSpecifierRange(startSpecifier, specifierLen)); 5341 5342 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5343 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5344 << FixedCS->toString() 5345 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5346 } else { 5347 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5348 << CS.toString() << /*conversion specifier*/1, 5349 getLocationOfByte(CS.getStart()), 5350 /*IsStringLocation*/true, 5351 getSpecifierRange(startSpecifier, specifierLen)); 5352 } 5353 } 5354 5355 void CheckFormatHandler::HandlePosition(const char *startPos, 5356 unsigned posLen) { 5357 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5358 getLocationOfByte(startPos), 5359 /*IsStringLocation*/true, 5360 getSpecifierRange(startPos, posLen)); 5361 } 5362 5363 void 5364 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5365 analyze_format_string::PositionContext p) { 5366 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5367 << (unsigned) p, 5368 getLocationOfByte(startPos), /*IsStringLocation*/true, 5369 getSpecifierRange(startPos, posLen)); 5370 } 5371 5372 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5373 unsigned posLen) { 5374 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5375 getLocationOfByte(startPos), 5376 /*IsStringLocation*/true, 5377 getSpecifierRange(startPos, posLen)); 5378 } 5379 5380 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5381 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5382 // The presence of a null character is likely an error. 5383 EmitFormatDiagnostic( 5384 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5385 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5386 getFormatStringRange()); 5387 } 5388 } 5389 5390 // Note that this may return NULL if there was an error parsing or building 5391 // one of the argument expressions. 5392 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5393 return Args[FirstDataArg + i]; 5394 } 5395 5396 void CheckFormatHandler::DoneProcessing() { 5397 // Does the number of data arguments exceed the number of 5398 // format conversions in the format string? 5399 if (!HasVAListArg) { 5400 // Find any arguments that weren't covered. 5401 CoveredArgs.flip(); 5402 signed notCoveredArg = CoveredArgs.find_first(); 5403 if (notCoveredArg >= 0) { 5404 assert((unsigned)notCoveredArg < NumDataArgs); 5405 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 5406 } else { 5407 UncoveredArg.setAllCovered(); 5408 } 5409 } 5410 } 5411 5412 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 5413 const Expr *ArgExpr) { 5414 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 5415 "Invalid state"); 5416 5417 if (!ArgExpr) 5418 return; 5419 5420 SourceLocation Loc = ArgExpr->getLocStart(); 5421 5422 if (S.getSourceManager().isInSystemMacro(Loc)) 5423 return; 5424 5425 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 5426 for (auto E : DiagnosticExprs) 5427 PDiag << E->getSourceRange(); 5428 5429 CheckFormatHandler::EmitFormatDiagnostic( 5430 S, IsFunctionCall, DiagnosticExprs[0], 5431 PDiag, Loc, /*IsStringLocation*/false, 5432 DiagnosticExprs[0]->getSourceRange()); 5433 } 5434 5435 bool 5436 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 5437 SourceLocation Loc, 5438 const char *startSpec, 5439 unsigned specifierLen, 5440 const char *csStart, 5441 unsigned csLen) { 5442 bool keepGoing = true; 5443 if (argIndex < NumDataArgs) { 5444 // Consider the argument coverered, even though the specifier doesn't 5445 // make sense. 5446 CoveredArgs.set(argIndex); 5447 } 5448 else { 5449 // If argIndex exceeds the number of data arguments we 5450 // don't issue a warning because that is just a cascade of warnings (and 5451 // they may have intended '%%' anyway). We don't want to continue processing 5452 // the format string after this point, however, as we will like just get 5453 // gibberish when trying to match arguments. 5454 keepGoing = false; 5455 } 5456 5457 StringRef Specifier(csStart, csLen); 5458 5459 // If the specifier in non-printable, it could be the first byte of a UTF-8 5460 // sequence. In that case, print the UTF-8 code point. If not, print the byte 5461 // hex value. 5462 std::string CodePointStr; 5463 if (!llvm::sys::locale::isPrint(*csStart)) { 5464 llvm::UTF32 CodePoint; 5465 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 5466 const llvm::UTF8 *E = 5467 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 5468 llvm::ConversionResult Result = 5469 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 5470 5471 if (Result != llvm::conversionOK) { 5472 unsigned char FirstChar = *csStart; 5473 CodePoint = (llvm::UTF32)FirstChar; 5474 } 5475 5476 llvm::raw_string_ostream OS(CodePointStr); 5477 if (CodePoint < 256) 5478 OS << "\\x" << llvm::format("%02x", CodePoint); 5479 else if (CodePoint <= 0xFFFF) 5480 OS << "\\u" << llvm::format("%04x", CodePoint); 5481 else 5482 OS << "\\U" << llvm::format("%08x", CodePoint); 5483 OS.flush(); 5484 Specifier = CodePointStr; 5485 } 5486 5487 EmitFormatDiagnostic( 5488 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 5489 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 5490 5491 return keepGoing; 5492 } 5493 5494 void 5495 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 5496 const char *startSpec, 5497 unsigned specifierLen) { 5498 EmitFormatDiagnostic( 5499 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 5500 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 5501 } 5502 5503 bool 5504 CheckFormatHandler::CheckNumArgs( 5505 const analyze_format_string::FormatSpecifier &FS, 5506 const analyze_format_string::ConversionSpecifier &CS, 5507 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 5508 5509 if (argIndex >= NumDataArgs) { 5510 PartialDiagnostic PDiag = FS.usesPositionalArg() 5511 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 5512 << (argIndex+1) << NumDataArgs) 5513 : S.PDiag(diag::warn_printf_insufficient_data_args); 5514 EmitFormatDiagnostic( 5515 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 5516 getSpecifierRange(startSpecifier, specifierLen)); 5517 5518 // Since more arguments than conversion tokens are given, by extension 5519 // all arguments are covered, so mark this as so. 5520 UncoveredArg.setAllCovered(); 5521 return false; 5522 } 5523 return true; 5524 } 5525 5526 template<typename Range> 5527 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 5528 SourceLocation Loc, 5529 bool IsStringLocation, 5530 Range StringRange, 5531 ArrayRef<FixItHint> FixIt) { 5532 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 5533 Loc, IsStringLocation, StringRange, FixIt); 5534 } 5535 5536 /// \brief If the format string is not within the funcion call, emit a note 5537 /// so that the function call and string are in diagnostic messages. 5538 /// 5539 /// \param InFunctionCall if true, the format string is within the function 5540 /// call and only one diagnostic message will be produced. Otherwise, an 5541 /// extra note will be emitted pointing to location of the format string. 5542 /// 5543 /// \param ArgumentExpr the expression that is passed as the format string 5544 /// argument in the function call. Used for getting locations when two 5545 /// diagnostics are emitted. 5546 /// 5547 /// \param PDiag the callee should already have provided any strings for the 5548 /// diagnostic message. This function only adds locations and fixits 5549 /// to diagnostics. 5550 /// 5551 /// \param Loc primary location for diagnostic. If two diagnostics are 5552 /// required, one will be at Loc and a new SourceLocation will be created for 5553 /// the other one. 5554 /// 5555 /// \param IsStringLocation if true, Loc points to the format string should be 5556 /// used for the note. Otherwise, Loc points to the argument list and will 5557 /// be used with PDiag. 5558 /// 5559 /// \param StringRange some or all of the string to highlight. This is 5560 /// templated so it can accept either a CharSourceRange or a SourceRange. 5561 /// 5562 /// \param FixIt optional fix it hint for the format string. 5563 template <typename Range> 5564 void CheckFormatHandler::EmitFormatDiagnostic( 5565 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 5566 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 5567 Range StringRange, ArrayRef<FixItHint> FixIt) { 5568 if (InFunctionCall) { 5569 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 5570 D << StringRange; 5571 D << FixIt; 5572 } else { 5573 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 5574 << ArgumentExpr->getSourceRange(); 5575 5576 const Sema::SemaDiagnosticBuilder &Note = 5577 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 5578 diag::note_format_string_defined); 5579 5580 Note << StringRange; 5581 Note << FixIt; 5582 } 5583 } 5584 5585 //===--- CHECK: Printf format string checking ------------------------------===// 5586 5587 namespace { 5588 class CheckPrintfHandler : public CheckFormatHandler { 5589 public: 5590 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 5591 const Expr *origFormatExpr, 5592 const Sema::FormatStringType type, unsigned firstDataArg, 5593 unsigned numDataArgs, bool isObjC, const char *beg, 5594 bool hasVAListArg, ArrayRef<const Expr *> Args, 5595 unsigned formatIdx, bool inFunctionCall, 5596 Sema::VariadicCallType CallType, 5597 llvm::SmallBitVector &CheckedVarArgs, 5598 UncoveredArgHandler &UncoveredArg) 5599 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 5600 numDataArgs, beg, hasVAListArg, Args, formatIdx, 5601 inFunctionCall, CallType, CheckedVarArgs, 5602 UncoveredArg) {} 5603 5604 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 5605 5606 /// Returns true if '%@' specifiers are allowed in the format string. 5607 bool allowsObjCArg() const { 5608 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 5609 FSType == Sema::FST_OSTrace; 5610 } 5611 5612 bool HandleInvalidPrintfConversionSpecifier( 5613 const analyze_printf::PrintfSpecifier &FS, 5614 const char *startSpecifier, 5615 unsigned specifierLen) override; 5616 5617 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 5618 const char *startSpecifier, 5619 unsigned specifierLen) override; 5620 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5621 const char *StartSpecifier, 5622 unsigned SpecifierLen, 5623 const Expr *E); 5624 5625 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 5626 const char *startSpecifier, unsigned specifierLen); 5627 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 5628 const analyze_printf::OptionalAmount &Amt, 5629 unsigned type, 5630 const char *startSpecifier, unsigned specifierLen); 5631 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5632 const analyze_printf::OptionalFlag &flag, 5633 const char *startSpecifier, unsigned specifierLen); 5634 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 5635 const analyze_printf::OptionalFlag &ignoredFlag, 5636 const analyze_printf::OptionalFlag &flag, 5637 const char *startSpecifier, unsigned specifierLen); 5638 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 5639 const Expr *E); 5640 5641 void HandleEmptyObjCModifierFlag(const char *startFlag, 5642 unsigned flagLen) override; 5643 5644 void HandleInvalidObjCModifierFlag(const char *startFlag, 5645 unsigned flagLen) override; 5646 5647 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 5648 const char *flagsEnd, 5649 const char *conversionPosition) 5650 override; 5651 }; 5652 } // end anonymous namespace 5653 5654 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 5655 const analyze_printf::PrintfSpecifier &FS, 5656 const char *startSpecifier, 5657 unsigned specifierLen) { 5658 const analyze_printf::PrintfConversionSpecifier &CS = 5659 FS.getConversionSpecifier(); 5660 5661 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5662 getLocationOfByte(CS.getStart()), 5663 startSpecifier, specifierLen, 5664 CS.getStart(), CS.getLength()); 5665 } 5666 5667 bool CheckPrintfHandler::HandleAmount( 5668 const analyze_format_string::OptionalAmount &Amt, 5669 unsigned k, const char *startSpecifier, 5670 unsigned specifierLen) { 5671 if (Amt.hasDataArgument()) { 5672 if (!HasVAListArg) { 5673 unsigned argIndex = Amt.getArgIndex(); 5674 if (argIndex >= NumDataArgs) { 5675 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 5676 << k, 5677 getLocationOfByte(Amt.getStart()), 5678 /*IsStringLocation*/true, 5679 getSpecifierRange(startSpecifier, specifierLen)); 5680 // Don't do any more checking. We will just emit 5681 // spurious errors. 5682 return false; 5683 } 5684 5685 // Type check the data argument. It should be an 'int'. 5686 // Although not in conformance with C99, we also allow the argument to be 5687 // an 'unsigned int' as that is a reasonably safe case. GCC also 5688 // doesn't emit a warning for that case. 5689 CoveredArgs.set(argIndex); 5690 const Expr *Arg = getDataArg(argIndex); 5691 if (!Arg) 5692 return false; 5693 5694 QualType T = Arg->getType(); 5695 5696 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 5697 assert(AT.isValid()); 5698 5699 if (!AT.matchesType(S.Context, T)) { 5700 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 5701 << k << AT.getRepresentativeTypeName(S.Context) 5702 << T << Arg->getSourceRange(), 5703 getLocationOfByte(Amt.getStart()), 5704 /*IsStringLocation*/true, 5705 getSpecifierRange(startSpecifier, specifierLen)); 5706 // Don't do any more checking. We will just emit 5707 // spurious errors. 5708 return false; 5709 } 5710 } 5711 } 5712 return true; 5713 } 5714 5715 void CheckPrintfHandler::HandleInvalidAmount( 5716 const analyze_printf::PrintfSpecifier &FS, 5717 const analyze_printf::OptionalAmount &Amt, 5718 unsigned type, 5719 const char *startSpecifier, 5720 unsigned specifierLen) { 5721 const analyze_printf::PrintfConversionSpecifier &CS = 5722 FS.getConversionSpecifier(); 5723 5724 FixItHint fixit = 5725 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 5726 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 5727 Amt.getConstantLength())) 5728 : FixItHint(); 5729 5730 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 5731 << type << CS.toString(), 5732 getLocationOfByte(Amt.getStart()), 5733 /*IsStringLocation*/true, 5734 getSpecifierRange(startSpecifier, specifierLen), 5735 fixit); 5736 } 5737 5738 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5739 const analyze_printf::OptionalFlag &flag, 5740 const char *startSpecifier, 5741 unsigned specifierLen) { 5742 // Warn about pointless flag with a fixit removal. 5743 const analyze_printf::PrintfConversionSpecifier &CS = 5744 FS.getConversionSpecifier(); 5745 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 5746 << flag.toString() << CS.toString(), 5747 getLocationOfByte(flag.getPosition()), 5748 /*IsStringLocation*/true, 5749 getSpecifierRange(startSpecifier, specifierLen), 5750 FixItHint::CreateRemoval( 5751 getSpecifierRange(flag.getPosition(), 1))); 5752 } 5753 5754 void CheckPrintfHandler::HandleIgnoredFlag( 5755 const analyze_printf::PrintfSpecifier &FS, 5756 const analyze_printf::OptionalFlag &ignoredFlag, 5757 const analyze_printf::OptionalFlag &flag, 5758 const char *startSpecifier, 5759 unsigned specifierLen) { 5760 // Warn about ignored flag with a fixit removal. 5761 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 5762 << ignoredFlag.toString() << flag.toString(), 5763 getLocationOfByte(ignoredFlag.getPosition()), 5764 /*IsStringLocation*/true, 5765 getSpecifierRange(startSpecifier, specifierLen), 5766 FixItHint::CreateRemoval( 5767 getSpecifierRange(ignoredFlag.getPosition(), 1))); 5768 } 5769 5770 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5771 // bool IsStringLocation, Range StringRange, 5772 // ArrayRef<FixItHint> Fixit = None); 5773 5774 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 5775 unsigned flagLen) { 5776 // Warn about an empty flag. 5777 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 5778 getLocationOfByte(startFlag), 5779 /*IsStringLocation*/true, 5780 getSpecifierRange(startFlag, flagLen)); 5781 } 5782 5783 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 5784 unsigned flagLen) { 5785 // Warn about an invalid flag. 5786 auto Range = getSpecifierRange(startFlag, flagLen); 5787 StringRef flag(startFlag, flagLen); 5788 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 5789 getLocationOfByte(startFlag), 5790 /*IsStringLocation*/true, 5791 Range, FixItHint::CreateRemoval(Range)); 5792 } 5793 5794 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 5795 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 5796 // Warn about using '[...]' without a '@' conversion. 5797 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 5798 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 5799 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 5800 getLocationOfByte(conversionPosition), 5801 /*IsStringLocation*/true, 5802 Range, FixItHint::CreateRemoval(Range)); 5803 } 5804 5805 // Determines if the specified is a C++ class or struct containing 5806 // a member with the specified name and kind (e.g. a CXXMethodDecl named 5807 // "c_str()"). 5808 template<typename MemberKind> 5809 static llvm::SmallPtrSet<MemberKind*, 1> 5810 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 5811 const RecordType *RT = Ty->getAs<RecordType>(); 5812 llvm::SmallPtrSet<MemberKind*, 1> Results; 5813 5814 if (!RT) 5815 return Results; 5816 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 5817 if (!RD || !RD->getDefinition()) 5818 return Results; 5819 5820 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 5821 Sema::LookupMemberName); 5822 R.suppressDiagnostics(); 5823 5824 // We just need to include all members of the right kind turned up by the 5825 // filter, at this point. 5826 if (S.LookupQualifiedName(R, RT->getDecl())) 5827 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 5828 NamedDecl *decl = (*I)->getUnderlyingDecl(); 5829 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 5830 Results.insert(FK); 5831 } 5832 return Results; 5833 } 5834 5835 /// Check if we could call '.c_str()' on an object. 5836 /// 5837 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 5838 /// allow the call, or if it would be ambiguous). 5839 bool Sema::hasCStrMethod(const Expr *E) { 5840 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5841 MethodSet Results = 5842 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 5843 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5844 MI != ME; ++MI) 5845 if ((*MI)->getMinRequiredArguments() == 0) 5846 return true; 5847 return false; 5848 } 5849 5850 // Check if a (w)string was passed when a (w)char* was needed, and offer a 5851 // better diagnostic if so. AT is assumed to be valid. 5852 // Returns true when a c_str() conversion method is found. 5853 bool CheckPrintfHandler::checkForCStrMembers( 5854 const analyze_printf::ArgType &AT, const Expr *E) { 5855 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5856 5857 MethodSet Results = 5858 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 5859 5860 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5861 MI != ME; ++MI) { 5862 const CXXMethodDecl *Method = *MI; 5863 if (Method->getMinRequiredArguments() == 0 && 5864 AT.matchesType(S.Context, Method->getReturnType())) { 5865 // FIXME: Suggest parens if the expression needs them. 5866 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 5867 S.Diag(E->getLocStart(), diag::note_printf_c_str) 5868 << "c_str()" 5869 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 5870 return true; 5871 } 5872 } 5873 5874 return false; 5875 } 5876 5877 bool 5878 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 5879 &FS, 5880 const char *startSpecifier, 5881 unsigned specifierLen) { 5882 using namespace analyze_format_string; 5883 using namespace analyze_printf; 5884 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 5885 5886 if (FS.consumesDataArgument()) { 5887 if (atFirstArg) { 5888 atFirstArg = false; 5889 usesPositionalArgs = FS.usesPositionalArg(); 5890 } 5891 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5892 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5893 startSpecifier, specifierLen); 5894 return false; 5895 } 5896 } 5897 5898 // First check if the field width, precision, and conversion specifier 5899 // have matching data arguments. 5900 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 5901 startSpecifier, specifierLen)) { 5902 return false; 5903 } 5904 5905 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 5906 startSpecifier, specifierLen)) { 5907 return false; 5908 } 5909 5910 if (!CS.consumesDataArgument()) { 5911 // FIXME: Technically specifying a precision or field width here 5912 // makes no sense. Worth issuing a warning at some point. 5913 return true; 5914 } 5915 5916 // Consume the argument. 5917 unsigned argIndex = FS.getArgIndex(); 5918 if (argIndex < NumDataArgs) { 5919 // The check to see if the argIndex is valid will come later. 5920 // We set the bit here because we may exit early from this 5921 // function if we encounter some other error. 5922 CoveredArgs.set(argIndex); 5923 } 5924 5925 // FreeBSD kernel extensions. 5926 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 5927 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 5928 // We need at least two arguments. 5929 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 5930 return false; 5931 5932 // Claim the second argument. 5933 CoveredArgs.set(argIndex + 1); 5934 5935 // Type check the first argument (int for %b, pointer for %D) 5936 const Expr *Ex = getDataArg(argIndex); 5937 const analyze_printf::ArgType &AT = 5938 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 5939 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 5940 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 5941 EmitFormatDiagnostic( 5942 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5943 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 5944 << false << Ex->getSourceRange(), 5945 Ex->getLocStart(), /*IsStringLocation*/false, 5946 getSpecifierRange(startSpecifier, specifierLen)); 5947 5948 // Type check the second argument (char * for both %b and %D) 5949 Ex = getDataArg(argIndex + 1); 5950 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 5951 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 5952 EmitFormatDiagnostic( 5953 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5954 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 5955 << false << Ex->getSourceRange(), 5956 Ex->getLocStart(), /*IsStringLocation*/false, 5957 getSpecifierRange(startSpecifier, specifierLen)); 5958 5959 return true; 5960 } 5961 5962 // Check for using an Objective-C specific conversion specifier 5963 // in a non-ObjC literal. 5964 if (!allowsObjCArg() && CS.isObjCArg()) { 5965 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5966 specifierLen); 5967 } 5968 5969 // %P can only be used with os_log. 5970 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 5971 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5972 specifierLen); 5973 } 5974 5975 // %n is not allowed with os_log. 5976 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 5977 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 5978 getLocationOfByte(CS.getStart()), 5979 /*IsStringLocation*/ false, 5980 getSpecifierRange(startSpecifier, specifierLen)); 5981 5982 return true; 5983 } 5984 5985 // Only scalars are allowed for os_trace. 5986 if (FSType == Sema::FST_OSTrace && 5987 (CS.getKind() == ConversionSpecifier::PArg || 5988 CS.getKind() == ConversionSpecifier::sArg || 5989 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 5990 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5991 specifierLen); 5992 } 5993 5994 // Check for use of public/private annotation outside of os_log(). 5995 if (FSType != Sema::FST_OSLog) { 5996 if (FS.isPublic().isSet()) { 5997 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 5998 << "public", 5999 getLocationOfByte(FS.isPublic().getPosition()), 6000 /*IsStringLocation*/ false, 6001 getSpecifierRange(startSpecifier, specifierLen)); 6002 } 6003 if (FS.isPrivate().isSet()) { 6004 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6005 << "private", 6006 getLocationOfByte(FS.isPrivate().getPosition()), 6007 /*IsStringLocation*/ false, 6008 getSpecifierRange(startSpecifier, specifierLen)); 6009 } 6010 } 6011 6012 // Check for invalid use of field width 6013 if (!FS.hasValidFieldWidth()) { 6014 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 6015 startSpecifier, specifierLen); 6016 } 6017 6018 // Check for invalid use of precision 6019 if (!FS.hasValidPrecision()) { 6020 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 6021 startSpecifier, specifierLen); 6022 } 6023 6024 // Precision is mandatory for %P specifier. 6025 if (CS.getKind() == ConversionSpecifier::PArg && 6026 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 6027 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 6028 getLocationOfByte(startSpecifier), 6029 /*IsStringLocation*/ false, 6030 getSpecifierRange(startSpecifier, specifierLen)); 6031 } 6032 6033 // Check each flag does not conflict with any other component. 6034 if (!FS.hasValidThousandsGroupingPrefix()) 6035 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 6036 if (!FS.hasValidLeadingZeros()) 6037 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 6038 if (!FS.hasValidPlusPrefix()) 6039 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 6040 if (!FS.hasValidSpacePrefix()) 6041 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 6042 if (!FS.hasValidAlternativeForm()) 6043 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 6044 if (!FS.hasValidLeftJustified()) 6045 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 6046 6047 // Check that flags are not ignored by another flag 6048 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 6049 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 6050 startSpecifier, specifierLen); 6051 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 6052 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 6053 startSpecifier, specifierLen); 6054 6055 // Check the length modifier is valid with the given conversion specifier. 6056 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6057 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6058 diag::warn_format_nonsensical_length); 6059 else if (!FS.hasStandardLengthModifier()) 6060 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6061 else if (!FS.hasStandardLengthConversionCombination()) 6062 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6063 diag::warn_format_non_standard_conversion_spec); 6064 6065 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6066 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6067 6068 // The remaining checks depend on the data arguments. 6069 if (HasVAListArg) 6070 return true; 6071 6072 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6073 return false; 6074 6075 const Expr *Arg = getDataArg(argIndex); 6076 if (!Arg) 6077 return true; 6078 6079 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 6080 } 6081 6082 static bool requiresParensToAddCast(const Expr *E) { 6083 // FIXME: We should have a general way to reason about operator 6084 // precedence and whether parens are actually needed here. 6085 // Take care of a few common cases where they aren't. 6086 const Expr *Inside = E->IgnoreImpCasts(); 6087 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 6088 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 6089 6090 switch (Inside->getStmtClass()) { 6091 case Stmt::ArraySubscriptExprClass: 6092 case Stmt::CallExprClass: 6093 case Stmt::CharacterLiteralClass: 6094 case Stmt::CXXBoolLiteralExprClass: 6095 case Stmt::DeclRefExprClass: 6096 case Stmt::FloatingLiteralClass: 6097 case Stmt::IntegerLiteralClass: 6098 case Stmt::MemberExprClass: 6099 case Stmt::ObjCArrayLiteralClass: 6100 case Stmt::ObjCBoolLiteralExprClass: 6101 case Stmt::ObjCBoxedExprClass: 6102 case Stmt::ObjCDictionaryLiteralClass: 6103 case Stmt::ObjCEncodeExprClass: 6104 case Stmt::ObjCIvarRefExprClass: 6105 case Stmt::ObjCMessageExprClass: 6106 case Stmt::ObjCPropertyRefExprClass: 6107 case Stmt::ObjCStringLiteralClass: 6108 case Stmt::ObjCSubscriptRefExprClass: 6109 case Stmt::ParenExprClass: 6110 case Stmt::StringLiteralClass: 6111 case Stmt::UnaryOperatorClass: 6112 return false; 6113 default: 6114 return true; 6115 } 6116 } 6117 6118 static std::pair<QualType, StringRef> 6119 shouldNotPrintDirectly(const ASTContext &Context, 6120 QualType IntendedTy, 6121 const Expr *E) { 6122 // Use a 'while' to peel off layers of typedefs. 6123 QualType TyTy = IntendedTy; 6124 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 6125 StringRef Name = UserTy->getDecl()->getName(); 6126 QualType CastTy = llvm::StringSwitch<QualType>(Name) 6127 .Case("CFIndex", Context.LongTy) 6128 .Case("NSInteger", Context.LongTy) 6129 .Case("NSUInteger", Context.UnsignedLongTy) 6130 .Case("SInt32", Context.IntTy) 6131 .Case("UInt32", Context.UnsignedIntTy) 6132 .Default(QualType()); 6133 6134 if (!CastTy.isNull()) 6135 return std::make_pair(CastTy, Name); 6136 6137 TyTy = UserTy->desugar(); 6138 } 6139 6140 // Strip parens if necessary. 6141 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 6142 return shouldNotPrintDirectly(Context, 6143 PE->getSubExpr()->getType(), 6144 PE->getSubExpr()); 6145 6146 // If this is a conditional expression, then its result type is constructed 6147 // via usual arithmetic conversions and thus there might be no necessary 6148 // typedef sugar there. Recurse to operands to check for NSInteger & 6149 // Co. usage condition. 6150 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6151 QualType TrueTy, FalseTy; 6152 StringRef TrueName, FalseName; 6153 6154 std::tie(TrueTy, TrueName) = 6155 shouldNotPrintDirectly(Context, 6156 CO->getTrueExpr()->getType(), 6157 CO->getTrueExpr()); 6158 std::tie(FalseTy, FalseName) = 6159 shouldNotPrintDirectly(Context, 6160 CO->getFalseExpr()->getType(), 6161 CO->getFalseExpr()); 6162 6163 if (TrueTy == FalseTy) 6164 return std::make_pair(TrueTy, TrueName); 6165 else if (TrueTy.isNull()) 6166 return std::make_pair(FalseTy, FalseName); 6167 else if (FalseTy.isNull()) 6168 return std::make_pair(TrueTy, TrueName); 6169 } 6170 6171 return std::make_pair(QualType(), StringRef()); 6172 } 6173 6174 bool 6175 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6176 const char *StartSpecifier, 6177 unsigned SpecifierLen, 6178 const Expr *E) { 6179 using namespace analyze_format_string; 6180 using namespace analyze_printf; 6181 // Now type check the data expression that matches the 6182 // format specifier. 6183 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 6184 if (!AT.isValid()) 6185 return true; 6186 6187 QualType ExprTy = E->getType(); 6188 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 6189 ExprTy = TET->getUnderlyingExpr()->getType(); 6190 } 6191 6192 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 6193 6194 if (match == analyze_printf::ArgType::Match) { 6195 return true; 6196 } 6197 6198 // Look through argument promotions for our error message's reported type. 6199 // This includes the integral and floating promotions, but excludes array 6200 // and function pointer decay; seeing that an argument intended to be a 6201 // string has type 'char [6]' is probably more confusing than 'char *'. 6202 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6203 if (ICE->getCastKind() == CK_IntegralCast || 6204 ICE->getCastKind() == CK_FloatingCast) { 6205 E = ICE->getSubExpr(); 6206 ExprTy = E->getType(); 6207 6208 // Check if we didn't match because of an implicit cast from a 'char' 6209 // or 'short' to an 'int'. This is done because printf is a varargs 6210 // function. 6211 if (ICE->getType() == S.Context.IntTy || 6212 ICE->getType() == S.Context.UnsignedIntTy) { 6213 // All further checking is done on the subexpression. 6214 if (AT.matchesType(S.Context, ExprTy)) 6215 return true; 6216 } 6217 } 6218 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 6219 // Special case for 'a', which has type 'int' in C. 6220 // Note, however, that we do /not/ want to treat multibyte constants like 6221 // 'MooV' as characters! This form is deprecated but still exists. 6222 if (ExprTy == S.Context.IntTy) 6223 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 6224 ExprTy = S.Context.CharTy; 6225 } 6226 6227 // Look through enums to their underlying type. 6228 bool IsEnum = false; 6229 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 6230 ExprTy = EnumTy->getDecl()->getIntegerType(); 6231 IsEnum = true; 6232 } 6233 6234 // %C in an Objective-C context prints a unichar, not a wchar_t. 6235 // If the argument is an integer of some kind, believe the %C and suggest 6236 // a cast instead of changing the conversion specifier. 6237 QualType IntendedTy = ExprTy; 6238 if (isObjCContext() && 6239 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 6240 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 6241 !ExprTy->isCharType()) { 6242 // 'unichar' is defined as a typedef of unsigned short, but we should 6243 // prefer using the typedef if it is visible. 6244 IntendedTy = S.Context.UnsignedShortTy; 6245 6246 // While we are here, check if the value is an IntegerLiteral that happens 6247 // to be within the valid range. 6248 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 6249 const llvm::APInt &V = IL->getValue(); 6250 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 6251 return true; 6252 } 6253 6254 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 6255 Sema::LookupOrdinaryName); 6256 if (S.LookupName(Result, S.getCurScope())) { 6257 NamedDecl *ND = Result.getFoundDecl(); 6258 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 6259 if (TD->getUnderlyingType() == IntendedTy) 6260 IntendedTy = S.Context.getTypedefType(TD); 6261 } 6262 } 6263 } 6264 6265 // Special-case some of Darwin's platform-independence types by suggesting 6266 // casts to primitive types that are known to be large enough. 6267 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 6268 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 6269 QualType CastTy; 6270 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 6271 if (!CastTy.isNull()) { 6272 IntendedTy = CastTy; 6273 ShouldNotPrintDirectly = true; 6274 } 6275 } 6276 6277 // We may be able to offer a FixItHint if it is a supported type. 6278 PrintfSpecifier fixedFS = FS; 6279 bool success = 6280 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 6281 6282 if (success) { 6283 // Get the fix string from the fixed format specifier 6284 SmallString<16> buf; 6285 llvm::raw_svector_ostream os(buf); 6286 fixedFS.toString(os); 6287 6288 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 6289 6290 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 6291 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6292 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6293 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6294 } 6295 // In this case, the specifier is wrong and should be changed to match 6296 // the argument. 6297 EmitFormatDiagnostic(S.PDiag(diag) 6298 << AT.getRepresentativeTypeName(S.Context) 6299 << IntendedTy << IsEnum << E->getSourceRange(), 6300 E->getLocStart(), 6301 /*IsStringLocation*/ false, SpecRange, 6302 FixItHint::CreateReplacement(SpecRange, os.str())); 6303 } else { 6304 // The canonical type for formatting this value is different from the 6305 // actual type of the expression. (This occurs, for example, with Darwin's 6306 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 6307 // should be printed as 'long' for 64-bit compatibility.) 6308 // Rather than emitting a normal format/argument mismatch, we want to 6309 // add a cast to the recommended type (and correct the format string 6310 // if necessary). 6311 SmallString<16> CastBuf; 6312 llvm::raw_svector_ostream CastFix(CastBuf); 6313 CastFix << "("; 6314 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 6315 CastFix << ")"; 6316 6317 SmallVector<FixItHint,4> Hints; 6318 if (!AT.matchesType(S.Context, IntendedTy)) 6319 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 6320 6321 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 6322 // If there's already a cast present, just replace it. 6323 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 6324 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 6325 6326 } else if (!requiresParensToAddCast(E)) { 6327 // If the expression has high enough precedence, 6328 // just write the C-style cast. 6329 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6330 CastFix.str())); 6331 } else { 6332 // Otherwise, add parens around the expression as well as the cast. 6333 CastFix << "("; 6334 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6335 CastFix.str())); 6336 6337 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6338 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6339 } 6340 6341 if (ShouldNotPrintDirectly) { 6342 // The expression has a type that should not be printed directly. 6343 // We extract the name from the typedef because we don't want to show 6344 // the underlying type in the diagnostic. 6345 StringRef Name; 6346 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6347 Name = TypedefTy->getDecl()->getName(); 6348 else 6349 Name = CastTyName; 6350 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6351 << Name << IntendedTy << IsEnum 6352 << E->getSourceRange(), 6353 E->getLocStart(), /*IsStringLocation=*/false, 6354 SpecRange, Hints); 6355 } else { 6356 // In this case, the expression could be printed using a different 6357 // specifier, but we've decided that the specifier is probably correct 6358 // and we should cast instead. Just use the normal warning message. 6359 EmitFormatDiagnostic( 6360 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6361 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6362 << E->getSourceRange(), 6363 E->getLocStart(), /*IsStringLocation*/false, 6364 SpecRange, Hints); 6365 } 6366 } 6367 } else { 6368 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6369 SpecifierLen); 6370 // Since the warning for passing non-POD types to variadic functions 6371 // was deferred until now, we emit a warning for non-POD 6372 // arguments here. 6373 switch (S.isValidVarArgType(ExprTy)) { 6374 case Sema::VAK_Valid: 6375 case Sema::VAK_ValidInCXX11: { 6376 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6377 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6378 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6379 } 6380 6381 EmitFormatDiagnostic( 6382 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6383 << IsEnum << CSR << E->getSourceRange(), 6384 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6385 break; 6386 } 6387 case Sema::VAK_Undefined: 6388 case Sema::VAK_MSVCUndefined: 6389 EmitFormatDiagnostic( 6390 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6391 << S.getLangOpts().CPlusPlus11 6392 << ExprTy 6393 << CallType 6394 << AT.getRepresentativeTypeName(S.Context) 6395 << CSR 6396 << E->getSourceRange(), 6397 E->getLocStart(), /*IsStringLocation*/false, CSR); 6398 checkForCStrMembers(AT, E); 6399 break; 6400 6401 case Sema::VAK_Invalid: 6402 if (ExprTy->isObjCObjectType()) 6403 EmitFormatDiagnostic( 6404 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 6405 << S.getLangOpts().CPlusPlus11 6406 << ExprTy 6407 << CallType 6408 << AT.getRepresentativeTypeName(S.Context) 6409 << CSR 6410 << E->getSourceRange(), 6411 E->getLocStart(), /*IsStringLocation*/false, CSR); 6412 else 6413 // FIXME: If this is an initializer list, suggest removing the braces 6414 // or inserting a cast to the target type. 6415 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 6416 << isa<InitListExpr>(E) << ExprTy << CallType 6417 << AT.getRepresentativeTypeName(S.Context) 6418 << E->getSourceRange(); 6419 break; 6420 } 6421 6422 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 6423 "format string specifier index out of range"); 6424 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 6425 } 6426 6427 return true; 6428 } 6429 6430 //===--- CHECK: Scanf format string checking ------------------------------===// 6431 6432 namespace { 6433 class CheckScanfHandler : public CheckFormatHandler { 6434 public: 6435 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 6436 const Expr *origFormatExpr, Sema::FormatStringType type, 6437 unsigned firstDataArg, unsigned numDataArgs, 6438 const char *beg, bool hasVAListArg, 6439 ArrayRef<const Expr *> Args, unsigned formatIdx, 6440 bool inFunctionCall, Sema::VariadicCallType CallType, 6441 llvm::SmallBitVector &CheckedVarArgs, 6442 UncoveredArgHandler &UncoveredArg) 6443 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6444 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6445 inFunctionCall, CallType, CheckedVarArgs, 6446 UncoveredArg) {} 6447 6448 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 6449 const char *startSpecifier, 6450 unsigned specifierLen) override; 6451 6452 bool HandleInvalidScanfConversionSpecifier( 6453 const analyze_scanf::ScanfSpecifier &FS, 6454 const char *startSpecifier, 6455 unsigned specifierLen) override; 6456 6457 void HandleIncompleteScanList(const char *start, const char *end) override; 6458 }; 6459 } // end anonymous namespace 6460 6461 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 6462 const char *end) { 6463 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 6464 getLocationOfByte(end), /*IsStringLocation*/true, 6465 getSpecifierRange(start, end - start)); 6466 } 6467 6468 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 6469 const analyze_scanf::ScanfSpecifier &FS, 6470 const char *startSpecifier, 6471 unsigned specifierLen) { 6472 6473 const analyze_scanf::ScanfConversionSpecifier &CS = 6474 FS.getConversionSpecifier(); 6475 6476 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6477 getLocationOfByte(CS.getStart()), 6478 startSpecifier, specifierLen, 6479 CS.getStart(), CS.getLength()); 6480 } 6481 6482 bool CheckScanfHandler::HandleScanfSpecifier( 6483 const analyze_scanf::ScanfSpecifier &FS, 6484 const char *startSpecifier, 6485 unsigned specifierLen) { 6486 using namespace analyze_scanf; 6487 using namespace analyze_format_string; 6488 6489 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 6490 6491 // Handle case where '%' and '*' don't consume an argument. These shouldn't 6492 // be used to decide if we are using positional arguments consistently. 6493 if (FS.consumesDataArgument()) { 6494 if (atFirstArg) { 6495 atFirstArg = false; 6496 usesPositionalArgs = FS.usesPositionalArg(); 6497 } 6498 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6499 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6500 startSpecifier, specifierLen); 6501 return false; 6502 } 6503 } 6504 6505 // Check if the field with is non-zero. 6506 const OptionalAmount &Amt = FS.getFieldWidth(); 6507 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 6508 if (Amt.getConstantAmount() == 0) { 6509 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 6510 Amt.getConstantLength()); 6511 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 6512 getLocationOfByte(Amt.getStart()), 6513 /*IsStringLocation*/true, R, 6514 FixItHint::CreateRemoval(R)); 6515 } 6516 } 6517 6518 if (!FS.consumesDataArgument()) { 6519 // FIXME: Technically specifying a precision or field width here 6520 // makes no sense. Worth issuing a warning at some point. 6521 return true; 6522 } 6523 6524 // Consume the argument. 6525 unsigned argIndex = FS.getArgIndex(); 6526 if (argIndex < NumDataArgs) { 6527 // The check to see if the argIndex is valid will come later. 6528 // We set the bit here because we may exit early from this 6529 // function if we encounter some other error. 6530 CoveredArgs.set(argIndex); 6531 } 6532 6533 // Check the length modifier is valid with the given conversion specifier. 6534 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6535 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6536 diag::warn_format_nonsensical_length); 6537 else if (!FS.hasStandardLengthModifier()) 6538 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6539 else if (!FS.hasStandardLengthConversionCombination()) 6540 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6541 diag::warn_format_non_standard_conversion_spec); 6542 6543 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6544 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6545 6546 // The remaining checks depend on the data arguments. 6547 if (HasVAListArg) 6548 return true; 6549 6550 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6551 return false; 6552 6553 // Check that the argument type matches the format specifier. 6554 const Expr *Ex = getDataArg(argIndex); 6555 if (!Ex) 6556 return true; 6557 6558 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 6559 6560 if (!AT.isValid()) { 6561 return true; 6562 } 6563 6564 analyze_format_string::ArgType::MatchKind match = 6565 AT.matchesType(S.Context, Ex->getType()); 6566 if (match == analyze_format_string::ArgType::Match) { 6567 return true; 6568 } 6569 6570 ScanfSpecifier fixedFS = FS; 6571 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 6572 S.getLangOpts(), S.Context); 6573 6574 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6575 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6576 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6577 } 6578 6579 if (success) { 6580 // Get the fix string from the fixed format specifier. 6581 SmallString<128> buf; 6582 llvm::raw_svector_ostream os(buf); 6583 fixedFS.toString(os); 6584 6585 EmitFormatDiagnostic( 6586 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 6587 << Ex->getType() << false << Ex->getSourceRange(), 6588 Ex->getLocStart(), 6589 /*IsStringLocation*/ false, 6590 getSpecifierRange(startSpecifier, specifierLen), 6591 FixItHint::CreateReplacement( 6592 getSpecifierRange(startSpecifier, specifierLen), os.str())); 6593 } else { 6594 EmitFormatDiagnostic(S.PDiag(diag) 6595 << AT.getRepresentativeTypeName(S.Context) 6596 << Ex->getType() << false << Ex->getSourceRange(), 6597 Ex->getLocStart(), 6598 /*IsStringLocation*/ false, 6599 getSpecifierRange(startSpecifier, specifierLen)); 6600 } 6601 6602 return true; 6603 } 6604 6605 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6606 const Expr *OrigFormatExpr, 6607 ArrayRef<const Expr *> Args, 6608 bool HasVAListArg, unsigned format_idx, 6609 unsigned firstDataArg, 6610 Sema::FormatStringType Type, 6611 bool inFunctionCall, 6612 Sema::VariadicCallType CallType, 6613 llvm::SmallBitVector &CheckedVarArgs, 6614 UncoveredArgHandler &UncoveredArg) { 6615 // CHECK: is the format string a wide literal? 6616 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 6617 CheckFormatHandler::EmitFormatDiagnostic( 6618 S, inFunctionCall, Args[format_idx], 6619 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 6620 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6621 return; 6622 } 6623 6624 // Str - The format string. NOTE: this is NOT null-terminated! 6625 StringRef StrRef = FExpr->getString(); 6626 const char *Str = StrRef.data(); 6627 // Account for cases where the string literal is truncated in a declaration. 6628 const ConstantArrayType *T = 6629 S.Context.getAsConstantArrayType(FExpr->getType()); 6630 assert(T && "String literal not of constant array type!"); 6631 size_t TypeSize = T->getSize().getZExtValue(); 6632 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6633 const unsigned numDataArgs = Args.size() - firstDataArg; 6634 6635 // Emit a warning if the string literal is truncated and does not contain an 6636 // embedded null character. 6637 if (TypeSize <= StrRef.size() && 6638 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 6639 CheckFormatHandler::EmitFormatDiagnostic( 6640 S, inFunctionCall, Args[format_idx], 6641 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 6642 FExpr->getLocStart(), 6643 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 6644 return; 6645 } 6646 6647 // CHECK: empty format string? 6648 if (StrLen == 0 && numDataArgs > 0) { 6649 CheckFormatHandler::EmitFormatDiagnostic( 6650 S, inFunctionCall, Args[format_idx], 6651 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 6652 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6653 return; 6654 } 6655 6656 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 6657 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 6658 Type == Sema::FST_OSTrace) { 6659 CheckPrintfHandler H( 6660 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 6661 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 6662 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 6663 CheckedVarArgs, UncoveredArg); 6664 6665 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 6666 S.getLangOpts(), 6667 S.Context.getTargetInfo(), 6668 Type == Sema::FST_FreeBSDKPrintf)) 6669 H.DoneProcessing(); 6670 } else if (Type == Sema::FST_Scanf) { 6671 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 6672 numDataArgs, Str, HasVAListArg, Args, format_idx, 6673 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 6674 6675 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 6676 S.getLangOpts(), 6677 S.Context.getTargetInfo())) 6678 H.DoneProcessing(); 6679 } // TODO: handle other formats 6680 } 6681 6682 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 6683 // Str - The format string. NOTE: this is NOT null-terminated! 6684 StringRef StrRef = FExpr->getString(); 6685 const char *Str = StrRef.data(); 6686 // Account for cases where the string literal is truncated in a declaration. 6687 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 6688 assert(T && "String literal not of constant array type!"); 6689 size_t TypeSize = T->getSize().getZExtValue(); 6690 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6691 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 6692 getLangOpts(), 6693 Context.getTargetInfo()); 6694 } 6695 6696 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 6697 6698 // Returns the related absolute value function that is larger, of 0 if one 6699 // does not exist. 6700 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 6701 switch (AbsFunction) { 6702 default: 6703 return 0; 6704 6705 case Builtin::BI__builtin_abs: 6706 return Builtin::BI__builtin_labs; 6707 case Builtin::BI__builtin_labs: 6708 return Builtin::BI__builtin_llabs; 6709 case Builtin::BI__builtin_llabs: 6710 return 0; 6711 6712 case Builtin::BI__builtin_fabsf: 6713 return Builtin::BI__builtin_fabs; 6714 case Builtin::BI__builtin_fabs: 6715 return Builtin::BI__builtin_fabsl; 6716 case Builtin::BI__builtin_fabsl: 6717 return 0; 6718 6719 case Builtin::BI__builtin_cabsf: 6720 return Builtin::BI__builtin_cabs; 6721 case Builtin::BI__builtin_cabs: 6722 return Builtin::BI__builtin_cabsl; 6723 case Builtin::BI__builtin_cabsl: 6724 return 0; 6725 6726 case Builtin::BIabs: 6727 return Builtin::BIlabs; 6728 case Builtin::BIlabs: 6729 return Builtin::BIllabs; 6730 case Builtin::BIllabs: 6731 return 0; 6732 6733 case Builtin::BIfabsf: 6734 return Builtin::BIfabs; 6735 case Builtin::BIfabs: 6736 return Builtin::BIfabsl; 6737 case Builtin::BIfabsl: 6738 return 0; 6739 6740 case Builtin::BIcabsf: 6741 return Builtin::BIcabs; 6742 case Builtin::BIcabs: 6743 return Builtin::BIcabsl; 6744 case Builtin::BIcabsl: 6745 return 0; 6746 } 6747 } 6748 6749 // Returns the argument type of the absolute value function. 6750 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 6751 unsigned AbsType) { 6752 if (AbsType == 0) 6753 return QualType(); 6754 6755 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 6756 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 6757 if (Error != ASTContext::GE_None) 6758 return QualType(); 6759 6760 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 6761 if (!FT) 6762 return QualType(); 6763 6764 if (FT->getNumParams() != 1) 6765 return QualType(); 6766 6767 return FT->getParamType(0); 6768 } 6769 6770 // Returns the best absolute value function, or zero, based on type and 6771 // current absolute value function. 6772 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 6773 unsigned AbsFunctionKind) { 6774 unsigned BestKind = 0; 6775 uint64_t ArgSize = Context.getTypeSize(ArgType); 6776 for (unsigned Kind = AbsFunctionKind; Kind != 0; 6777 Kind = getLargerAbsoluteValueFunction(Kind)) { 6778 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 6779 if (Context.getTypeSize(ParamType) >= ArgSize) { 6780 if (BestKind == 0) 6781 BestKind = Kind; 6782 else if (Context.hasSameType(ParamType, ArgType)) { 6783 BestKind = Kind; 6784 break; 6785 } 6786 } 6787 } 6788 return BestKind; 6789 } 6790 6791 enum AbsoluteValueKind { 6792 AVK_Integer, 6793 AVK_Floating, 6794 AVK_Complex 6795 }; 6796 6797 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 6798 if (T->isIntegralOrEnumerationType()) 6799 return AVK_Integer; 6800 if (T->isRealFloatingType()) 6801 return AVK_Floating; 6802 if (T->isAnyComplexType()) 6803 return AVK_Complex; 6804 6805 llvm_unreachable("Type not integer, floating, or complex"); 6806 } 6807 6808 // Changes the absolute value function to a different type. Preserves whether 6809 // the function is a builtin. 6810 static unsigned changeAbsFunction(unsigned AbsKind, 6811 AbsoluteValueKind ValueKind) { 6812 switch (ValueKind) { 6813 case AVK_Integer: 6814 switch (AbsKind) { 6815 default: 6816 return 0; 6817 case Builtin::BI__builtin_fabsf: 6818 case Builtin::BI__builtin_fabs: 6819 case Builtin::BI__builtin_fabsl: 6820 case Builtin::BI__builtin_cabsf: 6821 case Builtin::BI__builtin_cabs: 6822 case Builtin::BI__builtin_cabsl: 6823 return Builtin::BI__builtin_abs; 6824 case Builtin::BIfabsf: 6825 case Builtin::BIfabs: 6826 case Builtin::BIfabsl: 6827 case Builtin::BIcabsf: 6828 case Builtin::BIcabs: 6829 case Builtin::BIcabsl: 6830 return Builtin::BIabs; 6831 } 6832 case AVK_Floating: 6833 switch (AbsKind) { 6834 default: 6835 return 0; 6836 case Builtin::BI__builtin_abs: 6837 case Builtin::BI__builtin_labs: 6838 case Builtin::BI__builtin_llabs: 6839 case Builtin::BI__builtin_cabsf: 6840 case Builtin::BI__builtin_cabs: 6841 case Builtin::BI__builtin_cabsl: 6842 return Builtin::BI__builtin_fabsf; 6843 case Builtin::BIabs: 6844 case Builtin::BIlabs: 6845 case Builtin::BIllabs: 6846 case Builtin::BIcabsf: 6847 case Builtin::BIcabs: 6848 case Builtin::BIcabsl: 6849 return Builtin::BIfabsf; 6850 } 6851 case AVK_Complex: 6852 switch (AbsKind) { 6853 default: 6854 return 0; 6855 case Builtin::BI__builtin_abs: 6856 case Builtin::BI__builtin_labs: 6857 case Builtin::BI__builtin_llabs: 6858 case Builtin::BI__builtin_fabsf: 6859 case Builtin::BI__builtin_fabs: 6860 case Builtin::BI__builtin_fabsl: 6861 return Builtin::BI__builtin_cabsf; 6862 case Builtin::BIabs: 6863 case Builtin::BIlabs: 6864 case Builtin::BIllabs: 6865 case Builtin::BIfabsf: 6866 case Builtin::BIfabs: 6867 case Builtin::BIfabsl: 6868 return Builtin::BIcabsf; 6869 } 6870 } 6871 llvm_unreachable("Unable to convert function"); 6872 } 6873 6874 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 6875 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 6876 if (!FnInfo) 6877 return 0; 6878 6879 switch (FDecl->getBuiltinID()) { 6880 default: 6881 return 0; 6882 case Builtin::BI__builtin_abs: 6883 case Builtin::BI__builtin_fabs: 6884 case Builtin::BI__builtin_fabsf: 6885 case Builtin::BI__builtin_fabsl: 6886 case Builtin::BI__builtin_labs: 6887 case Builtin::BI__builtin_llabs: 6888 case Builtin::BI__builtin_cabs: 6889 case Builtin::BI__builtin_cabsf: 6890 case Builtin::BI__builtin_cabsl: 6891 case Builtin::BIabs: 6892 case Builtin::BIlabs: 6893 case Builtin::BIllabs: 6894 case Builtin::BIfabs: 6895 case Builtin::BIfabsf: 6896 case Builtin::BIfabsl: 6897 case Builtin::BIcabs: 6898 case Builtin::BIcabsf: 6899 case Builtin::BIcabsl: 6900 return FDecl->getBuiltinID(); 6901 } 6902 llvm_unreachable("Unknown Builtin type"); 6903 } 6904 6905 // If the replacement is valid, emit a note with replacement function. 6906 // Additionally, suggest including the proper header if not already included. 6907 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 6908 unsigned AbsKind, QualType ArgType) { 6909 bool EmitHeaderHint = true; 6910 const char *HeaderName = nullptr; 6911 const char *FunctionName = nullptr; 6912 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 6913 FunctionName = "std::abs"; 6914 if (ArgType->isIntegralOrEnumerationType()) { 6915 HeaderName = "cstdlib"; 6916 } else if (ArgType->isRealFloatingType()) { 6917 HeaderName = "cmath"; 6918 } else { 6919 llvm_unreachable("Invalid Type"); 6920 } 6921 6922 // Lookup all std::abs 6923 if (NamespaceDecl *Std = S.getStdNamespace()) { 6924 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 6925 R.suppressDiagnostics(); 6926 S.LookupQualifiedName(R, Std); 6927 6928 for (const auto *I : R) { 6929 const FunctionDecl *FDecl = nullptr; 6930 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 6931 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 6932 } else { 6933 FDecl = dyn_cast<FunctionDecl>(I); 6934 } 6935 if (!FDecl) 6936 continue; 6937 6938 // Found std::abs(), check that they are the right ones. 6939 if (FDecl->getNumParams() != 1) 6940 continue; 6941 6942 // Check that the parameter type can handle the argument. 6943 QualType ParamType = FDecl->getParamDecl(0)->getType(); 6944 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 6945 S.Context.getTypeSize(ArgType) <= 6946 S.Context.getTypeSize(ParamType)) { 6947 // Found a function, don't need the header hint. 6948 EmitHeaderHint = false; 6949 break; 6950 } 6951 } 6952 } 6953 } else { 6954 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 6955 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 6956 6957 if (HeaderName) { 6958 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 6959 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 6960 R.suppressDiagnostics(); 6961 S.LookupName(R, S.getCurScope()); 6962 6963 if (R.isSingleResult()) { 6964 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 6965 if (FD && FD->getBuiltinID() == AbsKind) { 6966 EmitHeaderHint = false; 6967 } else { 6968 return; 6969 } 6970 } else if (!R.empty()) { 6971 return; 6972 } 6973 } 6974 } 6975 6976 S.Diag(Loc, diag::note_replace_abs_function) 6977 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 6978 6979 if (!HeaderName) 6980 return; 6981 6982 if (!EmitHeaderHint) 6983 return; 6984 6985 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 6986 << FunctionName; 6987 } 6988 6989 template <std::size_t StrLen> 6990 static bool IsStdFunction(const FunctionDecl *FDecl, 6991 const char (&Str)[StrLen]) { 6992 if (!FDecl) 6993 return false; 6994 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 6995 return false; 6996 if (!FDecl->isInStdNamespace()) 6997 return false; 6998 6999 return true; 7000 } 7001 7002 // Warn when using the wrong abs() function. 7003 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 7004 const FunctionDecl *FDecl) { 7005 if (Call->getNumArgs() != 1) 7006 return; 7007 7008 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 7009 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 7010 if (AbsKind == 0 && !IsStdAbs) 7011 return; 7012 7013 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7014 QualType ParamType = Call->getArg(0)->getType(); 7015 7016 // Unsigned types cannot be negative. Suggest removing the absolute value 7017 // function call. 7018 if (ArgType->isUnsignedIntegerType()) { 7019 const char *FunctionName = 7020 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 7021 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 7022 Diag(Call->getExprLoc(), diag::note_remove_abs) 7023 << FunctionName 7024 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 7025 return; 7026 } 7027 7028 // Taking the absolute value of a pointer is very suspicious, they probably 7029 // wanted to index into an array, dereference a pointer, call a function, etc. 7030 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 7031 unsigned DiagType = 0; 7032 if (ArgType->isFunctionType()) 7033 DiagType = 1; 7034 else if (ArgType->isArrayType()) 7035 DiagType = 2; 7036 7037 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 7038 return; 7039 } 7040 7041 // std::abs has overloads which prevent most of the absolute value problems 7042 // from occurring. 7043 if (IsStdAbs) 7044 return; 7045 7046 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 7047 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 7048 7049 // The argument and parameter are the same kind. Check if they are the right 7050 // size. 7051 if (ArgValueKind == ParamValueKind) { 7052 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 7053 return; 7054 7055 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 7056 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 7057 << FDecl << ArgType << ParamType; 7058 7059 if (NewAbsKind == 0) 7060 return; 7061 7062 emitReplacement(*this, Call->getExprLoc(), 7063 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7064 return; 7065 } 7066 7067 // ArgValueKind != ParamValueKind 7068 // The wrong type of absolute value function was used. Attempt to find the 7069 // proper one. 7070 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 7071 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 7072 if (NewAbsKind == 0) 7073 return; 7074 7075 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 7076 << FDecl << ParamValueKind << ArgValueKind; 7077 7078 emitReplacement(*this, Call->getExprLoc(), 7079 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7080 } 7081 7082 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 7083 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 7084 const FunctionDecl *FDecl) { 7085 if (!Call || !FDecl) return; 7086 7087 // Ignore template specializations and macros. 7088 if (inTemplateInstantiation()) return; 7089 if (Call->getExprLoc().isMacroID()) return; 7090 7091 // Only care about the one template argument, two function parameter std::max 7092 if (Call->getNumArgs() != 2) return; 7093 if (!IsStdFunction(FDecl, "max")) return; 7094 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 7095 if (!ArgList) return; 7096 if (ArgList->size() != 1) return; 7097 7098 // Check that template type argument is unsigned integer. 7099 const auto& TA = ArgList->get(0); 7100 if (TA.getKind() != TemplateArgument::Type) return; 7101 QualType ArgType = TA.getAsType(); 7102 if (!ArgType->isUnsignedIntegerType()) return; 7103 7104 // See if either argument is a literal zero. 7105 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 7106 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 7107 if (!MTE) return false; 7108 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 7109 if (!Num) return false; 7110 if (Num->getValue() != 0) return false; 7111 return true; 7112 }; 7113 7114 const Expr *FirstArg = Call->getArg(0); 7115 const Expr *SecondArg = Call->getArg(1); 7116 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 7117 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 7118 7119 // Only warn when exactly one argument is zero. 7120 if (IsFirstArgZero == IsSecondArgZero) return; 7121 7122 SourceRange FirstRange = FirstArg->getSourceRange(); 7123 SourceRange SecondRange = SecondArg->getSourceRange(); 7124 7125 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 7126 7127 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 7128 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 7129 7130 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 7131 SourceRange RemovalRange; 7132 if (IsFirstArgZero) { 7133 RemovalRange = SourceRange(FirstRange.getBegin(), 7134 SecondRange.getBegin().getLocWithOffset(-1)); 7135 } else { 7136 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 7137 SecondRange.getEnd()); 7138 } 7139 7140 Diag(Call->getExprLoc(), diag::note_remove_max_call) 7141 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 7142 << FixItHint::CreateRemoval(RemovalRange); 7143 } 7144 7145 //===--- CHECK: Standard memory functions ---------------------------------===// 7146 7147 /// \brief Takes the expression passed to the size_t parameter of functions 7148 /// such as memcmp, strncat, etc and warns if it's a comparison. 7149 /// 7150 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 7151 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 7152 IdentifierInfo *FnName, 7153 SourceLocation FnLoc, 7154 SourceLocation RParenLoc) { 7155 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 7156 if (!Size) 7157 return false; 7158 7159 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 7160 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 7161 return false; 7162 7163 SourceRange SizeRange = Size->getSourceRange(); 7164 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 7165 << SizeRange << FnName; 7166 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 7167 << FnName << FixItHint::CreateInsertion( 7168 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 7169 << FixItHint::CreateRemoval(RParenLoc); 7170 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 7171 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 7172 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 7173 ")"); 7174 7175 return true; 7176 } 7177 7178 /// \brief Determine whether the given type is or contains a dynamic class type 7179 /// (e.g., whether it has a vtable). 7180 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 7181 bool &IsContained) { 7182 // Look through array types while ignoring qualifiers. 7183 const Type *Ty = T->getBaseElementTypeUnsafe(); 7184 IsContained = false; 7185 7186 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 7187 RD = RD ? RD->getDefinition() : nullptr; 7188 if (!RD || RD->isInvalidDecl()) 7189 return nullptr; 7190 7191 if (RD->isDynamicClass()) 7192 return RD; 7193 7194 // Check all the fields. If any bases were dynamic, the class is dynamic. 7195 // It's impossible for a class to transitively contain itself by value, so 7196 // infinite recursion is impossible. 7197 for (auto *FD : RD->fields()) { 7198 bool SubContained; 7199 if (const CXXRecordDecl *ContainedRD = 7200 getContainedDynamicClass(FD->getType(), SubContained)) { 7201 IsContained = true; 7202 return ContainedRD; 7203 } 7204 } 7205 7206 return nullptr; 7207 } 7208 7209 /// \brief If E is a sizeof expression, returns its argument expression, 7210 /// otherwise returns NULL. 7211 static const Expr *getSizeOfExprArg(const Expr *E) { 7212 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7213 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7214 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 7215 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 7216 7217 return nullptr; 7218 } 7219 7220 /// \brief If E is a sizeof expression, returns its argument type. 7221 static QualType getSizeOfArgType(const Expr *E) { 7222 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7223 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7224 if (SizeOf->getKind() == clang::UETT_SizeOf) 7225 return SizeOf->getTypeOfArgument(); 7226 7227 return QualType(); 7228 } 7229 7230 /// \brief Check for dangerous or invalid arguments to memset(). 7231 /// 7232 /// This issues warnings on known problematic, dangerous or unspecified 7233 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 7234 /// function calls. 7235 /// 7236 /// \param Call The call expression to diagnose. 7237 void Sema::CheckMemaccessArguments(const CallExpr *Call, 7238 unsigned BId, 7239 IdentifierInfo *FnName) { 7240 assert(BId != 0); 7241 7242 // It is possible to have a non-standard definition of memset. Validate 7243 // we have enough arguments, and if not, abort further checking. 7244 unsigned ExpectedNumArgs = 7245 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 7246 if (Call->getNumArgs() < ExpectedNumArgs) 7247 return; 7248 7249 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 7250 BId == Builtin::BIstrndup ? 1 : 2); 7251 unsigned LenArg = 7252 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 7253 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 7254 7255 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 7256 Call->getLocStart(), Call->getRParenLoc())) 7257 return; 7258 7259 // We have special checking when the length is a sizeof expression. 7260 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 7261 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 7262 llvm::FoldingSetNodeID SizeOfArgID; 7263 7264 // Although widely used, 'bzero' is not a standard function. Be more strict 7265 // with the argument types before allowing diagnostics and only allow the 7266 // form bzero(ptr, sizeof(...)). 7267 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7268 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 7269 return; 7270 7271 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 7272 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 7273 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 7274 7275 QualType DestTy = Dest->getType(); 7276 QualType PointeeTy; 7277 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 7278 PointeeTy = DestPtrTy->getPointeeType(); 7279 7280 // Never warn about void type pointers. This can be used to suppress 7281 // false positives. 7282 if (PointeeTy->isVoidType()) 7283 continue; 7284 7285 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 7286 // actually comparing the expressions for equality. Because computing the 7287 // expression IDs can be expensive, we only do this if the diagnostic is 7288 // enabled. 7289 if (SizeOfArg && 7290 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 7291 SizeOfArg->getExprLoc())) { 7292 // We only compute IDs for expressions if the warning is enabled, and 7293 // cache the sizeof arg's ID. 7294 if (SizeOfArgID == llvm::FoldingSetNodeID()) 7295 SizeOfArg->Profile(SizeOfArgID, Context, true); 7296 llvm::FoldingSetNodeID DestID; 7297 Dest->Profile(DestID, Context, true); 7298 if (DestID == SizeOfArgID) { 7299 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 7300 // over sizeof(src) as well. 7301 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 7302 StringRef ReadableName = FnName->getName(); 7303 7304 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 7305 if (UnaryOp->getOpcode() == UO_AddrOf) 7306 ActionIdx = 1; // If its an address-of operator, just remove it. 7307 if (!PointeeTy->isIncompleteType() && 7308 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 7309 ActionIdx = 2; // If the pointee's size is sizeof(char), 7310 // suggest an explicit length. 7311 7312 // If the function is defined as a builtin macro, do not show macro 7313 // expansion. 7314 SourceLocation SL = SizeOfArg->getExprLoc(); 7315 SourceRange DSR = Dest->getSourceRange(); 7316 SourceRange SSR = SizeOfArg->getSourceRange(); 7317 SourceManager &SM = getSourceManager(); 7318 7319 if (SM.isMacroArgExpansion(SL)) { 7320 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 7321 SL = SM.getSpellingLoc(SL); 7322 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 7323 SM.getSpellingLoc(DSR.getEnd())); 7324 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 7325 SM.getSpellingLoc(SSR.getEnd())); 7326 } 7327 7328 DiagRuntimeBehavior(SL, SizeOfArg, 7329 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 7330 << ReadableName 7331 << PointeeTy 7332 << DestTy 7333 << DSR 7334 << SSR); 7335 DiagRuntimeBehavior(SL, SizeOfArg, 7336 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 7337 << ActionIdx 7338 << SSR); 7339 7340 break; 7341 } 7342 } 7343 7344 // Also check for cases where the sizeof argument is the exact same 7345 // type as the memory argument, and where it points to a user-defined 7346 // record type. 7347 if (SizeOfArgTy != QualType()) { 7348 if (PointeeTy->isRecordType() && 7349 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 7350 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 7351 PDiag(diag::warn_sizeof_pointer_type_memaccess) 7352 << FnName << SizeOfArgTy << ArgIdx 7353 << PointeeTy << Dest->getSourceRange() 7354 << LenExpr->getSourceRange()); 7355 break; 7356 } 7357 } 7358 } else if (DestTy->isArrayType()) { 7359 PointeeTy = DestTy; 7360 } 7361 7362 if (PointeeTy == QualType()) 7363 continue; 7364 7365 // Always complain about dynamic classes. 7366 bool IsContained; 7367 if (const CXXRecordDecl *ContainedRD = 7368 getContainedDynamicClass(PointeeTy, IsContained)) { 7369 7370 unsigned OperationType = 0; 7371 // "overwritten" if we're warning about the destination for any call 7372 // but memcmp; otherwise a verb appropriate to the call. 7373 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 7374 if (BId == Builtin::BImemcpy) 7375 OperationType = 1; 7376 else if(BId == Builtin::BImemmove) 7377 OperationType = 2; 7378 else if (BId == Builtin::BImemcmp) 7379 OperationType = 3; 7380 } 7381 7382 DiagRuntimeBehavior( 7383 Dest->getExprLoc(), Dest, 7384 PDiag(diag::warn_dyn_class_memaccess) 7385 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 7386 << FnName << IsContained << ContainedRD << OperationType 7387 << Call->getCallee()->getSourceRange()); 7388 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 7389 BId != Builtin::BImemset) 7390 DiagRuntimeBehavior( 7391 Dest->getExprLoc(), Dest, 7392 PDiag(diag::warn_arc_object_memaccess) 7393 << ArgIdx << FnName << PointeeTy 7394 << Call->getCallee()->getSourceRange()); 7395 else 7396 continue; 7397 7398 DiagRuntimeBehavior( 7399 Dest->getExprLoc(), Dest, 7400 PDiag(diag::note_bad_memaccess_silence) 7401 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 7402 break; 7403 } 7404 } 7405 7406 // A little helper routine: ignore addition and subtraction of integer literals. 7407 // This intentionally does not ignore all integer constant expressions because 7408 // we don't want to remove sizeof(). 7409 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 7410 Ex = Ex->IgnoreParenCasts(); 7411 7412 for (;;) { 7413 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 7414 if (!BO || !BO->isAdditiveOp()) 7415 break; 7416 7417 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 7418 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 7419 7420 if (isa<IntegerLiteral>(RHS)) 7421 Ex = LHS; 7422 else if (isa<IntegerLiteral>(LHS)) 7423 Ex = RHS; 7424 else 7425 break; 7426 } 7427 7428 return Ex; 7429 } 7430 7431 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 7432 ASTContext &Context) { 7433 // Only handle constant-sized or VLAs, but not flexible members. 7434 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 7435 // Only issue the FIXIT for arrays of size > 1. 7436 if (CAT->getSize().getSExtValue() <= 1) 7437 return false; 7438 } else if (!Ty->isVariableArrayType()) { 7439 return false; 7440 } 7441 return true; 7442 } 7443 7444 // Warn if the user has made the 'size' argument to strlcpy or strlcat 7445 // be the size of the source, instead of the destination. 7446 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 7447 IdentifierInfo *FnName) { 7448 7449 // Don't crash if the user has the wrong number of arguments 7450 unsigned NumArgs = Call->getNumArgs(); 7451 if ((NumArgs != 3) && (NumArgs != 4)) 7452 return; 7453 7454 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 7455 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 7456 const Expr *CompareWithSrc = nullptr; 7457 7458 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 7459 Call->getLocStart(), Call->getRParenLoc())) 7460 return; 7461 7462 // Look for 'strlcpy(dst, x, sizeof(x))' 7463 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 7464 CompareWithSrc = Ex; 7465 else { 7466 // Look for 'strlcpy(dst, x, strlen(x))' 7467 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 7468 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 7469 SizeCall->getNumArgs() == 1) 7470 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 7471 } 7472 } 7473 7474 if (!CompareWithSrc) 7475 return; 7476 7477 // Determine if the argument to sizeof/strlen is equal to the source 7478 // argument. In principle there's all kinds of things you could do 7479 // here, for instance creating an == expression and evaluating it with 7480 // EvaluateAsBooleanCondition, but this uses a more direct technique: 7481 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 7482 if (!SrcArgDRE) 7483 return; 7484 7485 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 7486 if (!CompareWithSrcDRE || 7487 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 7488 return; 7489 7490 const Expr *OriginalSizeArg = Call->getArg(2); 7491 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 7492 << OriginalSizeArg->getSourceRange() << FnName; 7493 7494 // Output a FIXIT hint if the destination is an array (rather than a 7495 // pointer to an array). This could be enhanced to handle some 7496 // pointers if we know the actual size, like if DstArg is 'array+2' 7497 // we could say 'sizeof(array)-2'. 7498 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 7499 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 7500 return; 7501 7502 SmallString<128> sizeString; 7503 llvm::raw_svector_ostream OS(sizeString); 7504 OS << "sizeof("; 7505 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7506 OS << ")"; 7507 7508 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 7509 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 7510 OS.str()); 7511 } 7512 7513 /// Check if two expressions refer to the same declaration. 7514 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 7515 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 7516 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 7517 return D1->getDecl() == D2->getDecl(); 7518 return false; 7519 } 7520 7521 static const Expr *getStrlenExprArg(const Expr *E) { 7522 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7523 const FunctionDecl *FD = CE->getDirectCallee(); 7524 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 7525 return nullptr; 7526 return CE->getArg(0)->IgnoreParenCasts(); 7527 } 7528 return nullptr; 7529 } 7530 7531 // Warn on anti-patterns as the 'size' argument to strncat. 7532 // The correct size argument should look like following: 7533 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 7534 void Sema::CheckStrncatArguments(const CallExpr *CE, 7535 IdentifierInfo *FnName) { 7536 // Don't crash if the user has the wrong number of arguments. 7537 if (CE->getNumArgs() < 3) 7538 return; 7539 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 7540 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 7541 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 7542 7543 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 7544 CE->getRParenLoc())) 7545 return; 7546 7547 // Identify common expressions, which are wrongly used as the size argument 7548 // to strncat and may lead to buffer overflows. 7549 unsigned PatternType = 0; 7550 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 7551 // - sizeof(dst) 7552 if (referToTheSameDecl(SizeOfArg, DstArg)) 7553 PatternType = 1; 7554 // - sizeof(src) 7555 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 7556 PatternType = 2; 7557 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 7558 if (BE->getOpcode() == BO_Sub) { 7559 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 7560 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 7561 // - sizeof(dst) - strlen(dst) 7562 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 7563 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 7564 PatternType = 1; 7565 // - sizeof(src) - (anything) 7566 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 7567 PatternType = 2; 7568 } 7569 } 7570 7571 if (PatternType == 0) 7572 return; 7573 7574 // Generate the diagnostic. 7575 SourceLocation SL = LenArg->getLocStart(); 7576 SourceRange SR = LenArg->getSourceRange(); 7577 SourceManager &SM = getSourceManager(); 7578 7579 // If the function is defined as a builtin macro, do not show macro expansion. 7580 if (SM.isMacroArgExpansion(SL)) { 7581 SL = SM.getSpellingLoc(SL); 7582 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 7583 SM.getSpellingLoc(SR.getEnd())); 7584 } 7585 7586 // Check if the destination is an array (rather than a pointer to an array). 7587 QualType DstTy = DstArg->getType(); 7588 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 7589 Context); 7590 if (!isKnownSizeArray) { 7591 if (PatternType == 1) 7592 Diag(SL, diag::warn_strncat_wrong_size) << SR; 7593 else 7594 Diag(SL, diag::warn_strncat_src_size) << SR; 7595 return; 7596 } 7597 7598 if (PatternType == 1) 7599 Diag(SL, diag::warn_strncat_large_size) << SR; 7600 else 7601 Diag(SL, diag::warn_strncat_src_size) << SR; 7602 7603 SmallString<128> sizeString; 7604 llvm::raw_svector_ostream OS(sizeString); 7605 OS << "sizeof("; 7606 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7607 OS << ") - "; 7608 OS << "strlen("; 7609 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7610 OS << ") - 1"; 7611 7612 Diag(SL, diag::note_strncat_wrong_size) 7613 << FixItHint::CreateReplacement(SR, OS.str()); 7614 } 7615 7616 //===--- CHECK: Return Address of Stack Variable --------------------------===// 7617 7618 static const Expr *EvalVal(const Expr *E, 7619 SmallVectorImpl<const DeclRefExpr *> &refVars, 7620 const Decl *ParentDecl); 7621 static const Expr *EvalAddr(const Expr *E, 7622 SmallVectorImpl<const DeclRefExpr *> &refVars, 7623 const Decl *ParentDecl); 7624 7625 /// CheckReturnStackAddr - Check if a return statement returns the address 7626 /// of a stack variable. 7627 static void 7628 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 7629 SourceLocation ReturnLoc) { 7630 7631 const Expr *stackE = nullptr; 7632 SmallVector<const DeclRefExpr *, 8> refVars; 7633 7634 // Perform checking for returned stack addresses, local blocks, 7635 // label addresses or references to temporaries. 7636 if (lhsType->isPointerType() || 7637 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 7638 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 7639 } else if (lhsType->isReferenceType()) { 7640 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 7641 } 7642 7643 if (!stackE) 7644 return; // Nothing suspicious was found. 7645 7646 // Parameters are initialized in the calling scope, so taking the address 7647 // of a parameter reference doesn't need a warning. 7648 for (auto *DRE : refVars) 7649 if (isa<ParmVarDecl>(DRE->getDecl())) 7650 return; 7651 7652 SourceLocation diagLoc; 7653 SourceRange diagRange; 7654 if (refVars.empty()) { 7655 diagLoc = stackE->getLocStart(); 7656 diagRange = stackE->getSourceRange(); 7657 } else { 7658 // We followed through a reference variable. 'stackE' contains the 7659 // problematic expression but we will warn at the return statement pointing 7660 // at the reference variable. We will later display the "trail" of 7661 // reference variables using notes. 7662 diagLoc = refVars[0]->getLocStart(); 7663 diagRange = refVars[0]->getSourceRange(); 7664 } 7665 7666 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 7667 // address of local var 7668 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 7669 << DR->getDecl()->getDeclName() << diagRange; 7670 } else if (isa<BlockExpr>(stackE)) { // local block. 7671 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 7672 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 7673 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 7674 } else { // local temporary. 7675 // If there is an LValue->RValue conversion, then the value of the 7676 // reference type is used, not the reference. 7677 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 7678 if (ICE->getCastKind() == CK_LValueToRValue) { 7679 return; 7680 } 7681 } 7682 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 7683 << lhsType->isReferenceType() << diagRange; 7684 } 7685 7686 // Display the "trail" of reference variables that we followed until we 7687 // found the problematic expression using notes. 7688 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 7689 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 7690 // If this var binds to another reference var, show the range of the next 7691 // var, otherwise the var binds to the problematic expression, in which case 7692 // show the range of the expression. 7693 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 7694 : stackE->getSourceRange(); 7695 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 7696 << VD->getDeclName() << range; 7697 } 7698 } 7699 7700 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 7701 /// check if the expression in a return statement evaluates to an address 7702 /// to a location on the stack, a local block, an address of a label, or a 7703 /// reference to local temporary. The recursion is used to traverse the 7704 /// AST of the return expression, with recursion backtracking when we 7705 /// encounter a subexpression that (1) clearly does not lead to one of the 7706 /// above problematic expressions (2) is something we cannot determine leads to 7707 /// a problematic expression based on such local checking. 7708 /// 7709 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 7710 /// the expression that they point to. Such variables are added to the 7711 /// 'refVars' vector so that we know what the reference variable "trail" was. 7712 /// 7713 /// EvalAddr processes expressions that are pointers that are used as 7714 /// references (and not L-values). EvalVal handles all other values. 7715 /// At the base case of the recursion is a check for the above problematic 7716 /// expressions. 7717 /// 7718 /// This implementation handles: 7719 /// 7720 /// * pointer-to-pointer casts 7721 /// * implicit conversions from array references to pointers 7722 /// * taking the address of fields 7723 /// * arbitrary interplay between "&" and "*" operators 7724 /// * pointer arithmetic from an address of a stack variable 7725 /// * taking the address of an array element where the array is on the stack 7726 static const Expr *EvalAddr(const Expr *E, 7727 SmallVectorImpl<const DeclRefExpr *> &refVars, 7728 const Decl *ParentDecl) { 7729 if (E->isTypeDependent()) 7730 return nullptr; 7731 7732 // We should only be called for evaluating pointer expressions. 7733 assert((E->getType()->isAnyPointerType() || 7734 E->getType()->isBlockPointerType() || 7735 E->getType()->isObjCQualifiedIdType()) && 7736 "EvalAddr only works on pointers"); 7737 7738 E = E->IgnoreParens(); 7739 7740 // Our "symbolic interpreter" is just a dispatch off the currently 7741 // viewed AST node. We then recursively traverse the AST by calling 7742 // EvalAddr and EvalVal appropriately. 7743 switch (E->getStmtClass()) { 7744 case Stmt::DeclRefExprClass: { 7745 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7746 7747 // If we leave the immediate function, the lifetime isn't about to end. 7748 if (DR->refersToEnclosingVariableOrCapture()) 7749 return nullptr; 7750 7751 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 7752 // If this is a reference variable, follow through to the expression that 7753 // it points to. 7754 if (V->hasLocalStorage() && 7755 V->getType()->isReferenceType() && V->hasInit()) { 7756 // Add the reference variable to the "trail". 7757 refVars.push_back(DR); 7758 return EvalAddr(V->getInit(), refVars, ParentDecl); 7759 } 7760 7761 return nullptr; 7762 } 7763 7764 case Stmt::UnaryOperatorClass: { 7765 // The only unary operator that make sense to handle here 7766 // is AddrOf. All others don't make sense as pointers. 7767 const UnaryOperator *U = cast<UnaryOperator>(E); 7768 7769 if (U->getOpcode() == UO_AddrOf) 7770 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 7771 return nullptr; 7772 } 7773 7774 case Stmt::BinaryOperatorClass: { 7775 // Handle pointer arithmetic. All other binary operators are not valid 7776 // in this context. 7777 const BinaryOperator *B = cast<BinaryOperator>(E); 7778 BinaryOperatorKind op = B->getOpcode(); 7779 7780 if (op != BO_Add && op != BO_Sub) 7781 return nullptr; 7782 7783 const Expr *Base = B->getLHS(); 7784 7785 // Determine which argument is the real pointer base. It could be 7786 // the RHS argument instead of the LHS. 7787 if (!Base->getType()->isPointerType()) 7788 Base = B->getRHS(); 7789 7790 assert(Base->getType()->isPointerType()); 7791 return EvalAddr(Base, refVars, ParentDecl); 7792 } 7793 7794 // For conditional operators we need to see if either the LHS or RHS are 7795 // valid DeclRefExpr*s. If one of them is valid, we return it. 7796 case Stmt::ConditionalOperatorClass: { 7797 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7798 7799 // Handle the GNU extension for missing LHS. 7800 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 7801 if (const Expr *LHSExpr = C->getLHS()) { 7802 // In C++, we can have a throw-expression, which has 'void' type. 7803 if (!LHSExpr->getType()->isVoidType()) 7804 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 7805 return LHS; 7806 } 7807 7808 // In C++, we can have a throw-expression, which has 'void' type. 7809 if (C->getRHS()->getType()->isVoidType()) 7810 return nullptr; 7811 7812 return EvalAddr(C->getRHS(), refVars, ParentDecl); 7813 } 7814 7815 case Stmt::BlockExprClass: 7816 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 7817 return E; // local block. 7818 return nullptr; 7819 7820 case Stmt::AddrLabelExprClass: 7821 return E; // address of label. 7822 7823 case Stmt::ExprWithCleanupsClass: 7824 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7825 ParentDecl); 7826 7827 // For casts, we need to handle conversions from arrays to 7828 // pointer values, and pointer-to-pointer conversions. 7829 case Stmt::ImplicitCastExprClass: 7830 case Stmt::CStyleCastExprClass: 7831 case Stmt::CXXFunctionalCastExprClass: 7832 case Stmt::ObjCBridgedCastExprClass: 7833 case Stmt::CXXStaticCastExprClass: 7834 case Stmt::CXXDynamicCastExprClass: 7835 case Stmt::CXXConstCastExprClass: 7836 case Stmt::CXXReinterpretCastExprClass: { 7837 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 7838 switch (cast<CastExpr>(E)->getCastKind()) { 7839 case CK_LValueToRValue: 7840 case CK_NoOp: 7841 case CK_BaseToDerived: 7842 case CK_DerivedToBase: 7843 case CK_UncheckedDerivedToBase: 7844 case CK_Dynamic: 7845 case CK_CPointerToObjCPointerCast: 7846 case CK_BlockPointerToObjCPointerCast: 7847 case CK_AnyPointerToBlockPointerCast: 7848 return EvalAddr(SubExpr, refVars, ParentDecl); 7849 7850 case CK_ArrayToPointerDecay: 7851 return EvalVal(SubExpr, refVars, ParentDecl); 7852 7853 case CK_BitCast: 7854 if (SubExpr->getType()->isAnyPointerType() || 7855 SubExpr->getType()->isBlockPointerType() || 7856 SubExpr->getType()->isObjCQualifiedIdType()) 7857 return EvalAddr(SubExpr, refVars, ParentDecl); 7858 else 7859 return nullptr; 7860 7861 default: 7862 return nullptr; 7863 } 7864 } 7865 7866 case Stmt::MaterializeTemporaryExprClass: 7867 if (const Expr *Result = 7868 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7869 refVars, ParentDecl)) 7870 return Result; 7871 return E; 7872 7873 // Everything else: we simply don't reason about them. 7874 default: 7875 return nullptr; 7876 } 7877 } 7878 7879 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 7880 /// See the comments for EvalAddr for more details. 7881 static const Expr *EvalVal(const Expr *E, 7882 SmallVectorImpl<const DeclRefExpr *> &refVars, 7883 const Decl *ParentDecl) { 7884 do { 7885 // We should only be called for evaluating non-pointer expressions, or 7886 // expressions with a pointer type that are not used as references but 7887 // instead 7888 // are l-values (e.g., DeclRefExpr with a pointer type). 7889 7890 // Our "symbolic interpreter" is just a dispatch off the currently 7891 // viewed AST node. We then recursively traverse the AST by calling 7892 // EvalAddr and EvalVal appropriately. 7893 7894 E = E->IgnoreParens(); 7895 switch (E->getStmtClass()) { 7896 case Stmt::ImplicitCastExprClass: { 7897 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 7898 if (IE->getValueKind() == VK_LValue) { 7899 E = IE->getSubExpr(); 7900 continue; 7901 } 7902 return nullptr; 7903 } 7904 7905 case Stmt::ExprWithCleanupsClass: 7906 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7907 ParentDecl); 7908 7909 case Stmt::DeclRefExprClass: { 7910 // When we hit a DeclRefExpr we are looking at code that refers to a 7911 // variable's name. If it's not a reference variable we check if it has 7912 // local storage within the function, and if so, return the expression. 7913 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7914 7915 // If we leave the immediate function, the lifetime isn't about to end. 7916 if (DR->refersToEnclosingVariableOrCapture()) 7917 return nullptr; 7918 7919 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 7920 // Check if it refers to itself, e.g. "int& i = i;". 7921 if (V == ParentDecl) 7922 return DR; 7923 7924 if (V->hasLocalStorage()) { 7925 if (!V->getType()->isReferenceType()) 7926 return DR; 7927 7928 // Reference variable, follow through to the expression that 7929 // it points to. 7930 if (V->hasInit()) { 7931 // Add the reference variable to the "trail". 7932 refVars.push_back(DR); 7933 return EvalVal(V->getInit(), refVars, V); 7934 } 7935 } 7936 } 7937 7938 return nullptr; 7939 } 7940 7941 case Stmt::UnaryOperatorClass: { 7942 // The only unary operator that make sense to handle here 7943 // is Deref. All others don't resolve to a "name." This includes 7944 // handling all sorts of rvalues passed to a unary operator. 7945 const UnaryOperator *U = cast<UnaryOperator>(E); 7946 7947 if (U->getOpcode() == UO_Deref) 7948 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 7949 7950 return nullptr; 7951 } 7952 7953 case Stmt::ArraySubscriptExprClass: { 7954 // Array subscripts are potential references to data on the stack. We 7955 // retrieve the DeclRefExpr* for the array variable if it indeed 7956 // has local storage. 7957 const auto *ASE = cast<ArraySubscriptExpr>(E); 7958 if (ASE->isTypeDependent()) 7959 return nullptr; 7960 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 7961 } 7962 7963 case Stmt::OMPArraySectionExprClass: { 7964 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 7965 ParentDecl); 7966 } 7967 7968 case Stmt::ConditionalOperatorClass: { 7969 // For conditional operators we need to see if either the LHS or RHS are 7970 // non-NULL Expr's. If one is non-NULL, we return it. 7971 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7972 7973 // Handle the GNU extension for missing LHS. 7974 if (const Expr *LHSExpr = C->getLHS()) { 7975 // In C++, we can have a throw-expression, which has 'void' type. 7976 if (!LHSExpr->getType()->isVoidType()) 7977 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 7978 return LHS; 7979 } 7980 7981 // In C++, we can have a throw-expression, which has 'void' type. 7982 if (C->getRHS()->getType()->isVoidType()) 7983 return nullptr; 7984 7985 return EvalVal(C->getRHS(), refVars, ParentDecl); 7986 } 7987 7988 // Accesses to members are potential references to data on the stack. 7989 case Stmt::MemberExprClass: { 7990 const MemberExpr *M = cast<MemberExpr>(E); 7991 7992 // Check for indirect access. We only want direct field accesses. 7993 if (M->isArrow()) 7994 return nullptr; 7995 7996 // Check whether the member type is itself a reference, in which case 7997 // we're not going to refer to the member, but to what the member refers 7998 // to. 7999 if (M->getMemberDecl()->getType()->isReferenceType()) 8000 return nullptr; 8001 8002 return EvalVal(M->getBase(), refVars, ParentDecl); 8003 } 8004 8005 case Stmt::MaterializeTemporaryExprClass: 8006 if (const Expr *Result = 8007 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8008 refVars, ParentDecl)) 8009 return Result; 8010 return E; 8011 8012 default: 8013 // Check that we don't return or take the address of a reference to a 8014 // temporary. This is only useful in C++. 8015 if (!E->isTypeDependent() && E->isRValue()) 8016 return E; 8017 8018 // Everything else: we simply don't reason about them. 8019 return nullptr; 8020 } 8021 } while (true); 8022 } 8023 8024 void 8025 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 8026 SourceLocation ReturnLoc, 8027 bool isObjCMethod, 8028 const AttrVec *Attrs, 8029 const FunctionDecl *FD) { 8030 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 8031 8032 // Check if the return value is null but should not be. 8033 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 8034 (!isObjCMethod && isNonNullType(Context, lhsType))) && 8035 CheckNonNullExpr(*this, RetValExp)) 8036 Diag(ReturnLoc, diag::warn_null_ret) 8037 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 8038 8039 // C++11 [basic.stc.dynamic.allocation]p4: 8040 // If an allocation function declared with a non-throwing 8041 // exception-specification fails to allocate storage, it shall return 8042 // a null pointer. Any other allocation function that fails to allocate 8043 // storage shall indicate failure only by throwing an exception [...] 8044 if (FD) { 8045 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 8046 if (Op == OO_New || Op == OO_Array_New) { 8047 const FunctionProtoType *Proto 8048 = FD->getType()->castAs<FunctionProtoType>(); 8049 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 8050 CheckNonNullExpr(*this, RetValExp)) 8051 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 8052 << FD << getLangOpts().CPlusPlus11; 8053 } 8054 } 8055 } 8056 8057 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 8058 8059 /// Check for comparisons of floating point operands using != and ==. 8060 /// Issue a warning if these are no self-comparisons, as they are not likely 8061 /// to do what the programmer intended. 8062 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 8063 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 8064 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 8065 8066 // Special case: check for x == x (which is OK). 8067 // Do not emit warnings for such cases. 8068 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 8069 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 8070 if (DRL->getDecl() == DRR->getDecl()) 8071 return; 8072 8073 // Special case: check for comparisons against literals that can be exactly 8074 // represented by APFloat. In such cases, do not emit a warning. This 8075 // is a heuristic: often comparison against such literals are used to 8076 // detect if a value in a variable has not changed. This clearly can 8077 // lead to false negatives. 8078 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 8079 if (FLL->isExact()) 8080 return; 8081 } else 8082 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 8083 if (FLR->isExact()) 8084 return; 8085 8086 // Check for comparisons with builtin types. 8087 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 8088 if (CL->getBuiltinCallee()) 8089 return; 8090 8091 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 8092 if (CR->getBuiltinCallee()) 8093 return; 8094 8095 // Emit the diagnostic. 8096 Diag(Loc, diag::warn_floatingpoint_eq) 8097 << LHS->getSourceRange() << RHS->getSourceRange(); 8098 } 8099 8100 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 8101 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 8102 8103 namespace { 8104 8105 /// Structure recording the 'active' range of an integer-valued 8106 /// expression. 8107 struct IntRange { 8108 /// The number of bits active in the int. 8109 unsigned Width; 8110 8111 /// True if the int is known not to have negative values. 8112 bool NonNegative; 8113 8114 IntRange(unsigned Width, bool NonNegative) 8115 : Width(Width), NonNegative(NonNegative) 8116 {} 8117 8118 /// Returns the range of the bool type. 8119 static IntRange forBoolType() { 8120 return IntRange(1, true); 8121 } 8122 8123 /// Returns the range of an opaque value of the given integral type. 8124 static IntRange forValueOfType(ASTContext &C, QualType T) { 8125 return forValueOfCanonicalType(C, 8126 T->getCanonicalTypeInternal().getTypePtr()); 8127 } 8128 8129 /// Returns the range of an opaque value of a canonical integral type. 8130 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 8131 assert(T->isCanonicalUnqualified()); 8132 8133 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8134 T = VT->getElementType().getTypePtr(); 8135 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8136 T = CT->getElementType().getTypePtr(); 8137 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8138 T = AT->getValueType().getTypePtr(); 8139 8140 // For enum types, use the known bit width of the enumerators. 8141 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 8142 EnumDecl *Enum = ET->getDecl(); 8143 if (!Enum->isCompleteDefinition()) 8144 return IntRange(C.getIntWidth(QualType(T, 0)), false); 8145 8146 unsigned NumPositive = Enum->getNumPositiveBits(); 8147 unsigned NumNegative = Enum->getNumNegativeBits(); 8148 8149 if (NumNegative == 0) 8150 return IntRange(NumPositive, true/*NonNegative*/); 8151 else 8152 return IntRange(std::max(NumPositive + 1, NumNegative), 8153 false/*NonNegative*/); 8154 } 8155 8156 const BuiltinType *BT = cast<BuiltinType>(T); 8157 assert(BT->isInteger()); 8158 8159 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8160 } 8161 8162 /// Returns the "target" range of a canonical integral type, i.e. 8163 /// the range of values expressible in the type. 8164 /// 8165 /// This matches forValueOfCanonicalType except that enums have the 8166 /// full range of their type, not the range of their enumerators. 8167 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 8168 assert(T->isCanonicalUnqualified()); 8169 8170 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8171 T = VT->getElementType().getTypePtr(); 8172 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8173 T = CT->getElementType().getTypePtr(); 8174 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8175 T = AT->getValueType().getTypePtr(); 8176 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8177 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 8178 8179 const BuiltinType *BT = cast<BuiltinType>(T); 8180 assert(BT->isInteger()); 8181 8182 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8183 } 8184 8185 /// Returns the supremum of two ranges: i.e. their conservative merge. 8186 static IntRange join(IntRange L, IntRange R) { 8187 return IntRange(std::max(L.Width, R.Width), 8188 L.NonNegative && R.NonNegative); 8189 } 8190 8191 /// Returns the infinum of two ranges: i.e. their aggressive merge. 8192 static IntRange meet(IntRange L, IntRange R) { 8193 return IntRange(std::min(L.Width, R.Width), 8194 L.NonNegative || R.NonNegative); 8195 } 8196 }; 8197 8198 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 8199 if (value.isSigned() && value.isNegative()) 8200 return IntRange(value.getMinSignedBits(), false); 8201 8202 if (value.getBitWidth() > MaxWidth) 8203 value = value.trunc(MaxWidth); 8204 8205 // isNonNegative() just checks the sign bit without considering 8206 // signedness. 8207 return IntRange(value.getActiveBits(), true); 8208 } 8209 8210 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 8211 unsigned MaxWidth) { 8212 if (result.isInt()) 8213 return GetValueRange(C, result.getInt(), MaxWidth); 8214 8215 if (result.isVector()) { 8216 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 8217 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 8218 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 8219 R = IntRange::join(R, El); 8220 } 8221 return R; 8222 } 8223 8224 if (result.isComplexInt()) { 8225 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 8226 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 8227 return IntRange::join(R, I); 8228 } 8229 8230 // This can happen with lossless casts to intptr_t of "based" lvalues. 8231 // Assume it might use arbitrary bits. 8232 // FIXME: The only reason we need to pass the type in here is to get 8233 // the sign right on this one case. It would be nice if APValue 8234 // preserved this. 8235 assert(result.isLValue() || result.isAddrLabelDiff()); 8236 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 8237 } 8238 8239 QualType GetExprType(const Expr *E) { 8240 QualType Ty = E->getType(); 8241 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 8242 Ty = AtomicRHS->getValueType(); 8243 return Ty; 8244 } 8245 8246 /// Pseudo-evaluate the given integer expression, estimating the 8247 /// range of values it might take. 8248 /// 8249 /// \param MaxWidth - the width to which the value will be truncated 8250 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 8251 E = E->IgnoreParens(); 8252 8253 // Try a full evaluation first. 8254 Expr::EvalResult result; 8255 if (E->EvaluateAsRValue(result, C)) 8256 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 8257 8258 // I think we only want to look through implicit casts here; if the 8259 // user has an explicit widening cast, we should treat the value as 8260 // being of the new, wider type. 8261 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 8262 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 8263 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 8264 8265 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 8266 8267 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 8268 CE->getCastKind() == CK_BooleanToSignedIntegral; 8269 8270 // Assume that non-integer casts can span the full range of the type. 8271 if (!isIntegerCast) 8272 return OutputTypeRange; 8273 8274 IntRange SubRange 8275 = GetExprRange(C, CE->getSubExpr(), 8276 std::min(MaxWidth, OutputTypeRange.Width)); 8277 8278 // Bail out if the subexpr's range is as wide as the cast type. 8279 if (SubRange.Width >= OutputTypeRange.Width) 8280 return OutputTypeRange; 8281 8282 // Otherwise, we take the smaller width, and we're non-negative if 8283 // either the output type or the subexpr is. 8284 return IntRange(SubRange.Width, 8285 SubRange.NonNegative || OutputTypeRange.NonNegative); 8286 } 8287 8288 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 8289 // If we can fold the condition, just take that operand. 8290 bool CondResult; 8291 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 8292 return GetExprRange(C, CondResult ? CO->getTrueExpr() 8293 : CO->getFalseExpr(), 8294 MaxWidth); 8295 8296 // Otherwise, conservatively merge. 8297 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 8298 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 8299 return IntRange::join(L, R); 8300 } 8301 8302 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 8303 switch (BO->getOpcode()) { 8304 8305 // Boolean-valued operations are single-bit and positive. 8306 case BO_LAnd: 8307 case BO_LOr: 8308 case BO_LT: 8309 case BO_GT: 8310 case BO_LE: 8311 case BO_GE: 8312 case BO_EQ: 8313 case BO_NE: 8314 return IntRange::forBoolType(); 8315 8316 // The type of the assignments is the type of the LHS, so the RHS 8317 // is not necessarily the same type. 8318 case BO_MulAssign: 8319 case BO_DivAssign: 8320 case BO_RemAssign: 8321 case BO_AddAssign: 8322 case BO_SubAssign: 8323 case BO_XorAssign: 8324 case BO_OrAssign: 8325 // TODO: bitfields? 8326 return IntRange::forValueOfType(C, GetExprType(E)); 8327 8328 // Simple assignments just pass through the RHS, which will have 8329 // been coerced to the LHS type. 8330 case BO_Assign: 8331 // TODO: bitfields? 8332 return GetExprRange(C, BO->getRHS(), MaxWidth); 8333 8334 // Operations with opaque sources are black-listed. 8335 case BO_PtrMemD: 8336 case BO_PtrMemI: 8337 return IntRange::forValueOfType(C, GetExprType(E)); 8338 8339 // Bitwise-and uses the *infinum* of the two source ranges. 8340 case BO_And: 8341 case BO_AndAssign: 8342 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 8343 GetExprRange(C, BO->getRHS(), MaxWidth)); 8344 8345 // Left shift gets black-listed based on a judgement call. 8346 case BO_Shl: 8347 // ...except that we want to treat '1 << (blah)' as logically 8348 // positive. It's an important idiom. 8349 if (IntegerLiteral *I 8350 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 8351 if (I->getValue() == 1) { 8352 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 8353 return IntRange(R.Width, /*NonNegative*/ true); 8354 } 8355 } 8356 // fallthrough 8357 8358 case BO_ShlAssign: 8359 return IntRange::forValueOfType(C, GetExprType(E)); 8360 8361 // Right shift by a constant can narrow its left argument. 8362 case BO_Shr: 8363 case BO_ShrAssign: { 8364 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8365 8366 // If the shift amount is a positive constant, drop the width by 8367 // that much. 8368 llvm::APSInt shift; 8369 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 8370 shift.isNonNegative()) { 8371 unsigned zext = shift.getZExtValue(); 8372 if (zext >= L.Width) 8373 L.Width = (L.NonNegative ? 0 : 1); 8374 else 8375 L.Width -= zext; 8376 } 8377 8378 return L; 8379 } 8380 8381 // Comma acts as its right operand. 8382 case BO_Comma: 8383 return GetExprRange(C, BO->getRHS(), MaxWidth); 8384 8385 // Black-list pointer subtractions. 8386 case BO_Sub: 8387 if (BO->getLHS()->getType()->isPointerType()) 8388 return IntRange::forValueOfType(C, GetExprType(E)); 8389 break; 8390 8391 // The width of a division result is mostly determined by the size 8392 // of the LHS. 8393 case BO_Div: { 8394 // Don't 'pre-truncate' the operands. 8395 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8396 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8397 8398 // If the divisor is constant, use that. 8399 llvm::APSInt divisor; 8400 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 8401 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 8402 if (log2 >= L.Width) 8403 L.Width = (L.NonNegative ? 0 : 1); 8404 else 8405 L.Width = std::min(L.Width - log2, MaxWidth); 8406 return L; 8407 } 8408 8409 // Otherwise, just use the LHS's width. 8410 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8411 return IntRange(L.Width, L.NonNegative && R.NonNegative); 8412 } 8413 8414 // The result of a remainder can't be larger than the result of 8415 // either side. 8416 case BO_Rem: { 8417 // Don't 'pre-truncate' the operands. 8418 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8419 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8420 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8421 8422 IntRange meet = IntRange::meet(L, R); 8423 meet.Width = std::min(meet.Width, MaxWidth); 8424 return meet; 8425 } 8426 8427 // The default behavior is okay for these. 8428 case BO_Mul: 8429 case BO_Add: 8430 case BO_Xor: 8431 case BO_Or: 8432 break; 8433 } 8434 8435 // The default case is to treat the operation as if it were closed 8436 // on the narrowest type that encompasses both operands. 8437 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8438 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 8439 return IntRange::join(L, R); 8440 } 8441 8442 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 8443 switch (UO->getOpcode()) { 8444 // Boolean-valued operations are white-listed. 8445 case UO_LNot: 8446 return IntRange::forBoolType(); 8447 8448 // Operations with opaque sources are black-listed. 8449 case UO_Deref: 8450 case UO_AddrOf: // should be impossible 8451 return IntRange::forValueOfType(C, GetExprType(E)); 8452 8453 default: 8454 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 8455 } 8456 } 8457 8458 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 8459 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 8460 8461 if (const auto *BitField = E->getSourceBitField()) 8462 return IntRange(BitField->getBitWidthValue(C), 8463 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 8464 8465 return IntRange::forValueOfType(C, GetExprType(E)); 8466 } 8467 8468 IntRange GetExprRange(ASTContext &C, const Expr *E) { 8469 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 8470 } 8471 8472 /// Checks whether the given value, which currently has the given 8473 /// source semantics, has the same value when coerced through the 8474 /// target semantics. 8475 bool IsSameFloatAfterCast(const llvm::APFloat &value, 8476 const llvm::fltSemantics &Src, 8477 const llvm::fltSemantics &Tgt) { 8478 llvm::APFloat truncated = value; 8479 8480 bool ignored; 8481 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 8482 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 8483 8484 return truncated.bitwiseIsEqual(value); 8485 } 8486 8487 /// Checks whether the given value, which currently has the given 8488 /// source semantics, has the same value when coerced through the 8489 /// target semantics. 8490 /// 8491 /// The value might be a vector of floats (or a complex number). 8492 bool IsSameFloatAfterCast(const APValue &value, 8493 const llvm::fltSemantics &Src, 8494 const llvm::fltSemantics &Tgt) { 8495 if (value.isFloat()) 8496 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 8497 8498 if (value.isVector()) { 8499 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 8500 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 8501 return false; 8502 return true; 8503 } 8504 8505 assert(value.isComplexFloat()); 8506 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 8507 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 8508 } 8509 8510 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 8511 8512 bool IsZero(Sema &S, Expr *E) { 8513 // Suppress cases where we are comparing against an enum constant. 8514 if (const DeclRefExpr *DR = 8515 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 8516 if (isa<EnumConstantDecl>(DR->getDecl())) 8517 return false; 8518 8519 // Suppress cases where the '0' value is expanded from a macro. 8520 if (E->getLocStart().isMacroID()) 8521 return false; 8522 8523 llvm::APSInt Value; 8524 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 8525 } 8526 8527 bool HasEnumType(Expr *E) { 8528 // Strip off implicit integral promotions. 8529 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8530 if (ICE->getCastKind() != CK_IntegralCast && 8531 ICE->getCastKind() != CK_NoOp) 8532 break; 8533 E = ICE->getSubExpr(); 8534 } 8535 8536 return E->getType()->isEnumeralType(); 8537 } 8538 8539 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 8540 // Disable warning in template instantiations. 8541 if (S.inTemplateInstantiation()) 8542 return; 8543 8544 BinaryOperatorKind op = E->getOpcode(); 8545 if (E->isValueDependent()) 8546 return; 8547 8548 if (op == BO_LT && IsZero(S, E->getRHS())) { 8549 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8550 << "< 0" << "false" << HasEnumType(E->getLHS()) 8551 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8552 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 8553 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8554 << ">= 0" << "true" << HasEnumType(E->getLHS()) 8555 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8556 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 8557 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8558 << "0 >" << "false" << HasEnumType(E->getRHS()) 8559 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8560 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 8561 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8562 << "0 <=" << "true" << HasEnumType(E->getRHS()) 8563 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8564 } 8565 } 8566 8567 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant, 8568 Expr *Other, const llvm::APSInt &Value, 8569 bool RhsConstant) { 8570 // Disable warning in template instantiations. 8571 if (S.inTemplateInstantiation()) 8572 return; 8573 8574 // TODO: Investigate using GetExprRange() to get tighter bounds 8575 // on the bit ranges. 8576 QualType OtherT = Other->getType(); 8577 if (const auto *AT = OtherT->getAs<AtomicType>()) 8578 OtherT = AT->getValueType(); 8579 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 8580 unsigned OtherWidth = OtherRange.Width; 8581 8582 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 8583 8584 // 0 values are handled later by CheckTrivialUnsignedComparison(). 8585 if ((Value == 0) && (!OtherIsBooleanType)) 8586 return; 8587 8588 BinaryOperatorKind op = E->getOpcode(); 8589 bool IsTrue = true; 8590 8591 // Used for diagnostic printout. 8592 enum { 8593 LiteralConstant = 0, 8594 CXXBoolLiteralTrue, 8595 CXXBoolLiteralFalse 8596 } LiteralOrBoolConstant = LiteralConstant; 8597 8598 if (!OtherIsBooleanType) { 8599 QualType ConstantT = Constant->getType(); 8600 QualType CommonT = E->getLHS()->getType(); 8601 8602 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 8603 return; 8604 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 8605 "comparison with non-integer type"); 8606 8607 bool ConstantSigned = ConstantT->isSignedIntegerType(); 8608 bool CommonSigned = CommonT->isSignedIntegerType(); 8609 8610 bool EqualityOnly = false; 8611 8612 if (CommonSigned) { 8613 // The common type is signed, therefore no signed to unsigned conversion. 8614 if (!OtherRange.NonNegative) { 8615 // Check that the constant is representable in type OtherT. 8616 if (ConstantSigned) { 8617 if (OtherWidth >= Value.getMinSignedBits()) 8618 return; 8619 } else { // !ConstantSigned 8620 if (OtherWidth >= Value.getActiveBits() + 1) 8621 return; 8622 } 8623 } else { // !OtherSigned 8624 // Check that the constant is representable in type OtherT. 8625 // Negative values are out of range. 8626 if (ConstantSigned) { 8627 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 8628 return; 8629 } else { // !ConstantSigned 8630 if (OtherWidth >= Value.getActiveBits()) 8631 return; 8632 } 8633 } 8634 } else { // !CommonSigned 8635 if (OtherRange.NonNegative) { 8636 if (OtherWidth >= Value.getActiveBits()) 8637 return; 8638 } else { // OtherSigned 8639 assert(!ConstantSigned && 8640 "Two signed types converted to unsigned types."); 8641 // Check to see if the constant is representable in OtherT. 8642 if (OtherWidth > Value.getActiveBits()) 8643 return; 8644 // Check to see if the constant is equivalent to a negative value 8645 // cast to CommonT. 8646 if (S.Context.getIntWidth(ConstantT) == 8647 S.Context.getIntWidth(CommonT) && 8648 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 8649 return; 8650 // The constant value rests between values that OtherT can represent 8651 // after conversion. Relational comparison still works, but equality 8652 // comparisons will be tautological. 8653 EqualityOnly = true; 8654 } 8655 } 8656 8657 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 8658 8659 if (op == BO_EQ || op == BO_NE) { 8660 IsTrue = op == BO_NE; 8661 } else if (EqualityOnly) { 8662 return; 8663 } else if (RhsConstant) { 8664 if (op == BO_GT || op == BO_GE) 8665 IsTrue = !PositiveConstant; 8666 else // op == BO_LT || op == BO_LE 8667 IsTrue = PositiveConstant; 8668 } else { 8669 if (op == BO_LT || op == BO_LE) 8670 IsTrue = !PositiveConstant; 8671 else // op == BO_GT || op == BO_GE 8672 IsTrue = PositiveConstant; 8673 } 8674 } else { 8675 // Other isKnownToHaveBooleanValue 8676 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 8677 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 8678 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 8679 8680 static const struct LinkedConditions { 8681 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 8682 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 8683 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 8684 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 8685 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 8686 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 8687 8688 } TruthTable = { 8689 // Constant on LHS. | Constant on RHS. | 8690 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 8691 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 8692 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 8693 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 8694 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 8695 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 8696 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 8697 }; 8698 8699 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 8700 8701 enum ConstantValue ConstVal = Zero; 8702 if (Value.isUnsigned() || Value.isNonNegative()) { 8703 if (Value == 0) { 8704 LiteralOrBoolConstant = 8705 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 8706 ConstVal = Zero; 8707 } else if (Value == 1) { 8708 LiteralOrBoolConstant = 8709 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 8710 ConstVal = One; 8711 } else { 8712 LiteralOrBoolConstant = LiteralConstant; 8713 ConstVal = GT_One; 8714 } 8715 } else { 8716 ConstVal = LT_Zero; 8717 } 8718 8719 CompareBoolWithConstantResult CmpRes; 8720 8721 switch (op) { 8722 case BO_LT: 8723 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 8724 break; 8725 case BO_GT: 8726 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 8727 break; 8728 case BO_LE: 8729 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 8730 break; 8731 case BO_GE: 8732 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 8733 break; 8734 case BO_EQ: 8735 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 8736 break; 8737 case BO_NE: 8738 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 8739 break; 8740 default: 8741 CmpRes = Unkwn; 8742 break; 8743 } 8744 8745 if (CmpRes == AFals) { 8746 IsTrue = false; 8747 } else if (CmpRes == ATrue) { 8748 IsTrue = true; 8749 } else { 8750 return; 8751 } 8752 } 8753 8754 // If this is a comparison to an enum constant, include that 8755 // constant in the diagnostic. 8756 const EnumConstantDecl *ED = nullptr; 8757 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 8758 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 8759 8760 SmallString<64> PrettySourceValue; 8761 llvm::raw_svector_ostream OS(PrettySourceValue); 8762 if (ED) 8763 OS << '\'' << *ED << "' (" << Value << ")"; 8764 else 8765 OS << Value; 8766 8767 S.DiagRuntimeBehavior( 8768 E->getOperatorLoc(), E, 8769 S.PDiag(diag::warn_out_of_range_compare) 8770 << OS.str() << LiteralOrBoolConstant 8771 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 8772 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 8773 } 8774 8775 /// Analyze the operands of the given comparison. Implements the 8776 /// fallback case from AnalyzeComparison. 8777 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 8778 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8779 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8780 } 8781 8782 /// \brief Implements -Wsign-compare. 8783 /// 8784 /// \param E the binary operator to check for warnings 8785 void AnalyzeComparison(Sema &S, BinaryOperator *E) { 8786 // The type the comparison is being performed in. 8787 QualType T = E->getLHS()->getType(); 8788 8789 // Only analyze comparison operators where both sides have been converted to 8790 // the same type. 8791 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 8792 return AnalyzeImpConvsInComparison(S, E); 8793 8794 // Don't analyze value-dependent comparisons directly. 8795 if (E->isValueDependent()) 8796 return AnalyzeImpConvsInComparison(S, E); 8797 8798 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 8799 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 8800 8801 bool IsComparisonConstant = false; 8802 8803 // Check whether an integer constant comparison results in a value 8804 // of 'true' or 'false'. 8805 if (T->isIntegralType(S.Context)) { 8806 llvm::APSInt RHSValue; 8807 bool IsRHSIntegralLiteral = 8808 RHS->isIntegerConstantExpr(RHSValue, S.Context); 8809 llvm::APSInt LHSValue; 8810 bool IsLHSIntegralLiteral = 8811 LHS->isIntegerConstantExpr(LHSValue, S.Context); 8812 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 8813 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 8814 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 8815 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 8816 else 8817 IsComparisonConstant = 8818 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 8819 } else if (!T->hasUnsignedIntegerRepresentation()) 8820 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 8821 8822 // We don't do anything special if this isn't an unsigned integral 8823 // comparison: we're only interested in integral comparisons, and 8824 // signed comparisons only happen in cases we don't care to warn about. 8825 // 8826 // We also don't care about value-dependent expressions or expressions 8827 // whose result is a constant. 8828 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 8829 return AnalyzeImpConvsInComparison(S, E); 8830 8831 // Check to see if one of the (unmodified) operands is of different 8832 // signedness. 8833 Expr *signedOperand, *unsignedOperand; 8834 if (LHS->getType()->hasSignedIntegerRepresentation()) { 8835 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 8836 "unsigned comparison between two signed integer expressions?"); 8837 signedOperand = LHS; 8838 unsignedOperand = RHS; 8839 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 8840 signedOperand = RHS; 8841 unsignedOperand = LHS; 8842 } else { 8843 CheckTrivialUnsignedComparison(S, E); 8844 return AnalyzeImpConvsInComparison(S, E); 8845 } 8846 8847 // Otherwise, calculate the effective range of the signed operand. 8848 IntRange signedRange = GetExprRange(S.Context, signedOperand); 8849 8850 // Go ahead and analyze implicit conversions in the operands. Note 8851 // that we skip the implicit conversions on both sides. 8852 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 8853 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 8854 8855 // If the signed range is non-negative, -Wsign-compare won't fire, 8856 // but we should still check for comparisons which are always true 8857 // or false. 8858 if (signedRange.NonNegative) 8859 return CheckTrivialUnsignedComparison(S, E); 8860 8861 // For (in)equality comparisons, if the unsigned operand is a 8862 // constant which cannot collide with a overflowed signed operand, 8863 // then reinterpreting the signed operand as unsigned will not 8864 // change the result of the comparison. 8865 if (E->isEqualityOp()) { 8866 unsigned comparisonWidth = S.Context.getIntWidth(T); 8867 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 8868 8869 // We should never be unable to prove that the unsigned operand is 8870 // non-negative. 8871 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 8872 8873 if (unsignedRange.Width < comparisonWidth) 8874 return; 8875 } 8876 8877 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 8878 S.PDiag(diag::warn_mixed_sign_comparison) 8879 << LHS->getType() << RHS->getType() 8880 << LHS->getSourceRange() << RHS->getSourceRange()); 8881 } 8882 8883 /// Analyzes an attempt to assign the given value to a bitfield. 8884 /// 8885 /// Returns true if there was something fishy about the attempt. 8886 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 8887 SourceLocation InitLoc) { 8888 assert(Bitfield->isBitField()); 8889 if (Bitfield->isInvalidDecl()) 8890 return false; 8891 8892 // White-list bool bitfields. 8893 QualType BitfieldType = Bitfield->getType(); 8894 if (BitfieldType->isBooleanType()) 8895 return false; 8896 8897 if (BitfieldType->isEnumeralType()) { 8898 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 8899 // If the underlying enum type was not explicitly specified as an unsigned 8900 // type and the enum contain only positive values, MSVC++ will cause an 8901 // inconsistency by storing this as a signed type. 8902 if (S.getLangOpts().CPlusPlus11 && 8903 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 8904 BitfieldEnumDecl->getNumPositiveBits() > 0 && 8905 BitfieldEnumDecl->getNumNegativeBits() == 0) { 8906 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 8907 << BitfieldEnumDecl->getNameAsString(); 8908 } 8909 } 8910 8911 if (Bitfield->getType()->isBooleanType()) 8912 return false; 8913 8914 // Ignore value- or type-dependent expressions. 8915 if (Bitfield->getBitWidth()->isValueDependent() || 8916 Bitfield->getBitWidth()->isTypeDependent() || 8917 Init->isValueDependent() || 8918 Init->isTypeDependent()) 8919 return false; 8920 8921 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 8922 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 8923 8924 llvm::APSInt Value; 8925 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 8926 Expr::SE_AllowSideEffects)) { 8927 // The RHS is not constant. If the RHS has an enum type, make sure the 8928 // bitfield is wide enough to hold all the values of the enum without 8929 // truncation. 8930 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 8931 EnumDecl *ED = EnumTy->getDecl(); 8932 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 8933 8934 // Enum types are implicitly signed on Windows, so check if there are any 8935 // negative enumerators to see if the enum was intended to be signed or 8936 // not. 8937 bool SignedEnum = ED->getNumNegativeBits() > 0; 8938 8939 // Check for surprising sign changes when assigning enum values to a 8940 // bitfield of different signedness. If the bitfield is signed and we 8941 // have exactly the right number of bits to store this unsigned enum, 8942 // suggest changing the enum to an unsigned type. This typically happens 8943 // on Windows where unfixed enums always use an underlying type of 'int'. 8944 unsigned DiagID = 0; 8945 if (SignedEnum && !SignedBitfield) { 8946 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 8947 } else if (SignedBitfield && !SignedEnum && 8948 ED->getNumPositiveBits() == FieldWidth) { 8949 DiagID = diag::warn_signed_bitfield_enum_conversion; 8950 } 8951 8952 if (DiagID) { 8953 S.Diag(InitLoc, DiagID) << Bitfield << ED; 8954 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 8955 SourceRange TypeRange = 8956 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 8957 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 8958 << SignedEnum << TypeRange; 8959 } 8960 8961 // Compute the required bitwidth. If the enum has negative values, we need 8962 // one more bit than the normal number of positive bits to represent the 8963 // sign bit. 8964 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 8965 ED->getNumNegativeBits()) 8966 : ED->getNumPositiveBits(); 8967 8968 // Check the bitwidth. 8969 if (BitsNeeded > FieldWidth) { 8970 Expr *WidthExpr = Bitfield->getBitWidth(); 8971 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 8972 << Bitfield << ED; 8973 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 8974 << BitsNeeded << ED << WidthExpr->getSourceRange(); 8975 } 8976 } 8977 8978 return false; 8979 } 8980 8981 unsigned OriginalWidth = Value.getBitWidth(); 8982 8983 if (!Value.isSigned() || Value.isNegative()) 8984 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 8985 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 8986 OriginalWidth = Value.getMinSignedBits(); 8987 8988 if (OriginalWidth <= FieldWidth) 8989 return false; 8990 8991 // Compute the value which the bitfield will contain. 8992 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 8993 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 8994 8995 // Check whether the stored value is equal to the original value. 8996 TruncatedValue = TruncatedValue.extend(OriginalWidth); 8997 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 8998 return false; 8999 9000 // Special-case bitfields of width 1: booleans are naturally 0/1, and 9001 // therefore don't strictly fit into a signed bitfield of width 1. 9002 if (FieldWidth == 1 && Value == 1) 9003 return false; 9004 9005 std::string PrettyValue = Value.toString(10); 9006 std::string PrettyTrunc = TruncatedValue.toString(10); 9007 9008 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 9009 << PrettyValue << PrettyTrunc << OriginalInit->getType() 9010 << Init->getSourceRange(); 9011 9012 return true; 9013 } 9014 9015 /// Analyze the given simple or compound assignment for warning-worthy 9016 /// operations. 9017 void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 9018 // Just recurse on the LHS. 9019 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9020 9021 // We want to recurse on the RHS as normal unless we're assigning to 9022 // a bitfield. 9023 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 9024 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 9025 E->getOperatorLoc())) { 9026 // Recurse, ignoring any implicit conversions on the RHS. 9027 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 9028 E->getOperatorLoc()); 9029 } 9030 } 9031 9032 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9033 } 9034 9035 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9036 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 9037 SourceLocation CContext, unsigned diag, 9038 bool pruneControlFlow = false) { 9039 if (pruneControlFlow) { 9040 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9041 S.PDiag(diag) 9042 << SourceType << T << E->getSourceRange() 9043 << SourceRange(CContext)); 9044 return; 9045 } 9046 S.Diag(E->getExprLoc(), diag) 9047 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 9048 } 9049 9050 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9051 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 9052 unsigned diag, bool pruneControlFlow = false) { 9053 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 9054 } 9055 9056 9057 /// Diagnose an implicit cast from a floating point value to an integer value. 9058 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 9059 9060 SourceLocation CContext) { 9061 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 9062 const bool PruneWarnings = S.inTemplateInstantiation(); 9063 9064 Expr *InnerE = E->IgnoreParenImpCasts(); 9065 // We also want to warn on, e.g., "int i = -1.234" 9066 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 9067 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 9068 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 9069 9070 const bool IsLiteral = 9071 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 9072 9073 llvm::APFloat Value(0.0); 9074 bool IsConstant = 9075 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 9076 if (!IsConstant) { 9077 return DiagnoseImpCast(S, E, T, CContext, 9078 diag::warn_impcast_float_integer, PruneWarnings); 9079 } 9080 9081 bool isExact = false; 9082 9083 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 9084 T->hasUnsignedIntegerRepresentation()); 9085 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 9086 &isExact) == llvm::APFloat::opOK && 9087 isExact) { 9088 if (IsLiteral) return; 9089 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 9090 PruneWarnings); 9091 } 9092 9093 unsigned DiagID = 0; 9094 if (IsLiteral) { 9095 // Warn on floating point literal to integer. 9096 DiagID = diag::warn_impcast_literal_float_to_integer; 9097 } else if (IntegerValue == 0) { 9098 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 9099 return DiagnoseImpCast(S, E, T, CContext, 9100 diag::warn_impcast_float_integer, PruneWarnings); 9101 } 9102 // Warn on non-zero to zero conversion. 9103 DiagID = diag::warn_impcast_float_to_integer_zero; 9104 } else { 9105 if (IntegerValue.isUnsigned()) { 9106 if (!IntegerValue.isMaxValue()) { 9107 return DiagnoseImpCast(S, E, T, CContext, 9108 diag::warn_impcast_float_integer, PruneWarnings); 9109 } 9110 } else { // IntegerValue.isSigned() 9111 if (!IntegerValue.isMaxSignedValue() && 9112 !IntegerValue.isMinSignedValue()) { 9113 return DiagnoseImpCast(S, E, T, CContext, 9114 diag::warn_impcast_float_integer, PruneWarnings); 9115 } 9116 } 9117 // Warn on evaluatable floating point expression to integer conversion. 9118 DiagID = diag::warn_impcast_float_to_integer; 9119 } 9120 9121 // FIXME: Force the precision of the source value down so we don't print 9122 // digits which are usually useless (we don't really care here if we 9123 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 9124 // would automatically print the shortest representation, but it's a bit 9125 // tricky to implement. 9126 SmallString<16> PrettySourceValue; 9127 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 9128 precision = (precision * 59 + 195) / 196; 9129 Value.toString(PrettySourceValue, precision); 9130 9131 SmallString<16> PrettyTargetValue; 9132 if (IsBool) 9133 PrettyTargetValue = Value.isZero() ? "false" : "true"; 9134 else 9135 IntegerValue.toString(PrettyTargetValue); 9136 9137 if (PruneWarnings) { 9138 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9139 S.PDiag(DiagID) 9140 << E->getType() << T.getUnqualifiedType() 9141 << PrettySourceValue << PrettyTargetValue 9142 << E->getSourceRange() << SourceRange(CContext)); 9143 } else { 9144 S.Diag(E->getExprLoc(), DiagID) 9145 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 9146 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 9147 } 9148 } 9149 9150 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 9151 if (!Range.Width) return "0"; 9152 9153 llvm::APSInt ValueInRange = Value; 9154 ValueInRange.setIsSigned(!Range.NonNegative); 9155 ValueInRange = ValueInRange.trunc(Range.Width); 9156 return ValueInRange.toString(10); 9157 } 9158 9159 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 9160 if (!isa<ImplicitCastExpr>(Ex)) 9161 return false; 9162 9163 Expr *InnerE = Ex->IgnoreParenImpCasts(); 9164 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 9165 const Type *Source = 9166 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 9167 if (Target->isDependentType()) 9168 return false; 9169 9170 const BuiltinType *FloatCandidateBT = 9171 dyn_cast<BuiltinType>(ToBool ? Source : Target); 9172 const Type *BoolCandidateType = ToBool ? Target : Source; 9173 9174 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 9175 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 9176 } 9177 9178 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 9179 SourceLocation CC) { 9180 unsigned NumArgs = TheCall->getNumArgs(); 9181 for (unsigned i = 0; i < NumArgs; ++i) { 9182 Expr *CurrA = TheCall->getArg(i); 9183 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 9184 continue; 9185 9186 bool IsSwapped = ((i > 0) && 9187 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 9188 IsSwapped |= ((i < (NumArgs - 1)) && 9189 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 9190 if (IsSwapped) { 9191 // Warn on this floating-point to bool conversion. 9192 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 9193 CurrA->getType(), CC, 9194 diag::warn_impcast_floating_point_to_bool); 9195 } 9196 } 9197 } 9198 9199 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) { 9200 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 9201 E->getExprLoc())) 9202 return; 9203 9204 // Don't warn on functions which have return type nullptr_t. 9205 if (isa<CallExpr>(E)) 9206 return; 9207 9208 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 9209 const Expr::NullPointerConstantKind NullKind = 9210 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 9211 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 9212 return; 9213 9214 // Return if target type is a safe conversion. 9215 if (T->isAnyPointerType() || T->isBlockPointerType() || 9216 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 9217 return; 9218 9219 SourceLocation Loc = E->getSourceRange().getBegin(); 9220 9221 // Venture through the macro stacks to get to the source of macro arguments. 9222 // The new location is a better location than the complete location that was 9223 // passed in. 9224 while (S.SourceMgr.isMacroArgExpansion(Loc)) 9225 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); 9226 9227 while (S.SourceMgr.isMacroArgExpansion(CC)) 9228 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); 9229 9230 // __null is usually wrapped in a macro. Go up a macro if that is the case. 9231 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 9232 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 9233 Loc, S.SourceMgr, S.getLangOpts()); 9234 if (MacroName == "NULL") 9235 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 9236 } 9237 9238 // Only warn if the null and context location are in the same macro expansion. 9239 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 9240 return; 9241 9242 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 9243 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) 9244 << FixItHint::CreateReplacement(Loc, 9245 S.getFixItZeroLiteralForType(T, Loc)); 9246 } 9247 9248 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9249 ObjCArrayLiteral *ArrayLiteral); 9250 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9251 ObjCDictionaryLiteral *DictionaryLiteral); 9252 9253 /// Check a single element within a collection literal against the 9254 /// target element type. 9255 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, 9256 Expr *Element, unsigned ElementKind) { 9257 // Skip a bitcast to 'id' or qualified 'id'. 9258 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 9259 if (ICE->getCastKind() == CK_BitCast && 9260 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 9261 Element = ICE->getSubExpr(); 9262 } 9263 9264 QualType ElementType = Element->getType(); 9265 ExprResult ElementResult(Element); 9266 if (ElementType->getAs<ObjCObjectPointerType>() && 9267 S.CheckSingleAssignmentConstraints(TargetElementType, 9268 ElementResult, 9269 false, false) 9270 != Sema::Compatible) { 9271 S.Diag(Element->getLocStart(), 9272 diag::warn_objc_collection_literal_element) 9273 << ElementType << ElementKind << TargetElementType 9274 << Element->getSourceRange(); 9275 } 9276 9277 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 9278 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 9279 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 9280 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 9281 } 9282 9283 /// Check an Objective-C array literal being converted to the given 9284 /// target type. 9285 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9286 ObjCArrayLiteral *ArrayLiteral) { 9287 if (!S.NSArrayDecl) 9288 return; 9289 9290 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9291 if (!TargetObjCPtr) 9292 return; 9293 9294 if (TargetObjCPtr->isUnspecialized() || 9295 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9296 != S.NSArrayDecl->getCanonicalDecl()) 9297 return; 9298 9299 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9300 if (TypeArgs.size() != 1) 9301 return; 9302 9303 QualType TargetElementType = TypeArgs[0]; 9304 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 9305 checkObjCCollectionLiteralElement(S, TargetElementType, 9306 ArrayLiteral->getElement(I), 9307 0); 9308 } 9309 } 9310 9311 /// Check an Objective-C dictionary literal being converted to the given 9312 /// target type. 9313 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9314 ObjCDictionaryLiteral *DictionaryLiteral) { 9315 if (!S.NSDictionaryDecl) 9316 return; 9317 9318 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9319 if (!TargetObjCPtr) 9320 return; 9321 9322 if (TargetObjCPtr->isUnspecialized() || 9323 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9324 != S.NSDictionaryDecl->getCanonicalDecl()) 9325 return; 9326 9327 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9328 if (TypeArgs.size() != 2) 9329 return; 9330 9331 QualType TargetKeyType = TypeArgs[0]; 9332 QualType TargetObjectType = TypeArgs[1]; 9333 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 9334 auto Element = DictionaryLiteral->getKeyValueElement(I); 9335 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 9336 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 9337 } 9338 } 9339 9340 // Helper function to filter out cases for constant width constant conversion. 9341 // Don't warn on char array initialization or for non-decimal values. 9342 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 9343 SourceLocation CC) { 9344 // If initializing from a constant, and the constant starts with '0', 9345 // then it is a binary, octal, or hexadecimal. Allow these constants 9346 // to fill all the bits, even if there is a sign change. 9347 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 9348 const char FirstLiteralCharacter = 9349 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 9350 if (FirstLiteralCharacter == '0') 9351 return false; 9352 } 9353 9354 // If the CC location points to a '{', and the type is char, then assume 9355 // assume it is an array initialization. 9356 if (CC.isValid() && T->isCharType()) { 9357 const char FirstContextCharacter = 9358 S.getSourceManager().getCharacterData(CC)[0]; 9359 if (FirstContextCharacter == '{') 9360 return false; 9361 } 9362 9363 return true; 9364 } 9365 9366 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 9367 SourceLocation CC, bool *ICContext = nullptr) { 9368 if (E->isTypeDependent() || E->isValueDependent()) return; 9369 9370 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 9371 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 9372 if (Source == Target) return; 9373 if (Target->isDependentType()) return; 9374 9375 // If the conversion context location is invalid don't complain. We also 9376 // don't want to emit a warning if the issue occurs from the expansion of 9377 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 9378 // delay this check as long as possible. Once we detect we are in that 9379 // scenario, we just return. 9380 if (CC.isInvalid()) 9381 return; 9382 9383 // Diagnose implicit casts to bool. 9384 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 9385 if (isa<StringLiteral>(E)) 9386 // Warn on string literal to bool. Checks for string literals in logical 9387 // and expressions, for instance, assert(0 && "error here"), are 9388 // prevented by a check in AnalyzeImplicitConversions(). 9389 return DiagnoseImpCast(S, E, T, CC, 9390 diag::warn_impcast_string_literal_to_bool); 9391 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 9392 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 9393 // This covers the literal expressions that evaluate to Objective-C 9394 // objects. 9395 return DiagnoseImpCast(S, E, T, CC, 9396 diag::warn_impcast_objective_c_literal_to_bool); 9397 } 9398 if (Source->isPointerType() || Source->canDecayToPointerType()) { 9399 // Warn on pointer to bool conversion that is always true. 9400 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 9401 SourceRange(CC)); 9402 } 9403 } 9404 9405 // Check implicit casts from Objective-C collection literals to specialized 9406 // collection types, e.g., NSArray<NSString *> *. 9407 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 9408 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 9409 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 9410 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 9411 9412 // Strip vector types. 9413 if (isa<VectorType>(Source)) { 9414 if (!isa<VectorType>(Target)) { 9415 if (S.SourceMgr.isInSystemMacro(CC)) 9416 return; 9417 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 9418 } 9419 9420 // If the vector cast is cast between two vectors of the same size, it is 9421 // a bitcast, not a conversion. 9422 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 9423 return; 9424 9425 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 9426 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 9427 } 9428 if (auto VecTy = dyn_cast<VectorType>(Target)) 9429 Target = VecTy->getElementType().getTypePtr(); 9430 9431 // Strip complex types. 9432 if (isa<ComplexType>(Source)) { 9433 if (!isa<ComplexType>(Target)) { 9434 if (S.SourceMgr.isInSystemMacro(CC)) 9435 return; 9436 9437 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 9438 } 9439 9440 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 9441 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 9442 } 9443 9444 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 9445 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 9446 9447 // If the source is floating point... 9448 if (SourceBT && SourceBT->isFloatingPoint()) { 9449 // ...and the target is floating point... 9450 if (TargetBT && TargetBT->isFloatingPoint()) { 9451 // ...then warn if we're dropping FP rank. 9452 9453 // Builtin FP kinds are ordered by increasing FP rank. 9454 if (SourceBT->getKind() > TargetBT->getKind()) { 9455 // Don't warn about float constants that are precisely 9456 // representable in the target type. 9457 Expr::EvalResult result; 9458 if (E->EvaluateAsRValue(result, S.Context)) { 9459 // Value might be a float, a float vector, or a float complex. 9460 if (IsSameFloatAfterCast(result.Val, 9461 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 9462 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 9463 return; 9464 } 9465 9466 if (S.SourceMgr.isInSystemMacro(CC)) 9467 return; 9468 9469 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 9470 } 9471 // ... or possibly if we're increasing rank, too 9472 else if (TargetBT->getKind() > SourceBT->getKind()) { 9473 if (S.SourceMgr.isInSystemMacro(CC)) 9474 return; 9475 9476 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 9477 } 9478 return; 9479 } 9480 9481 // If the target is integral, always warn. 9482 if (TargetBT && TargetBT->isInteger()) { 9483 if (S.SourceMgr.isInSystemMacro(CC)) 9484 return; 9485 9486 DiagnoseFloatingImpCast(S, E, T, CC); 9487 } 9488 9489 // Detect the case where a call result is converted from floating-point to 9490 // to bool, and the final argument to the call is converted from bool, to 9491 // discover this typo: 9492 // 9493 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 9494 // 9495 // FIXME: This is an incredibly special case; is there some more general 9496 // way to detect this class of misplaced-parentheses bug? 9497 if (Target->isBooleanType() && isa<CallExpr>(E)) { 9498 // Check last argument of function call to see if it is an 9499 // implicit cast from a type matching the type the result 9500 // is being cast to. 9501 CallExpr *CEx = cast<CallExpr>(E); 9502 if (unsigned NumArgs = CEx->getNumArgs()) { 9503 Expr *LastA = CEx->getArg(NumArgs - 1); 9504 Expr *InnerE = LastA->IgnoreParenImpCasts(); 9505 if (isa<ImplicitCastExpr>(LastA) && 9506 InnerE->getType()->isBooleanType()) { 9507 // Warn on this floating-point to bool conversion 9508 DiagnoseImpCast(S, E, T, CC, 9509 diag::warn_impcast_floating_point_to_bool); 9510 } 9511 } 9512 } 9513 return; 9514 } 9515 9516 DiagnoseNullConversion(S, E, T, CC); 9517 9518 S.DiscardMisalignedMemberAddress(Target, E); 9519 9520 if (!Source->isIntegerType() || !Target->isIntegerType()) 9521 return; 9522 9523 // TODO: remove this early return once the false positives for constant->bool 9524 // in templates, macros, etc, are reduced or removed. 9525 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 9526 return; 9527 9528 IntRange SourceRange = GetExprRange(S.Context, E); 9529 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 9530 9531 if (SourceRange.Width > TargetRange.Width) { 9532 // If the source is a constant, use a default-on diagnostic. 9533 // TODO: this should happen for bitfield stores, too. 9534 llvm::APSInt Value(32); 9535 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 9536 if (S.SourceMgr.isInSystemMacro(CC)) 9537 return; 9538 9539 std::string PrettySourceValue = Value.toString(10); 9540 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9541 9542 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9543 S.PDiag(diag::warn_impcast_integer_precision_constant) 9544 << PrettySourceValue << PrettyTargetValue 9545 << E->getType() << T << E->getSourceRange() 9546 << clang::SourceRange(CC)); 9547 return; 9548 } 9549 9550 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 9551 if (S.SourceMgr.isInSystemMacro(CC)) 9552 return; 9553 9554 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 9555 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 9556 /* pruneControlFlow */ true); 9557 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 9558 } 9559 9560 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 9561 SourceRange.NonNegative && Source->isSignedIntegerType()) { 9562 // Warn when doing a signed to signed conversion, warn if the positive 9563 // source value is exactly the width of the target type, which will 9564 // cause a negative value to be stored. 9565 9566 llvm::APSInt Value; 9567 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 9568 !S.SourceMgr.isInSystemMacro(CC)) { 9569 if (isSameWidthConstantConversion(S, E, T, CC)) { 9570 std::string PrettySourceValue = Value.toString(10); 9571 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9572 9573 S.DiagRuntimeBehavior( 9574 E->getExprLoc(), E, 9575 S.PDiag(diag::warn_impcast_integer_precision_constant) 9576 << PrettySourceValue << PrettyTargetValue << E->getType() << T 9577 << E->getSourceRange() << clang::SourceRange(CC)); 9578 return; 9579 } 9580 } 9581 9582 // Fall through for non-constants to give a sign conversion warning. 9583 } 9584 9585 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 9586 (!TargetRange.NonNegative && SourceRange.NonNegative && 9587 SourceRange.Width == TargetRange.Width)) { 9588 if (S.SourceMgr.isInSystemMacro(CC)) 9589 return; 9590 9591 unsigned DiagID = diag::warn_impcast_integer_sign; 9592 9593 // Traditionally, gcc has warned about this under -Wsign-compare. 9594 // We also want to warn about it in -Wconversion. 9595 // So if -Wconversion is off, use a completely identical diagnostic 9596 // in the sign-compare group. 9597 // The conditional-checking code will 9598 if (ICContext) { 9599 DiagID = diag::warn_impcast_integer_sign_conditional; 9600 *ICContext = true; 9601 } 9602 9603 return DiagnoseImpCast(S, E, T, CC, DiagID); 9604 } 9605 9606 // Diagnose conversions between different enumeration types. 9607 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 9608 // type, to give us better diagnostics. 9609 QualType SourceType = E->getType(); 9610 if (!S.getLangOpts().CPlusPlus) { 9611 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9612 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 9613 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 9614 SourceType = S.Context.getTypeDeclType(Enum); 9615 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 9616 } 9617 } 9618 9619 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 9620 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 9621 if (SourceEnum->getDecl()->hasNameForLinkage() && 9622 TargetEnum->getDecl()->hasNameForLinkage() && 9623 SourceEnum != TargetEnum) { 9624 if (S.SourceMgr.isInSystemMacro(CC)) 9625 return; 9626 9627 return DiagnoseImpCast(S, E, SourceType, T, CC, 9628 diag::warn_impcast_different_enum_types); 9629 } 9630 } 9631 9632 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9633 SourceLocation CC, QualType T); 9634 9635 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 9636 SourceLocation CC, bool &ICContext) { 9637 E = E->IgnoreParenImpCasts(); 9638 9639 if (isa<ConditionalOperator>(E)) 9640 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 9641 9642 AnalyzeImplicitConversions(S, E, CC); 9643 if (E->getType() != T) 9644 return CheckImplicitConversion(S, E, T, CC, &ICContext); 9645 } 9646 9647 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9648 SourceLocation CC, QualType T) { 9649 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 9650 9651 bool Suspicious = false; 9652 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 9653 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 9654 9655 // If -Wconversion would have warned about either of the candidates 9656 // for a signedness conversion to the context type... 9657 if (!Suspicious) return; 9658 9659 // ...but it's currently ignored... 9660 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 9661 return; 9662 9663 // ...then check whether it would have warned about either of the 9664 // candidates for a signedness conversion to the condition type. 9665 if (E->getType() == T) return; 9666 9667 Suspicious = false; 9668 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 9669 E->getType(), CC, &Suspicious); 9670 if (!Suspicious) 9671 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 9672 E->getType(), CC, &Suspicious); 9673 } 9674 9675 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9676 /// Input argument E is a logical expression. 9677 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 9678 if (S.getLangOpts().Bool) 9679 return; 9680 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 9681 } 9682 9683 /// AnalyzeImplicitConversions - Find and report any interesting 9684 /// implicit conversions in the given expression. There are a couple 9685 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 9686 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 9687 QualType T = OrigE->getType(); 9688 Expr *E = OrigE->IgnoreParenImpCasts(); 9689 9690 if (E->isTypeDependent() || E->isValueDependent()) 9691 return; 9692 9693 // For conditional operators, we analyze the arguments as if they 9694 // were being fed directly into the output. 9695 if (isa<ConditionalOperator>(E)) { 9696 ConditionalOperator *CO = cast<ConditionalOperator>(E); 9697 CheckConditionalOperator(S, CO, CC, T); 9698 return; 9699 } 9700 9701 // Check implicit argument conversions for function calls. 9702 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 9703 CheckImplicitArgumentConversions(S, Call, CC); 9704 9705 // Go ahead and check any implicit conversions we might have skipped. 9706 // The non-canonical typecheck is just an optimization; 9707 // CheckImplicitConversion will filter out dead implicit conversions. 9708 if (E->getType() != T) 9709 CheckImplicitConversion(S, E, T, CC); 9710 9711 // Now continue drilling into this expression. 9712 9713 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 9714 // The bound subexpressions in a PseudoObjectExpr are not reachable 9715 // as transitive children. 9716 // FIXME: Use a more uniform representation for this. 9717 for (auto *SE : POE->semantics()) 9718 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 9719 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 9720 } 9721 9722 // Skip past explicit casts. 9723 if (isa<ExplicitCastExpr>(E)) { 9724 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 9725 return AnalyzeImplicitConversions(S, E, CC); 9726 } 9727 9728 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9729 // Do a somewhat different check with comparison operators. 9730 if (BO->isComparisonOp()) 9731 return AnalyzeComparison(S, BO); 9732 9733 // And with simple assignments. 9734 if (BO->getOpcode() == BO_Assign) 9735 return AnalyzeAssignment(S, BO); 9736 } 9737 9738 // These break the otherwise-useful invariant below. Fortunately, 9739 // we don't really need to recurse into them, because any internal 9740 // expressions should have been analyzed already when they were 9741 // built into statements. 9742 if (isa<StmtExpr>(E)) return; 9743 9744 // Don't descend into unevaluated contexts. 9745 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 9746 9747 // Now just recurse over the expression's children. 9748 CC = E->getExprLoc(); 9749 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 9750 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 9751 for (Stmt *SubStmt : E->children()) { 9752 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 9753 if (!ChildExpr) 9754 continue; 9755 9756 if (IsLogicalAndOperator && 9757 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 9758 // Ignore checking string literals that are in logical and operators. 9759 // This is a common pattern for asserts. 9760 continue; 9761 AnalyzeImplicitConversions(S, ChildExpr, CC); 9762 } 9763 9764 if (BO && BO->isLogicalOp()) { 9765 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 9766 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9767 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9768 9769 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 9770 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9771 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9772 } 9773 9774 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 9775 if (U->getOpcode() == UO_LNot) 9776 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 9777 } 9778 9779 } // end anonymous namespace 9780 9781 /// Diagnose integer type and any valid implicit convertion to it. 9782 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 9783 // Taking into account implicit conversions, 9784 // allow any integer. 9785 if (!E->getType()->isIntegerType()) { 9786 S.Diag(E->getLocStart(), 9787 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 9788 return true; 9789 } 9790 // Potentially emit standard warnings for implicit conversions if enabled 9791 // using -Wconversion. 9792 CheckImplicitConversion(S, E, IntT, E->getLocStart()); 9793 return false; 9794 } 9795 9796 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 9797 // Returns true when emitting a warning about taking the address of a reference. 9798 static bool CheckForReference(Sema &SemaRef, const Expr *E, 9799 const PartialDiagnostic &PD) { 9800 E = E->IgnoreParenImpCasts(); 9801 9802 const FunctionDecl *FD = nullptr; 9803 9804 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9805 if (!DRE->getDecl()->getType()->isReferenceType()) 9806 return false; 9807 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9808 if (!M->getMemberDecl()->getType()->isReferenceType()) 9809 return false; 9810 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 9811 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 9812 return false; 9813 FD = Call->getDirectCallee(); 9814 } else { 9815 return false; 9816 } 9817 9818 SemaRef.Diag(E->getExprLoc(), PD); 9819 9820 // If possible, point to location of function. 9821 if (FD) { 9822 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 9823 } 9824 9825 return true; 9826 } 9827 9828 // Returns true if the SourceLocation is expanded from any macro body. 9829 // Returns false if the SourceLocation is invalid, is from not in a macro 9830 // expansion, or is from expanded from a top-level macro argument. 9831 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 9832 if (Loc.isInvalid()) 9833 return false; 9834 9835 while (Loc.isMacroID()) { 9836 if (SM.isMacroBodyExpansion(Loc)) 9837 return true; 9838 Loc = SM.getImmediateMacroCallerLoc(Loc); 9839 } 9840 9841 return false; 9842 } 9843 9844 /// \brief Diagnose pointers that are always non-null. 9845 /// \param E the expression containing the pointer 9846 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 9847 /// compared to a null pointer 9848 /// \param IsEqual True when the comparison is equal to a null pointer 9849 /// \param Range Extra SourceRange to highlight in the diagnostic 9850 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 9851 Expr::NullPointerConstantKind NullKind, 9852 bool IsEqual, SourceRange Range) { 9853 if (!E) 9854 return; 9855 9856 // Don't warn inside macros. 9857 if (E->getExprLoc().isMacroID()) { 9858 const SourceManager &SM = getSourceManager(); 9859 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 9860 IsInAnyMacroBody(SM, Range.getBegin())) 9861 return; 9862 } 9863 E = E->IgnoreImpCasts(); 9864 9865 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 9866 9867 if (isa<CXXThisExpr>(E)) { 9868 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 9869 : diag::warn_this_bool_conversion; 9870 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 9871 return; 9872 } 9873 9874 bool IsAddressOf = false; 9875 9876 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9877 if (UO->getOpcode() != UO_AddrOf) 9878 return; 9879 IsAddressOf = true; 9880 E = UO->getSubExpr(); 9881 } 9882 9883 if (IsAddressOf) { 9884 unsigned DiagID = IsCompare 9885 ? diag::warn_address_of_reference_null_compare 9886 : diag::warn_address_of_reference_bool_conversion; 9887 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 9888 << IsEqual; 9889 if (CheckForReference(*this, E, PD)) { 9890 return; 9891 } 9892 } 9893 9894 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 9895 bool IsParam = isa<NonNullAttr>(NonnullAttr); 9896 std::string Str; 9897 llvm::raw_string_ostream S(Str); 9898 E->printPretty(S, nullptr, getPrintingPolicy()); 9899 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 9900 : diag::warn_cast_nonnull_to_bool; 9901 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 9902 << E->getSourceRange() << Range << IsEqual; 9903 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 9904 }; 9905 9906 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 9907 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 9908 if (auto *Callee = Call->getDirectCallee()) { 9909 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 9910 ComplainAboutNonnullParamOrCall(A); 9911 return; 9912 } 9913 } 9914 } 9915 9916 // Expect to find a single Decl. Skip anything more complicated. 9917 ValueDecl *D = nullptr; 9918 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 9919 D = R->getDecl(); 9920 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9921 D = M->getMemberDecl(); 9922 } 9923 9924 // Weak Decls can be null. 9925 if (!D || D->isWeak()) 9926 return; 9927 9928 // Check for parameter decl with nonnull attribute 9929 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 9930 if (getCurFunction() && 9931 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 9932 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 9933 ComplainAboutNonnullParamOrCall(A); 9934 return; 9935 } 9936 9937 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 9938 auto ParamIter = llvm::find(FD->parameters(), PV); 9939 assert(ParamIter != FD->param_end()); 9940 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 9941 9942 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 9943 if (!NonNull->args_size()) { 9944 ComplainAboutNonnullParamOrCall(NonNull); 9945 return; 9946 } 9947 9948 for (unsigned ArgNo : NonNull->args()) { 9949 if (ArgNo == ParamNo) { 9950 ComplainAboutNonnullParamOrCall(NonNull); 9951 return; 9952 } 9953 } 9954 } 9955 } 9956 } 9957 } 9958 9959 QualType T = D->getType(); 9960 const bool IsArray = T->isArrayType(); 9961 const bool IsFunction = T->isFunctionType(); 9962 9963 // Address of function is used to silence the function warning. 9964 if (IsAddressOf && IsFunction) { 9965 return; 9966 } 9967 9968 // Found nothing. 9969 if (!IsAddressOf && !IsFunction && !IsArray) 9970 return; 9971 9972 // Pretty print the expression for the diagnostic. 9973 std::string Str; 9974 llvm::raw_string_ostream S(Str); 9975 E->printPretty(S, nullptr, getPrintingPolicy()); 9976 9977 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 9978 : diag::warn_impcast_pointer_to_bool; 9979 enum { 9980 AddressOf, 9981 FunctionPointer, 9982 ArrayPointer 9983 } DiagType; 9984 if (IsAddressOf) 9985 DiagType = AddressOf; 9986 else if (IsFunction) 9987 DiagType = FunctionPointer; 9988 else if (IsArray) 9989 DiagType = ArrayPointer; 9990 else 9991 llvm_unreachable("Could not determine diagnostic."); 9992 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 9993 << Range << IsEqual; 9994 9995 if (!IsFunction) 9996 return; 9997 9998 // Suggest '&' to silence the function warning. 9999 Diag(E->getExprLoc(), diag::note_function_warning_silence) 10000 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 10001 10002 // Check to see if '()' fixit should be emitted. 10003 QualType ReturnType; 10004 UnresolvedSet<4> NonTemplateOverloads; 10005 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 10006 if (ReturnType.isNull()) 10007 return; 10008 10009 if (IsCompare) { 10010 // There are two cases here. If there is null constant, the only suggest 10011 // for a pointer return type. If the null is 0, then suggest if the return 10012 // type is a pointer or an integer type. 10013 if (!ReturnType->isPointerType()) { 10014 if (NullKind == Expr::NPCK_ZeroExpression || 10015 NullKind == Expr::NPCK_ZeroLiteral) { 10016 if (!ReturnType->isIntegerType()) 10017 return; 10018 } else { 10019 return; 10020 } 10021 } 10022 } else { // !IsCompare 10023 // For function to bool, only suggest if the function pointer has bool 10024 // return type. 10025 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 10026 return; 10027 } 10028 Diag(E->getExprLoc(), diag::note_function_to_function_call) 10029 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 10030 } 10031 10032 /// Diagnoses "dangerous" implicit conversions within the given 10033 /// expression (which is a full expression). Implements -Wconversion 10034 /// and -Wsign-compare. 10035 /// 10036 /// \param CC the "context" location of the implicit conversion, i.e. 10037 /// the most location of the syntactic entity requiring the implicit 10038 /// conversion 10039 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 10040 // Don't diagnose in unevaluated contexts. 10041 if (isUnevaluatedContext()) 10042 return; 10043 10044 // Don't diagnose for value- or type-dependent expressions. 10045 if (E->isTypeDependent() || E->isValueDependent()) 10046 return; 10047 10048 // Check for array bounds violations in cases where the check isn't triggered 10049 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 10050 // ArraySubscriptExpr is on the RHS of a variable initialization. 10051 CheckArrayAccess(E); 10052 10053 // This is not the right CC for (e.g.) a variable initialization. 10054 AnalyzeImplicitConversions(*this, E, CC); 10055 } 10056 10057 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10058 /// Input argument E is a logical expression. 10059 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 10060 ::CheckBoolLikeConversion(*this, E, CC); 10061 } 10062 10063 /// Diagnose when expression is an integer constant expression and its evaluation 10064 /// results in integer overflow 10065 void Sema::CheckForIntOverflow (Expr *E) { 10066 // Use a work list to deal with nested struct initializers. 10067 SmallVector<Expr *, 2> Exprs(1, E); 10068 10069 do { 10070 Expr *E = Exprs.pop_back_val(); 10071 10072 if (isa<BinaryOperator>(E->IgnoreParenCasts())) { 10073 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 10074 continue; 10075 } 10076 10077 if (auto InitList = dyn_cast<InitListExpr>(E)) 10078 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 10079 10080 if (isa<ObjCBoxedExpr>(E)) 10081 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 10082 } while (!Exprs.empty()); 10083 } 10084 10085 namespace { 10086 /// \brief Visitor for expressions which looks for unsequenced operations on the 10087 /// same object. 10088 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 10089 typedef EvaluatedExprVisitor<SequenceChecker> Base; 10090 10091 /// \brief A tree of sequenced regions within an expression. Two regions are 10092 /// unsequenced if one is an ancestor or a descendent of the other. When we 10093 /// finish processing an expression with sequencing, such as a comma 10094 /// expression, we fold its tree nodes into its parent, since they are 10095 /// unsequenced with respect to nodes we will visit later. 10096 class SequenceTree { 10097 struct Value { 10098 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 10099 unsigned Parent : 31; 10100 unsigned Merged : 1; 10101 }; 10102 SmallVector<Value, 8> Values; 10103 10104 public: 10105 /// \brief A region within an expression which may be sequenced with respect 10106 /// to some other region. 10107 class Seq { 10108 explicit Seq(unsigned N) : Index(N) {} 10109 unsigned Index; 10110 friend class SequenceTree; 10111 public: 10112 Seq() : Index(0) {} 10113 }; 10114 10115 SequenceTree() { Values.push_back(Value(0)); } 10116 Seq root() const { return Seq(0); } 10117 10118 /// \brief Create a new sequence of operations, which is an unsequenced 10119 /// subset of \p Parent. This sequence of operations is sequenced with 10120 /// respect to other children of \p Parent. 10121 Seq allocate(Seq Parent) { 10122 Values.push_back(Value(Parent.Index)); 10123 return Seq(Values.size() - 1); 10124 } 10125 10126 /// \brief Merge a sequence of operations into its parent. 10127 void merge(Seq S) { 10128 Values[S.Index].Merged = true; 10129 } 10130 10131 /// \brief Determine whether two operations are unsequenced. This operation 10132 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 10133 /// should have been merged into its parent as appropriate. 10134 bool isUnsequenced(Seq Cur, Seq Old) { 10135 unsigned C = representative(Cur.Index); 10136 unsigned Target = representative(Old.Index); 10137 while (C >= Target) { 10138 if (C == Target) 10139 return true; 10140 C = Values[C].Parent; 10141 } 10142 return false; 10143 } 10144 10145 private: 10146 /// \brief Pick a representative for a sequence. 10147 unsigned representative(unsigned K) { 10148 if (Values[K].Merged) 10149 // Perform path compression as we go. 10150 return Values[K].Parent = representative(Values[K].Parent); 10151 return K; 10152 } 10153 }; 10154 10155 /// An object for which we can track unsequenced uses. 10156 typedef NamedDecl *Object; 10157 10158 /// Different flavors of object usage which we track. We only track the 10159 /// least-sequenced usage of each kind. 10160 enum UsageKind { 10161 /// A read of an object. Multiple unsequenced reads are OK. 10162 UK_Use, 10163 /// A modification of an object which is sequenced before the value 10164 /// computation of the expression, such as ++n in C++. 10165 UK_ModAsValue, 10166 /// A modification of an object which is not sequenced before the value 10167 /// computation of the expression, such as n++. 10168 UK_ModAsSideEffect, 10169 10170 UK_Count = UK_ModAsSideEffect + 1 10171 }; 10172 10173 struct Usage { 10174 Usage() : Use(nullptr), Seq() {} 10175 Expr *Use; 10176 SequenceTree::Seq Seq; 10177 }; 10178 10179 struct UsageInfo { 10180 UsageInfo() : Diagnosed(false) {} 10181 Usage Uses[UK_Count]; 10182 /// Have we issued a diagnostic for this variable already? 10183 bool Diagnosed; 10184 }; 10185 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 10186 10187 Sema &SemaRef; 10188 /// Sequenced regions within the expression. 10189 SequenceTree Tree; 10190 /// Declaration modifications and references which we have seen. 10191 UsageInfoMap UsageMap; 10192 /// The region we are currently within. 10193 SequenceTree::Seq Region; 10194 /// Filled in with declarations which were modified as a side-effect 10195 /// (that is, post-increment operations). 10196 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 10197 /// Expressions to check later. We defer checking these to reduce 10198 /// stack usage. 10199 SmallVectorImpl<Expr *> &WorkList; 10200 10201 /// RAII object wrapping the visitation of a sequenced subexpression of an 10202 /// expression. At the end of this process, the side-effects of the evaluation 10203 /// become sequenced with respect to the value computation of the result, so 10204 /// we downgrade any UK_ModAsSideEffect within the evaluation to 10205 /// UK_ModAsValue. 10206 struct SequencedSubexpression { 10207 SequencedSubexpression(SequenceChecker &Self) 10208 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 10209 Self.ModAsSideEffect = &ModAsSideEffect; 10210 } 10211 ~SequencedSubexpression() { 10212 for (auto &M : llvm::reverse(ModAsSideEffect)) { 10213 UsageInfo &U = Self.UsageMap[M.first]; 10214 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 10215 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 10216 SideEffectUsage = M.second; 10217 } 10218 Self.ModAsSideEffect = OldModAsSideEffect; 10219 } 10220 10221 SequenceChecker &Self; 10222 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 10223 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 10224 }; 10225 10226 /// RAII object wrapping the visitation of a subexpression which we might 10227 /// choose to evaluate as a constant. If any subexpression is evaluated and 10228 /// found to be non-constant, this allows us to suppress the evaluation of 10229 /// the outer expression. 10230 class EvaluationTracker { 10231 public: 10232 EvaluationTracker(SequenceChecker &Self) 10233 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 10234 Self.EvalTracker = this; 10235 } 10236 ~EvaluationTracker() { 10237 Self.EvalTracker = Prev; 10238 if (Prev) 10239 Prev->EvalOK &= EvalOK; 10240 } 10241 10242 bool evaluate(const Expr *E, bool &Result) { 10243 if (!EvalOK || E->isValueDependent()) 10244 return false; 10245 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 10246 return EvalOK; 10247 } 10248 10249 private: 10250 SequenceChecker &Self; 10251 EvaluationTracker *Prev; 10252 bool EvalOK; 10253 } *EvalTracker; 10254 10255 /// \brief Find the object which is produced by the specified expression, 10256 /// if any. 10257 Object getObject(Expr *E, bool Mod) const { 10258 E = E->IgnoreParenCasts(); 10259 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10260 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 10261 return getObject(UO->getSubExpr(), Mod); 10262 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10263 if (BO->getOpcode() == BO_Comma) 10264 return getObject(BO->getRHS(), Mod); 10265 if (Mod && BO->isAssignmentOp()) 10266 return getObject(BO->getLHS(), Mod); 10267 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10268 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 10269 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 10270 return ME->getMemberDecl(); 10271 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10272 // FIXME: If this is a reference, map through to its value. 10273 return DRE->getDecl(); 10274 return nullptr; 10275 } 10276 10277 /// \brief Note that an object was modified or used by an expression. 10278 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 10279 Usage &U = UI.Uses[UK]; 10280 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 10281 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 10282 ModAsSideEffect->push_back(std::make_pair(O, U)); 10283 U.Use = Ref; 10284 U.Seq = Region; 10285 } 10286 } 10287 /// \brief Check whether a modification or use conflicts with a prior usage. 10288 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 10289 bool IsModMod) { 10290 if (UI.Diagnosed) 10291 return; 10292 10293 const Usage &U = UI.Uses[OtherKind]; 10294 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 10295 return; 10296 10297 Expr *Mod = U.Use; 10298 Expr *ModOrUse = Ref; 10299 if (OtherKind == UK_Use) 10300 std::swap(Mod, ModOrUse); 10301 10302 SemaRef.Diag(Mod->getExprLoc(), 10303 IsModMod ? diag::warn_unsequenced_mod_mod 10304 : diag::warn_unsequenced_mod_use) 10305 << O << SourceRange(ModOrUse->getExprLoc()); 10306 UI.Diagnosed = true; 10307 } 10308 10309 void notePreUse(Object O, Expr *Use) { 10310 UsageInfo &U = UsageMap[O]; 10311 // Uses conflict with other modifications. 10312 checkUsage(O, U, Use, UK_ModAsValue, false); 10313 } 10314 void notePostUse(Object O, Expr *Use) { 10315 UsageInfo &U = UsageMap[O]; 10316 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 10317 addUsage(U, O, Use, UK_Use); 10318 } 10319 10320 void notePreMod(Object O, Expr *Mod) { 10321 UsageInfo &U = UsageMap[O]; 10322 // Modifications conflict with other modifications and with uses. 10323 checkUsage(O, U, Mod, UK_ModAsValue, true); 10324 checkUsage(O, U, Mod, UK_Use, false); 10325 } 10326 void notePostMod(Object O, Expr *Use, UsageKind UK) { 10327 UsageInfo &U = UsageMap[O]; 10328 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 10329 addUsage(U, O, Use, UK); 10330 } 10331 10332 public: 10333 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 10334 : Base(S.Context), SemaRef(S), Region(Tree.root()), 10335 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 10336 Visit(E); 10337 } 10338 10339 void VisitStmt(Stmt *S) { 10340 // Skip all statements which aren't expressions for now. 10341 } 10342 10343 void VisitExpr(Expr *E) { 10344 // By default, just recurse to evaluated subexpressions. 10345 Base::VisitStmt(E); 10346 } 10347 10348 void VisitCastExpr(CastExpr *E) { 10349 Object O = Object(); 10350 if (E->getCastKind() == CK_LValueToRValue) 10351 O = getObject(E->getSubExpr(), false); 10352 10353 if (O) 10354 notePreUse(O, E); 10355 VisitExpr(E); 10356 if (O) 10357 notePostUse(O, E); 10358 } 10359 10360 void VisitBinComma(BinaryOperator *BO) { 10361 // C++11 [expr.comma]p1: 10362 // Every value computation and side effect associated with the left 10363 // expression is sequenced before every value computation and side 10364 // effect associated with the right expression. 10365 SequenceTree::Seq LHS = Tree.allocate(Region); 10366 SequenceTree::Seq RHS = Tree.allocate(Region); 10367 SequenceTree::Seq OldRegion = Region; 10368 10369 { 10370 SequencedSubexpression SeqLHS(*this); 10371 Region = LHS; 10372 Visit(BO->getLHS()); 10373 } 10374 10375 Region = RHS; 10376 Visit(BO->getRHS()); 10377 10378 Region = OldRegion; 10379 10380 // Forget that LHS and RHS are sequenced. They are both unsequenced 10381 // with respect to other stuff. 10382 Tree.merge(LHS); 10383 Tree.merge(RHS); 10384 } 10385 10386 void VisitBinAssign(BinaryOperator *BO) { 10387 // The modification is sequenced after the value computation of the LHS 10388 // and RHS, so check it before inspecting the operands and update the 10389 // map afterwards. 10390 Object O = getObject(BO->getLHS(), true); 10391 if (!O) 10392 return VisitExpr(BO); 10393 10394 notePreMod(O, BO); 10395 10396 // C++11 [expr.ass]p7: 10397 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 10398 // only once. 10399 // 10400 // Therefore, for a compound assignment operator, O is considered used 10401 // everywhere except within the evaluation of E1 itself. 10402 if (isa<CompoundAssignOperator>(BO)) 10403 notePreUse(O, BO); 10404 10405 Visit(BO->getLHS()); 10406 10407 if (isa<CompoundAssignOperator>(BO)) 10408 notePostUse(O, BO); 10409 10410 Visit(BO->getRHS()); 10411 10412 // C++11 [expr.ass]p1: 10413 // the assignment is sequenced [...] before the value computation of the 10414 // assignment expression. 10415 // C11 6.5.16/3 has no such rule. 10416 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10417 : UK_ModAsSideEffect); 10418 } 10419 10420 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 10421 VisitBinAssign(CAO); 10422 } 10423 10424 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10425 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10426 void VisitUnaryPreIncDec(UnaryOperator *UO) { 10427 Object O = getObject(UO->getSubExpr(), true); 10428 if (!O) 10429 return VisitExpr(UO); 10430 10431 notePreMod(O, UO); 10432 Visit(UO->getSubExpr()); 10433 // C++11 [expr.pre.incr]p1: 10434 // the expression ++x is equivalent to x+=1 10435 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10436 : UK_ModAsSideEffect); 10437 } 10438 10439 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10440 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10441 void VisitUnaryPostIncDec(UnaryOperator *UO) { 10442 Object O = getObject(UO->getSubExpr(), true); 10443 if (!O) 10444 return VisitExpr(UO); 10445 10446 notePreMod(O, UO); 10447 Visit(UO->getSubExpr()); 10448 notePostMod(O, UO, UK_ModAsSideEffect); 10449 } 10450 10451 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 10452 void VisitBinLOr(BinaryOperator *BO) { 10453 // The side-effects of the LHS of an '&&' are sequenced before the 10454 // value computation of the RHS, and hence before the value computation 10455 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 10456 // as if they were unconditionally sequenced. 10457 EvaluationTracker Eval(*this); 10458 { 10459 SequencedSubexpression Sequenced(*this); 10460 Visit(BO->getLHS()); 10461 } 10462 10463 bool Result; 10464 if (Eval.evaluate(BO->getLHS(), Result)) { 10465 if (!Result) 10466 Visit(BO->getRHS()); 10467 } else { 10468 // Check for unsequenced operations in the RHS, treating it as an 10469 // entirely separate evaluation. 10470 // 10471 // FIXME: If there are operations in the RHS which are unsequenced 10472 // with respect to operations outside the RHS, and those operations 10473 // are unconditionally evaluated, diagnose them. 10474 WorkList.push_back(BO->getRHS()); 10475 } 10476 } 10477 void VisitBinLAnd(BinaryOperator *BO) { 10478 EvaluationTracker Eval(*this); 10479 { 10480 SequencedSubexpression Sequenced(*this); 10481 Visit(BO->getLHS()); 10482 } 10483 10484 bool Result; 10485 if (Eval.evaluate(BO->getLHS(), Result)) { 10486 if (Result) 10487 Visit(BO->getRHS()); 10488 } else { 10489 WorkList.push_back(BO->getRHS()); 10490 } 10491 } 10492 10493 // Only visit the condition, unless we can be sure which subexpression will 10494 // be chosen. 10495 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 10496 EvaluationTracker Eval(*this); 10497 { 10498 SequencedSubexpression Sequenced(*this); 10499 Visit(CO->getCond()); 10500 } 10501 10502 bool Result; 10503 if (Eval.evaluate(CO->getCond(), Result)) 10504 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 10505 else { 10506 WorkList.push_back(CO->getTrueExpr()); 10507 WorkList.push_back(CO->getFalseExpr()); 10508 } 10509 } 10510 10511 void VisitCallExpr(CallExpr *CE) { 10512 // C++11 [intro.execution]p15: 10513 // When calling a function [...], every value computation and side effect 10514 // associated with any argument expression, or with the postfix expression 10515 // designating the called function, is sequenced before execution of every 10516 // expression or statement in the body of the function [and thus before 10517 // the value computation of its result]. 10518 SequencedSubexpression Sequenced(*this); 10519 Base::VisitCallExpr(CE); 10520 10521 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 10522 } 10523 10524 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 10525 // This is a call, so all subexpressions are sequenced before the result. 10526 SequencedSubexpression Sequenced(*this); 10527 10528 if (!CCE->isListInitialization()) 10529 return VisitExpr(CCE); 10530 10531 // In C++11, list initializations are sequenced. 10532 SmallVector<SequenceTree::Seq, 32> Elts; 10533 SequenceTree::Seq Parent = Region; 10534 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 10535 E = CCE->arg_end(); 10536 I != E; ++I) { 10537 Region = Tree.allocate(Parent); 10538 Elts.push_back(Region); 10539 Visit(*I); 10540 } 10541 10542 // Forget that the initializers are sequenced. 10543 Region = Parent; 10544 for (unsigned I = 0; I < Elts.size(); ++I) 10545 Tree.merge(Elts[I]); 10546 } 10547 10548 void VisitInitListExpr(InitListExpr *ILE) { 10549 if (!SemaRef.getLangOpts().CPlusPlus11) 10550 return VisitExpr(ILE); 10551 10552 // In C++11, list initializations are sequenced. 10553 SmallVector<SequenceTree::Seq, 32> Elts; 10554 SequenceTree::Seq Parent = Region; 10555 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 10556 Expr *E = ILE->getInit(I); 10557 if (!E) continue; 10558 Region = Tree.allocate(Parent); 10559 Elts.push_back(Region); 10560 Visit(E); 10561 } 10562 10563 // Forget that the initializers are sequenced. 10564 Region = Parent; 10565 for (unsigned I = 0; I < Elts.size(); ++I) 10566 Tree.merge(Elts[I]); 10567 } 10568 }; 10569 } // end anonymous namespace 10570 10571 void Sema::CheckUnsequencedOperations(Expr *E) { 10572 SmallVector<Expr *, 8> WorkList; 10573 WorkList.push_back(E); 10574 while (!WorkList.empty()) { 10575 Expr *Item = WorkList.pop_back_val(); 10576 SequenceChecker(*this, Item, WorkList); 10577 } 10578 } 10579 10580 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 10581 bool IsConstexpr) { 10582 CheckImplicitConversions(E, CheckLoc); 10583 if (!E->isInstantiationDependent()) 10584 CheckUnsequencedOperations(E); 10585 if (!IsConstexpr && !E->isValueDependent()) 10586 CheckForIntOverflow(E); 10587 DiagnoseMisalignedMembers(); 10588 } 10589 10590 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 10591 FieldDecl *BitField, 10592 Expr *Init) { 10593 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 10594 } 10595 10596 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 10597 SourceLocation Loc) { 10598 if (!PType->isVariablyModifiedType()) 10599 return; 10600 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 10601 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 10602 return; 10603 } 10604 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 10605 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 10606 return; 10607 } 10608 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 10609 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 10610 return; 10611 } 10612 10613 const ArrayType *AT = S.Context.getAsArrayType(PType); 10614 if (!AT) 10615 return; 10616 10617 if (AT->getSizeModifier() != ArrayType::Star) { 10618 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 10619 return; 10620 } 10621 10622 S.Diag(Loc, diag::err_array_star_in_function_definition); 10623 } 10624 10625 /// CheckParmsForFunctionDef - Check that the parameters of the given 10626 /// function are appropriate for the definition of a function. This 10627 /// takes care of any checks that cannot be performed on the 10628 /// declaration itself, e.g., that the types of each of the function 10629 /// parameters are complete. 10630 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 10631 bool CheckParameterNames) { 10632 bool HasInvalidParm = false; 10633 for (ParmVarDecl *Param : Parameters) { 10634 // C99 6.7.5.3p4: the parameters in a parameter type list in a 10635 // function declarator that is part of a function definition of 10636 // that function shall not have incomplete type. 10637 // 10638 // This is also C++ [dcl.fct]p6. 10639 if (!Param->isInvalidDecl() && 10640 RequireCompleteType(Param->getLocation(), Param->getType(), 10641 diag::err_typecheck_decl_incomplete_type)) { 10642 Param->setInvalidDecl(); 10643 HasInvalidParm = true; 10644 } 10645 10646 // C99 6.9.1p5: If the declarator includes a parameter type list, the 10647 // declaration of each parameter shall include an identifier. 10648 if (CheckParameterNames && 10649 Param->getIdentifier() == nullptr && 10650 !Param->isImplicit() && 10651 !getLangOpts().CPlusPlus) 10652 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10653 10654 // C99 6.7.5.3p12: 10655 // If the function declarator is not part of a definition of that 10656 // function, parameters may have incomplete type and may use the [*] 10657 // notation in their sequences of declarator specifiers to specify 10658 // variable length array types. 10659 QualType PType = Param->getOriginalType(); 10660 // FIXME: This diagnostic should point the '[*]' if source-location 10661 // information is added for it. 10662 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 10663 10664 // MSVC destroys objects passed by value in the callee. Therefore a 10665 // function definition which takes such a parameter must be able to call the 10666 // object's destructor. However, we don't perform any direct access check 10667 // on the dtor. 10668 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 10669 .getCXXABI() 10670 .areArgsDestroyedLeftToRightInCallee()) { 10671 if (!Param->isInvalidDecl()) { 10672 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 10673 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 10674 if (!ClassDecl->isInvalidDecl() && 10675 !ClassDecl->hasIrrelevantDestructor() && 10676 !ClassDecl->isDependentContext()) { 10677 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10678 MarkFunctionReferenced(Param->getLocation(), Destructor); 10679 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 10680 } 10681 } 10682 } 10683 } 10684 10685 // Parameters with the pass_object_size attribute only need to be marked 10686 // constant at function definitions. Because we lack information about 10687 // whether we're on a declaration or definition when we're instantiating the 10688 // attribute, we need to check for constness here. 10689 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 10690 if (!Param->getType().isConstQualified()) 10691 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 10692 << Attr->getSpelling() << 1; 10693 } 10694 10695 return HasInvalidParm; 10696 } 10697 10698 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 10699 /// or MemberExpr. 10700 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 10701 ASTContext &Context) { 10702 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 10703 return Context.getDeclAlign(DRE->getDecl()); 10704 10705 if (const auto *ME = dyn_cast<MemberExpr>(E)) 10706 return Context.getDeclAlign(ME->getMemberDecl()); 10707 10708 return TypeAlign; 10709 } 10710 10711 /// CheckCastAlign - Implements -Wcast-align, which warns when a 10712 /// pointer cast increases the alignment requirements. 10713 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 10714 // This is actually a lot of work to potentially be doing on every 10715 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 10716 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 10717 return; 10718 10719 // Ignore dependent types. 10720 if (T->isDependentType() || Op->getType()->isDependentType()) 10721 return; 10722 10723 // Require that the destination be a pointer type. 10724 const PointerType *DestPtr = T->getAs<PointerType>(); 10725 if (!DestPtr) return; 10726 10727 // If the destination has alignment 1, we're done. 10728 QualType DestPointee = DestPtr->getPointeeType(); 10729 if (DestPointee->isIncompleteType()) return; 10730 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 10731 if (DestAlign.isOne()) return; 10732 10733 // Require that the source be a pointer type. 10734 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 10735 if (!SrcPtr) return; 10736 QualType SrcPointee = SrcPtr->getPointeeType(); 10737 10738 // Whitelist casts from cv void*. We already implicitly 10739 // whitelisted casts to cv void*, since they have alignment 1. 10740 // Also whitelist casts involving incomplete types, which implicitly 10741 // includes 'void'. 10742 if (SrcPointee->isIncompleteType()) return; 10743 10744 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 10745 10746 if (auto *CE = dyn_cast<CastExpr>(Op)) { 10747 if (CE->getCastKind() == CK_ArrayToPointerDecay) 10748 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 10749 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 10750 if (UO->getOpcode() == UO_AddrOf) 10751 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 10752 } 10753 10754 if (SrcAlign >= DestAlign) return; 10755 10756 Diag(TRange.getBegin(), diag::warn_cast_align) 10757 << Op->getType() << T 10758 << static_cast<unsigned>(SrcAlign.getQuantity()) 10759 << static_cast<unsigned>(DestAlign.getQuantity()) 10760 << TRange << Op->getSourceRange(); 10761 } 10762 10763 /// \brief Check whether this array fits the idiom of a size-one tail padded 10764 /// array member of a struct. 10765 /// 10766 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 10767 /// commonly used to emulate flexible arrays in C89 code. 10768 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 10769 const NamedDecl *ND) { 10770 if (Size != 1 || !ND) return false; 10771 10772 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 10773 if (!FD) return false; 10774 10775 // Don't consider sizes resulting from macro expansions or template argument 10776 // substitution to form C89 tail-padded arrays. 10777 10778 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 10779 while (TInfo) { 10780 TypeLoc TL = TInfo->getTypeLoc(); 10781 // Look through typedefs. 10782 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 10783 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 10784 TInfo = TDL->getTypeSourceInfo(); 10785 continue; 10786 } 10787 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 10788 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 10789 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 10790 return false; 10791 } 10792 break; 10793 } 10794 10795 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 10796 if (!RD) return false; 10797 if (RD->isUnion()) return false; 10798 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10799 if (!CRD->isStandardLayout()) return false; 10800 } 10801 10802 // See if this is the last field decl in the record. 10803 const Decl *D = FD; 10804 while ((D = D->getNextDeclInContext())) 10805 if (isa<FieldDecl>(D)) 10806 return false; 10807 return true; 10808 } 10809 10810 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 10811 const ArraySubscriptExpr *ASE, 10812 bool AllowOnePastEnd, bool IndexNegated) { 10813 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 10814 if (IndexExpr->isValueDependent()) 10815 return; 10816 10817 const Type *EffectiveType = 10818 BaseExpr->getType()->getPointeeOrArrayElementType(); 10819 BaseExpr = BaseExpr->IgnoreParenCasts(); 10820 const ConstantArrayType *ArrayTy = 10821 Context.getAsConstantArrayType(BaseExpr->getType()); 10822 if (!ArrayTy) 10823 return; 10824 10825 llvm::APSInt index; 10826 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 10827 return; 10828 if (IndexNegated) 10829 index = -index; 10830 10831 const NamedDecl *ND = nullptr; 10832 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10833 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10834 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10835 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10836 10837 if (index.isUnsigned() || !index.isNegative()) { 10838 llvm::APInt size = ArrayTy->getSize(); 10839 if (!size.isStrictlyPositive()) 10840 return; 10841 10842 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 10843 if (BaseType != EffectiveType) { 10844 // Make sure we're comparing apples to apples when comparing index to size 10845 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 10846 uint64_t array_typesize = Context.getTypeSize(BaseType); 10847 // Handle ptrarith_typesize being zero, such as when casting to void* 10848 if (!ptrarith_typesize) ptrarith_typesize = 1; 10849 if (ptrarith_typesize != array_typesize) { 10850 // There's a cast to a different size type involved 10851 uint64_t ratio = array_typesize / ptrarith_typesize; 10852 // TODO: Be smarter about handling cases where array_typesize is not a 10853 // multiple of ptrarith_typesize 10854 if (ptrarith_typesize * ratio == array_typesize) 10855 size *= llvm::APInt(size.getBitWidth(), ratio); 10856 } 10857 } 10858 10859 if (size.getBitWidth() > index.getBitWidth()) 10860 index = index.zext(size.getBitWidth()); 10861 else if (size.getBitWidth() < index.getBitWidth()) 10862 size = size.zext(index.getBitWidth()); 10863 10864 // For array subscripting the index must be less than size, but for pointer 10865 // arithmetic also allow the index (offset) to be equal to size since 10866 // computing the next address after the end of the array is legal and 10867 // commonly done e.g. in C++ iterators and range-based for loops. 10868 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 10869 return; 10870 10871 // Also don't warn for arrays of size 1 which are members of some 10872 // structure. These are often used to approximate flexible arrays in C89 10873 // code. 10874 if (IsTailPaddedMemberArray(*this, size, ND)) 10875 return; 10876 10877 // Suppress the warning if the subscript expression (as identified by the 10878 // ']' location) and the index expression are both from macro expansions 10879 // within a system header. 10880 if (ASE) { 10881 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 10882 ASE->getRBracketLoc()); 10883 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 10884 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 10885 IndexExpr->getLocStart()); 10886 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 10887 return; 10888 } 10889 } 10890 10891 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 10892 if (ASE) 10893 DiagID = diag::warn_array_index_exceeds_bounds; 10894 10895 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10896 PDiag(DiagID) << index.toString(10, true) 10897 << size.toString(10, true) 10898 << (unsigned)size.getLimitedValue(~0U) 10899 << IndexExpr->getSourceRange()); 10900 } else { 10901 unsigned DiagID = diag::warn_array_index_precedes_bounds; 10902 if (!ASE) { 10903 DiagID = diag::warn_ptr_arith_precedes_bounds; 10904 if (index.isNegative()) index = -index; 10905 } 10906 10907 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10908 PDiag(DiagID) << index.toString(10, true) 10909 << IndexExpr->getSourceRange()); 10910 } 10911 10912 if (!ND) { 10913 // Try harder to find a NamedDecl to point at in the note. 10914 while (const ArraySubscriptExpr *ASE = 10915 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 10916 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 10917 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10918 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10919 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10920 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10921 } 10922 10923 if (ND) 10924 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 10925 PDiag(diag::note_array_index_out_of_bounds) 10926 << ND->getDeclName()); 10927 } 10928 10929 void Sema::CheckArrayAccess(const Expr *expr) { 10930 int AllowOnePastEnd = 0; 10931 while (expr) { 10932 expr = expr->IgnoreParenImpCasts(); 10933 switch (expr->getStmtClass()) { 10934 case Stmt::ArraySubscriptExprClass: { 10935 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 10936 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 10937 AllowOnePastEnd > 0); 10938 return; 10939 } 10940 case Stmt::OMPArraySectionExprClass: { 10941 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 10942 if (ASE->getLowerBound()) 10943 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 10944 /*ASE=*/nullptr, AllowOnePastEnd > 0); 10945 return; 10946 } 10947 case Stmt::UnaryOperatorClass: { 10948 // Only unwrap the * and & unary operators 10949 const UnaryOperator *UO = cast<UnaryOperator>(expr); 10950 expr = UO->getSubExpr(); 10951 switch (UO->getOpcode()) { 10952 case UO_AddrOf: 10953 AllowOnePastEnd++; 10954 break; 10955 case UO_Deref: 10956 AllowOnePastEnd--; 10957 break; 10958 default: 10959 return; 10960 } 10961 break; 10962 } 10963 case Stmt::ConditionalOperatorClass: { 10964 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 10965 if (const Expr *lhs = cond->getLHS()) 10966 CheckArrayAccess(lhs); 10967 if (const Expr *rhs = cond->getRHS()) 10968 CheckArrayAccess(rhs); 10969 return; 10970 } 10971 case Stmt::CXXOperatorCallExprClass: { 10972 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 10973 for (const auto *Arg : OCE->arguments()) 10974 CheckArrayAccess(Arg); 10975 return; 10976 } 10977 default: 10978 return; 10979 } 10980 } 10981 } 10982 10983 //===--- CHECK: Objective-C retain cycles ----------------------------------// 10984 10985 namespace { 10986 struct RetainCycleOwner { 10987 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 10988 VarDecl *Variable; 10989 SourceRange Range; 10990 SourceLocation Loc; 10991 bool Indirect; 10992 10993 void setLocsFrom(Expr *e) { 10994 Loc = e->getExprLoc(); 10995 Range = e->getSourceRange(); 10996 } 10997 }; 10998 } // end anonymous namespace 10999 11000 /// Consider whether capturing the given variable can possibly lead to 11001 /// a retain cycle. 11002 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 11003 // In ARC, it's captured strongly iff the variable has __strong 11004 // lifetime. In MRR, it's captured strongly if the variable is 11005 // __block and has an appropriate type. 11006 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11007 return false; 11008 11009 owner.Variable = var; 11010 if (ref) 11011 owner.setLocsFrom(ref); 11012 return true; 11013 } 11014 11015 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 11016 while (true) { 11017 e = e->IgnoreParens(); 11018 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 11019 switch (cast->getCastKind()) { 11020 case CK_BitCast: 11021 case CK_LValueBitCast: 11022 case CK_LValueToRValue: 11023 case CK_ARCReclaimReturnedObject: 11024 e = cast->getSubExpr(); 11025 continue; 11026 11027 default: 11028 return false; 11029 } 11030 } 11031 11032 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 11033 ObjCIvarDecl *ivar = ref->getDecl(); 11034 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11035 return false; 11036 11037 // Try to find a retain cycle in the base. 11038 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 11039 return false; 11040 11041 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 11042 owner.Indirect = true; 11043 return true; 11044 } 11045 11046 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 11047 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 11048 if (!var) return false; 11049 return considerVariable(var, ref, owner); 11050 } 11051 11052 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 11053 if (member->isArrow()) return false; 11054 11055 // Don't count this as an indirect ownership. 11056 e = member->getBase(); 11057 continue; 11058 } 11059 11060 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 11061 // Only pay attention to pseudo-objects on property references. 11062 ObjCPropertyRefExpr *pre 11063 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 11064 ->IgnoreParens()); 11065 if (!pre) return false; 11066 if (pre->isImplicitProperty()) return false; 11067 ObjCPropertyDecl *property = pre->getExplicitProperty(); 11068 if (!property->isRetaining() && 11069 !(property->getPropertyIvarDecl() && 11070 property->getPropertyIvarDecl()->getType() 11071 .getObjCLifetime() == Qualifiers::OCL_Strong)) 11072 return false; 11073 11074 owner.Indirect = true; 11075 if (pre->isSuperReceiver()) { 11076 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 11077 if (!owner.Variable) 11078 return false; 11079 owner.Loc = pre->getLocation(); 11080 owner.Range = pre->getSourceRange(); 11081 return true; 11082 } 11083 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 11084 ->getSourceExpr()); 11085 continue; 11086 } 11087 11088 // Array ivars? 11089 11090 return false; 11091 } 11092 } 11093 11094 namespace { 11095 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 11096 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 11097 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 11098 Context(Context), Variable(variable), Capturer(nullptr), 11099 VarWillBeReased(false) {} 11100 ASTContext &Context; 11101 VarDecl *Variable; 11102 Expr *Capturer; 11103 bool VarWillBeReased; 11104 11105 void VisitDeclRefExpr(DeclRefExpr *ref) { 11106 if (ref->getDecl() == Variable && !Capturer) 11107 Capturer = ref; 11108 } 11109 11110 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 11111 if (Capturer) return; 11112 Visit(ref->getBase()); 11113 if (Capturer && ref->isFreeIvar()) 11114 Capturer = ref; 11115 } 11116 11117 void VisitBlockExpr(BlockExpr *block) { 11118 // Look inside nested blocks 11119 if (block->getBlockDecl()->capturesVariable(Variable)) 11120 Visit(block->getBlockDecl()->getBody()); 11121 } 11122 11123 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 11124 if (Capturer) return; 11125 if (OVE->getSourceExpr()) 11126 Visit(OVE->getSourceExpr()); 11127 } 11128 void VisitBinaryOperator(BinaryOperator *BinOp) { 11129 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 11130 return; 11131 Expr *LHS = BinOp->getLHS(); 11132 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 11133 if (DRE->getDecl() != Variable) 11134 return; 11135 if (Expr *RHS = BinOp->getRHS()) { 11136 RHS = RHS->IgnoreParenCasts(); 11137 llvm::APSInt Value; 11138 VarWillBeReased = 11139 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 11140 } 11141 } 11142 } 11143 }; 11144 } // end anonymous namespace 11145 11146 /// Check whether the given argument is a block which captures a 11147 /// variable. 11148 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 11149 assert(owner.Variable && owner.Loc.isValid()); 11150 11151 e = e->IgnoreParenCasts(); 11152 11153 // Look through [^{...} copy] and Block_copy(^{...}). 11154 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 11155 Selector Cmd = ME->getSelector(); 11156 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 11157 e = ME->getInstanceReceiver(); 11158 if (!e) 11159 return nullptr; 11160 e = e->IgnoreParenCasts(); 11161 } 11162 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 11163 if (CE->getNumArgs() == 1) { 11164 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 11165 if (Fn) { 11166 const IdentifierInfo *FnI = Fn->getIdentifier(); 11167 if (FnI && FnI->isStr("_Block_copy")) { 11168 e = CE->getArg(0)->IgnoreParenCasts(); 11169 } 11170 } 11171 } 11172 } 11173 11174 BlockExpr *block = dyn_cast<BlockExpr>(e); 11175 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 11176 return nullptr; 11177 11178 FindCaptureVisitor visitor(S.Context, owner.Variable); 11179 visitor.Visit(block->getBlockDecl()->getBody()); 11180 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 11181 } 11182 11183 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 11184 RetainCycleOwner &owner) { 11185 assert(capturer); 11186 assert(owner.Variable && owner.Loc.isValid()); 11187 11188 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 11189 << owner.Variable << capturer->getSourceRange(); 11190 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 11191 << owner.Indirect << owner.Range; 11192 } 11193 11194 /// Check for a keyword selector that starts with the word 'add' or 11195 /// 'set'. 11196 static bool isSetterLikeSelector(Selector sel) { 11197 if (sel.isUnarySelector()) return false; 11198 11199 StringRef str = sel.getNameForSlot(0); 11200 while (!str.empty() && str.front() == '_') str = str.substr(1); 11201 if (str.startswith("set")) 11202 str = str.substr(3); 11203 else if (str.startswith("add")) { 11204 // Specially whitelist 'addOperationWithBlock:'. 11205 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 11206 return false; 11207 str = str.substr(3); 11208 } 11209 else 11210 return false; 11211 11212 if (str.empty()) return true; 11213 return !isLowercase(str.front()); 11214 } 11215 11216 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 11217 ObjCMessageExpr *Message) { 11218 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 11219 Message->getReceiverInterface(), 11220 NSAPI::ClassId_NSMutableArray); 11221 if (!IsMutableArray) { 11222 return None; 11223 } 11224 11225 Selector Sel = Message->getSelector(); 11226 11227 Optional<NSAPI::NSArrayMethodKind> MKOpt = 11228 S.NSAPIObj->getNSArrayMethodKind(Sel); 11229 if (!MKOpt) { 11230 return None; 11231 } 11232 11233 NSAPI::NSArrayMethodKind MK = *MKOpt; 11234 11235 switch (MK) { 11236 case NSAPI::NSMutableArr_addObject: 11237 case NSAPI::NSMutableArr_insertObjectAtIndex: 11238 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 11239 return 0; 11240 case NSAPI::NSMutableArr_replaceObjectAtIndex: 11241 return 1; 11242 11243 default: 11244 return None; 11245 } 11246 11247 return None; 11248 } 11249 11250 static 11251 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 11252 ObjCMessageExpr *Message) { 11253 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 11254 Message->getReceiverInterface(), 11255 NSAPI::ClassId_NSMutableDictionary); 11256 if (!IsMutableDictionary) { 11257 return None; 11258 } 11259 11260 Selector Sel = Message->getSelector(); 11261 11262 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 11263 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 11264 if (!MKOpt) { 11265 return None; 11266 } 11267 11268 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 11269 11270 switch (MK) { 11271 case NSAPI::NSMutableDict_setObjectForKey: 11272 case NSAPI::NSMutableDict_setValueForKey: 11273 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 11274 return 0; 11275 11276 default: 11277 return None; 11278 } 11279 11280 return None; 11281 } 11282 11283 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 11284 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 11285 Message->getReceiverInterface(), 11286 NSAPI::ClassId_NSMutableSet); 11287 11288 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 11289 Message->getReceiverInterface(), 11290 NSAPI::ClassId_NSMutableOrderedSet); 11291 if (!IsMutableSet && !IsMutableOrderedSet) { 11292 return None; 11293 } 11294 11295 Selector Sel = Message->getSelector(); 11296 11297 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 11298 if (!MKOpt) { 11299 return None; 11300 } 11301 11302 NSAPI::NSSetMethodKind MK = *MKOpt; 11303 11304 switch (MK) { 11305 case NSAPI::NSMutableSet_addObject: 11306 case NSAPI::NSOrderedSet_setObjectAtIndex: 11307 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 11308 case NSAPI::NSOrderedSet_insertObjectAtIndex: 11309 return 0; 11310 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 11311 return 1; 11312 } 11313 11314 return None; 11315 } 11316 11317 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 11318 if (!Message->isInstanceMessage()) { 11319 return; 11320 } 11321 11322 Optional<int> ArgOpt; 11323 11324 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 11325 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 11326 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 11327 return; 11328 } 11329 11330 int ArgIndex = *ArgOpt; 11331 11332 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 11333 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 11334 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 11335 } 11336 11337 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 11338 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11339 if (ArgRE->isObjCSelfExpr()) { 11340 Diag(Message->getSourceRange().getBegin(), 11341 diag::warn_objc_circular_container) 11342 << ArgRE->getDecl()->getName() << StringRef("super"); 11343 } 11344 } 11345 } else { 11346 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 11347 11348 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 11349 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 11350 } 11351 11352 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 11353 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11354 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 11355 ValueDecl *Decl = ReceiverRE->getDecl(); 11356 Diag(Message->getSourceRange().getBegin(), 11357 diag::warn_objc_circular_container) 11358 << Decl->getName() << Decl->getName(); 11359 if (!ArgRE->isObjCSelfExpr()) { 11360 Diag(Decl->getLocation(), 11361 diag::note_objc_circular_container_declared_here) 11362 << Decl->getName(); 11363 } 11364 } 11365 } 11366 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 11367 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 11368 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 11369 ObjCIvarDecl *Decl = IvarRE->getDecl(); 11370 Diag(Message->getSourceRange().getBegin(), 11371 diag::warn_objc_circular_container) 11372 << Decl->getName() << Decl->getName(); 11373 Diag(Decl->getLocation(), 11374 diag::note_objc_circular_container_declared_here) 11375 << Decl->getName(); 11376 } 11377 } 11378 } 11379 } 11380 } 11381 11382 /// Check a message send to see if it's likely to cause a retain cycle. 11383 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 11384 // Only check instance methods whose selector looks like a setter. 11385 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 11386 return; 11387 11388 // Try to find a variable that the receiver is strongly owned by. 11389 RetainCycleOwner owner; 11390 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 11391 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 11392 return; 11393 } else { 11394 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 11395 owner.Variable = getCurMethodDecl()->getSelfDecl(); 11396 owner.Loc = msg->getSuperLoc(); 11397 owner.Range = msg->getSuperLoc(); 11398 } 11399 11400 // Check whether the receiver is captured by any of the arguments. 11401 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 11402 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 11403 return diagnoseRetainCycle(*this, capturer, owner); 11404 } 11405 11406 /// Check a property assign to see if it's likely to cause a retain cycle. 11407 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 11408 RetainCycleOwner owner; 11409 if (!findRetainCycleOwner(*this, receiver, owner)) 11410 return; 11411 11412 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 11413 diagnoseRetainCycle(*this, capturer, owner); 11414 } 11415 11416 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 11417 RetainCycleOwner Owner; 11418 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 11419 return; 11420 11421 // Because we don't have an expression for the variable, we have to set the 11422 // location explicitly here. 11423 Owner.Loc = Var->getLocation(); 11424 Owner.Range = Var->getSourceRange(); 11425 11426 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 11427 diagnoseRetainCycle(*this, Capturer, Owner); 11428 } 11429 11430 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 11431 Expr *RHS, bool isProperty) { 11432 // Check if RHS is an Objective-C object literal, which also can get 11433 // immediately zapped in a weak reference. Note that we explicitly 11434 // allow ObjCStringLiterals, since those are designed to never really die. 11435 RHS = RHS->IgnoreParenImpCasts(); 11436 11437 // This enum needs to match with the 'select' in 11438 // warn_objc_arc_literal_assign (off-by-1). 11439 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 11440 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 11441 return false; 11442 11443 S.Diag(Loc, diag::warn_arc_literal_assign) 11444 << (unsigned) Kind 11445 << (isProperty ? 0 : 1) 11446 << RHS->getSourceRange(); 11447 11448 return true; 11449 } 11450 11451 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 11452 Qualifiers::ObjCLifetime LT, 11453 Expr *RHS, bool isProperty) { 11454 // Strip off any implicit cast added to get to the one ARC-specific. 11455 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11456 if (cast->getCastKind() == CK_ARCConsumeObject) { 11457 S.Diag(Loc, diag::warn_arc_retained_assign) 11458 << (LT == Qualifiers::OCL_ExplicitNone) 11459 << (isProperty ? 0 : 1) 11460 << RHS->getSourceRange(); 11461 return true; 11462 } 11463 RHS = cast->getSubExpr(); 11464 } 11465 11466 if (LT == Qualifiers::OCL_Weak && 11467 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 11468 return true; 11469 11470 return false; 11471 } 11472 11473 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 11474 QualType LHS, Expr *RHS) { 11475 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 11476 11477 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 11478 return false; 11479 11480 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 11481 return true; 11482 11483 return false; 11484 } 11485 11486 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 11487 Expr *LHS, Expr *RHS) { 11488 QualType LHSType; 11489 // PropertyRef on LHS type need be directly obtained from 11490 // its declaration as it has a PseudoType. 11491 ObjCPropertyRefExpr *PRE 11492 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 11493 if (PRE && !PRE->isImplicitProperty()) { 11494 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11495 if (PD) 11496 LHSType = PD->getType(); 11497 } 11498 11499 if (LHSType.isNull()) 11500 LHSType = LHS->getType(); 11501 11502 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 11503 11504 if (LT == Qualifiers::OCL_Weak) { 11505 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 11506 getCurFunction()->markSafeWeakUse(LHS); 11507 } 11508 11509 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 11510 return; 11511 11512 // FIXME. Check for other life times. 11513 if (LT != Qualifiers::OCL_None) 11514 return; 11515 11516 if (PRE) { 11517 if (PRE->isImplicitProperty()) 11518 return; 11519 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11520 if (!PD) 11521 return; 11522 11523 unsigned Attributes = PD->getPropertyAttributes(); 11524 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 11525 // when 'assign' attribute was not explicitly specified 11526 // by user, ignore it and rely on property type itself 11527 // for lifetime info. 11528 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 11529 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 11530 LHSType->isObjCRetainableType()) 11531 return; 11532 11533 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11534 if (cast->getCastKind() == CK_ARCConsumeObject) { 11535 Diag(Loc, diag::warn_arc_retained_property_assign) 11536 << RHS->getSourceRange(); 11537 return; 11538 } 11539 RHS = cast->getSubExpr(); 11540 } 11541 } 11542 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 11543 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 11544 return; 11545 } 11546 } 11547 } 11548 11549 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 11550 11551 namespace { 11552 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 11553 SourceLocation StmtLoc, 11554 const NullStmt *Body) { 11555 // Do not warn if the body is a macro that expands to nothing, e.g: 11556 // 11557 // #define CALL(x) 11558 // if (condition) 11559 // CALL(0); 11560 // 11561 if (Body->hasLeadingEmptyMacro()) 11562 return false; 11563 11564 // Get line numbers of statement and body. 11565 bool StmtLineInvalid; 11566 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 11567 &StmtLineInvalid); 11568 if (StmtLineInvalid) 11569 return false; 11570 11571 bool BodyLineInvalid; 11572 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 11573 &BodyLineInvalid); 11574 if (BodyLineInvalid) 11575 return false; 11576 11577 // Warn if null statement and body are on the same line. 11578 if (StmtLine != BodyLine) 11579 return false; 11580 11581 return true; 11582 } 11583 } // end anonymous namespace 11584 11585 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 11586 const Stmt *Body, 11587 unsigned DiagID) { 11588 // Since this is a syntactic check, don't emit diagnostic for template 11589 // instantiations, this just adds noise. 11590 if (CurrentInstantiationScope) 11591 return; 11592 11593 // The body should be a null statement. 11594 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11595 if (!NBody) 11596 return; 11597 11598 // Do the usual checks. 11599 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11600 return; 11601 11602 Diag(NBody->getSemiLoc(), DiagID); 11603 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11604 } 11605 11606 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 11607 const Stmt *PossibleBody) { 11608 assert(!CurrentInstantiationScope); // Ensured by caller 11609 11610 SourceLocation StmtLoc; 11611 const Stmt *Body; 11612 unsigned DiagID; 11613 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 11614 StmtLoc = FS->getRParenLoc(); 11615 Body = FS->getBody(); 11616 DiagID = diag::warn_empty_for_body; 11617 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 11618 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 11619 Body = WS->getBody(); 11620 DiagID = diag::warn_empty_while_body; 11621 } else 11622 return; // Neither `for' nor `while'. 11623 11624 // The body should be a null statement. 11625 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11626 if (!NBody) 11627 return; 11628 11629 // Skip expensive checks if diagnostic is disabled. 11630 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 11631 return; 11632 11633 // Do the usual checks. 11634 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11635 return; 11636 11637 // `for(...);' and `while(...);' are popular idioms, so in order to keep 11638 // noise level low, emit diagnostics only if for/while is followed by a 11639 // CompoundStmt, e.g.: 11640 // for (int i = 0; i < n; i++); 11641 // { 11642 // a(i); 11643 // } 11644 // or if for/while is followed by a statement with more indentation 11645 // than for/while itself: 11646 // for (int i = 0; i < n; i++); 11647 // a(i); 11648 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 11649 if (!ProbableTypo) { 11650 bool BodyColInvalid; 11651 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 11652 PossibleBody->getLocStart(), 11653 &BodyColInvalid); 11654 if (BodyColInvalid) 11655 return; 11656 11657 bool StmtColInvalid; 11658 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 11659 S->getLocStart(), 11660 &StmtColInvalid); 11661 if (StmtColInvalid) 11662 return; 11663 11664 if (BodyCol > StmtCol) 11665 ProbableTypo = true; 11666 } 11667 11668 if (ProbableTypo) { 11669 Diag(NBody->getSemiLoc(), DiagID); 11670 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11671 } 11672 } 11673 11674 //===--- CHECK: Warn on self move with std::move. -------------------------===// 11675 11676 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 11677 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 11678 SourceLocation OpLoc) { 11679 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 11680 return; 11681 11682 if (inTemplateInstantiation()) 11683 return; 11684 11685 // Strip parens and casts away. 11686 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11687 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11688 11689 // Check for a call expression 11690 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 11691 if (!CE || CE->getNumArgs() != 1) 11692 return; 11693 11694 // Check for a call to std::move 11695 const FunctionDecl *FD = CE->getDirectCallee(); 11696 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() || 11697 !FD->getIdentifier()->isStr("move")) 11698 return; 11699 11700 // Get argument from std::move 11701 RHSExpr = CE->getArg(0); 11702 11703 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11704 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11705 11706 // Two DeclRefExpr's, check that the decls are the same. 11707 if (LHSDeclRef && RHSDeclRef) { 11708 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11709 return; 11710 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11711 RHSDeclRef->getDecl()->getCanonicalDecl()) 11712 return; 11713 11714 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11715 << LHSExpr->getSourceRange() 11716 << RHSExpr->getSourceRange(); 11717 return; 11718 } 11719 11720 // Member variables require a different approach to check for self moves. 11721 // MemberExpr's are the same if every nested MemberExpr refers to the same 11722 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 11723 // the base Expr's are CXXThisExpr's. 11724 const Expr *LHSBase = LHSExpr; 11725 const Expr *RHSBase = RHSExpr; 11726 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 11727 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 11728 if (!LHSME || !RHSME) 11729 return; 11730 11731 while (LHSME && RHSME) { 11732 if (LHSME->getMemberDecl()->getCanonicalDecl() != 11733 RHSME->getMemberDecl()->getCanonicalDecl()) 11734 return; 11735 11736 LHSBase = LHSME->getBase(); 11737 RHSBase = RHSME->getBase(); 11738 LHSME = dyn_cast<MemberExpr>(LHSBase); 11739 RHSME = dyn_cast<MemberExpr>(RHSBase); 11740 } 11741 11742 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 11743 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 11744 if (LHSDeclRef && RHSDeclRef) { 11745 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11746 return; 11747 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11748 RHSDeclRef->getDecl()->getCanonicalDecl()) 11749 return; 11750 11751 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11752 << LHSExpr->getSourceRange() 11753 << RHSExpr->getSourceRange(); 11754 return; 11755 } 11756 11757 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 11758 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11759 << LHSExpr->getSourceRange() 11760 << RHSExpr->getSourceRange(); 11761 } 11762 11763 //===--- Layout compatibility ----------------------------------------------// 11764 11765 namespace { 11766 11767 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 11768 11769 /// \brief Check if two enumeration types are layout-compatible. 11770 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 11771 // C++11 [dcl.enum] p8: 11772 // Two enumeration types are layout-compatible if they have the same 11773 // underlying type. 11774 return ED1->isComplete() && ED2->isComplete() && 11775 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 11776 } 11777 11778 /// \brief Check if two fields are layout-compatible. 11779 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 11780 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 11781 return false; 11782 11783 if (Field1->isBitField() != Field2->isBitField()) 11784 return false; 11785 11786 if (Field1->isBitField()) { 11787 // Make sure that the bit-fields are the same length. 11788 unsigned Bits1 = Field1->getBitWidthValue(C); 11789 unsigned Bits2 = Field2->getBitWidthValue(C); 11790 11791 if (Bits1 != Bits2) 11792 return false; 11793 } 11794 11795 return true; 11796 } 11797 11798 /// \brief Check if two standard-layout structs are layout-compatible. 11799 /// (C++11 [class.mem] p17) 11800 bool isLayoutCompatibleStruct(ASTContext &C, 11801 RecordDecl *RD1, 11802 RecordDecl *RD2) { 11803 // If both records are C++ classes, check that base classes match. 11804 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 11805 // If one of records is a CXXRecordDecl we are in C++ mode, 11806 // thus the other one is a CXXRecordDecl, too. 11807 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 11808 // Check number of base classes. 11809 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 11810 return false; 11811 11812 // Check the base classes. 11813 for (CXXRecordDecl::base_class_const_iterator 11814 Base1 = D1CXX->bases_begin(), 11815 BaseEnd1 = D1CXX->bases_end(), 11816 Base2 = D2CXX->bases_begin(); 11817 Base1 != BaseEnd1; 11818 ++Base1, ++Base2) { 11819 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 11820 return false; 11821 } 11822 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 11823 // If only RD2 is a C++ class, it should have zero base classes. 11824 if (D2CXX->getNumBases() > 0) 11825 return false; 11826 } 11827 11828 // Check the fields. 11829 RecordDecl::field_iterator Field2 = RD2->field_begin(), 11830 Field2End = RD2->field_end(), 11831 Field1 = RD1->field_begin(), 11832 Field1End = RD1->field_end(); 11833 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 11834 if (!isLayoutCompatible(C, *Field1, *Field2)) 11835 return false; 11836 } 11837 if (Field1 != Field1End || Field2 != Field2End) 11838 return false; 11839 11840 return true; 11841 } 11842 11843 /// \brief Check if two standard-layout unions are layout-compatible. 11844 /// (C++11 [class.mem] p18) 11845 bool isLayoutCompatibleUnion(ASTContext &C, 11846 RecordDecl *RD1, 11847 RecordDecl *RD2) { 11848 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 11849 for (auto *Field2 : RD2->fields()) 11850 UnmatchedFields.insert(Field2); 11851 11852 for (auto *Field1 : RD1->fields()) { 11853 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 11854 I = UnmatchedFields.begin(), 11855 E = UnmatchedFields.end(); 11856 11857 for ( ; I != E; ++I) { 11858 if (isLayoutCompatible(C, Field1, *I)) { 11859 bool Result = UnmatchedFields.erase(*I); 11860 (void) Result; 11861 assert(Result); 11862 break; 11863 } 11864 } 11865 if (I == E) 11866 return false; 11867 } 11868 11869 return UnmatchedFields.empty(); 11870 } 11871 11872 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 11873 if (RD1->isUnion() != RD2->isUnion()) 11874 return false; 11875 11876 if (RD1->isUnion()) 11877 return isLayoutCompatibleUnion(C, RD1, RD2); 11878 else 11879 return isLayoutCompatibleStruct(C, RD1, RD2); 11880 } 11881 11882 /// \brief Check if two types are layout-compatible in C++11 sense. 11883 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 11884 if (T1.isNull() || T2.isNull()) 11885 return false; 11886 11887 // C++11 [basic.types] p11: 11888 // If two types T1 and T2 are the same type, then T1 and T2 are 11889 // layout-compatible types. 11890 if (C.hasSameType(T1, T2)) 11891 return true; 11892 11893 T1 = T1.getCanonicalType().getUnqualifiedType(); 11894 T2 = T2.getCanonicalType().getUnqualifiedType(); 11895 11896 const Type::TypeClass TC1 = T1->getTypeClass(); 11897 const Type::TypeClass TC2 = T2->getTypeClass(); 11898 11899 if (TC1 != TC2) 11900 return false; 11901 11902 if (TC1 == Type::Enum) { 11903 return isLayoutCompatible(C, 11904 cast<EnumType>(T1)->getDecl(), 11905 cast<EnumType>(T2)->getDecl()); 11906 } else if (TC1 == Type::Record) { 11907 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 11908 return false; 11909 11910 return isLayoutCompatible(C, 11911 cast<RecordType>(T1)->getDecl(), 11912 cast<RecordType>(T2)->getDecl()); 11913 } 11914 11915 return false; 11916 } 11917 } // end anonymous namespace 11918 11919 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 11920 11921 namespace { 11922 /// \brief Given a type tag expression find the type tag itself. 11923 /// 11924 /// \param TypeExpr Type tag expression, as it appears in user's code. 11925 /// 11926 /// \param VD Declaration of an identifier that appears in a type tag. 11927 /// 11928 /// \param MagicValue Type tag magic value. 11929 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 11930 const ValueDecl **VD, uint64_t *MagicValue) { 11931 while(true) { 11932 if (!TypeExpr) 11933 return false; 11934 11935 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 11936 11937 switch (TypeExpr->getStmtClass()) { 11938 case Stmt::UnaryOperatorClass: { 11939 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 11940 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 11941 TypeExpr = UO->getSubExpr(); 11942 continue; 11943 } 11944 return false; 11945 } 11946 11947 case Stmt::DeclRefExprClass: { 11948 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 11949 *VD = DRE->getDecl(); 11950 return true; 11951 } 11952 11953 case Stmt::IntegerLiteralClass: { 11954 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 11955 llvm::APInt MagicValueAPInt = IL->getValue(); 11956 if (MagicValueAPInt.getActiveBits() <= 64) { 11957 *MagicValue = MagicValueAPInt.getZExtValue(); 11958 return true; 11959 } else 11960 return false; 11961 } 11962 11963 case Stmt::BinaryConditionalOperatorClass: 11964 case Stmt::ConditionalOperatorClass: { 11965 const AbstractConditionalOperator *ACO = 11966 cast<AbstractConditionalOperator>(TypeExpr); 11967 bool Result; 11968 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 11969 if (Result) 11970 TypeExpr = ACO->getTrueExpr(); 11971 else 11972 TypeExpr = ACO->getFalseExpr(); 11973 continue; 11974 } 11975 return false; 11976 } 11977 11978 case Stmt::BinaryOperatorClass: { 11979 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 11980 if (BO->getOpcode() == BO_Comma) { 11981 TypeExpr = BO->getRHS(); 11982 continue; 11983 } 11984 return false; 11985 } 11986 11987 default: 11988 return false; 11989 } 11990 } 11991 } 11992 11993 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 11994 /// 11995 /// \param TypeExpr Expression that specifies a type tag. 11996 /// 11997 /// \param MagicValues Registered magic values. 11998 /// 11999 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 12000 /// kind. 12001 /// 12002 /// \param TypeInfo Information about the corresponding C type. 12003 /// 12004 /// \returns true if the corresponding C type was found. 12005 bool GetMatchingCType( 12006 const IdentifierInfo *ArgumentKind, 12007 const Expr *TypeExpr, const ASTContext &Ctx, 12008 const llvm::DenseMap<Sema::TypeTagMagicValue, 12009 Sema::TypeTagData> *MagicValues, 12010 bool &FoundWrongKind, 12011 Sema::TypeTagData &TypeInfo) { 12012 FoundWrongKind = false; 12013 12014 // Variable declaration that has type_tag_for_datatype attribute. 12015 const ValueDecl *VD = nullptr; 12016 12017 uint64_t MagicValue; 12018 12019 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 12020 return false; 12021 12022 if (VD) { 12023 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 12024 if (I->getArgumentKind() != ArgumentKind) { 12025 FoundWrongKind = true; 12026 return false; 12027 } 12028 TypeInfo.Type = I->getMatchingCType(); 12029 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 12030 TypeInfo.MustBeNull = I->getMustBeNull(); 12031 return true; 12032 } 12033 return false; 12034 } 12035 12036 if (!MagicValues) 12037 return false; 12038 12039 llvm::DenseMap<Sema::TypeTagMagicValue, 12040 Sema::TypeTagData>::const_iterator I = 12041 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 12042 if (I == MagicValues->end()) 12043 return false; 12044 12045 TypeInfo = I->second; 12046 return true; 12047 } 12048 } // end anonymous namespace 12049 12050 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 12051 uint64_t MagicValue, QualType Type, 12052 bool LayoutCompatible, 12053 bool MustBeNull) { 12054 if (!TypeTagForDatatypeMagicValues) 12055 TypeTagForDatatypeMagicValues.reset( 12056 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 12057 12058 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 12059 (*TypeTagForDatatypeMagicValues)[Magic] = 12060 TypeTagData(Type, LayoutCompatible, MustBeNull); 12061 } 12062 12063 namespace { 12064 bool IsSameCharType(QualType T1, QualType T2) { 12065 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 12066 if (!BT1) 12067 return false; 12068 12069 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 12070 if (!BT2) 12071 return false; 12072 12073 BuiltinType::Kind T1Kind = BT1->getKind(); 12074 BuiltinType::Kind T2Kind = BT2->getKind(); 12075 12076 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 12077 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 12078 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 12079 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 12080 } 12081 } // end anonymous namespace 12082 12083 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 12084 const Expr * const *ExprArgs) { 12085 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 12086 bool IsPointerAttr = Attr->getIsPointer(); 12087 12088 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 12089 bool FoundWrongKind; 12090 TypeTagData TypeInfo; 12091 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 12092 TypeTagForDatatypeMagicValues.get(), 12093 FoundWrongKind, TypeInfo)) { 12094 if (FoundWrongKind) 12095 Diag(TypeTagExpr->getExprLoc(), 12096 diag::warn_type_tag_for_datatype_wrong_kind) 12097 << TypeTagExpr->getSourceRange(); 12098 return; 12099 } 12100 12101 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 12102 if (IsPointerAttr) { 12103 // Skip implicit cast of pointer to `void *' (as a function argument). 12104 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 12105 if (ICE->getType()->isVoidPointerType() && 12106 ICE->getCastKind() == CK_BitCast) 12107 ArgumentExpr = ICE->getSubExpr(); 12108 } 12109 QualType ArgumentType = ArgumentExpr->getType(); 12110 12111 // Passing a `void*' pointer shouldn't trigger a warning. 12112 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 12113 return; 12114 12115 if (TypeInfo.MustBeNull) { 12116 // Type tag with matching void type requires a null pointer. 12117 if (!ArgumentExpr->isNullPointerConstant(Context, 12118 Expr::NPC_ValueDependentIsNotNull)) { 12119 Diag(ArgumentExpr->getExprLoc(), 12120 diag::warn_type_safety_null_pointer_required) 12121 << ArgumentKind->getName() 12122 << ArgumentExpr->getSourceRange() 12123 << TypeTagExpr->getSourceRange(); 12124 } 12125 return; 12126 } 12127 12128 QualType RequiredType = TypeInfo.Type; 12129 if (IsPointerAttr) 12130 RequiredType = Context.getPointerType(RequiredType); 12131 12132 bool mismatch = false; 12133 if (!TypeInfo.LayoutCompatible) { 12134 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 12135 12136 // C++11 [basic.fundamental] p1: 12137 // Plain char, signed char, and unsigned char are three distinct types. 12138 // 12139 // But we treat plain `char' as equivalent to `signed char' or `unsigned 12140 // char' depending on the current char signedness mode. 12141 if (mismatch) 12142 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 12143 RequiredType->getPointeeType())) || 12144 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 12145 mismatch = false; 12146 } else 12147 if (IsPointerAttr) 12148 mismatch = !isLayoutCompatible(Context, 12149 ArgumentType->getPointeeType(), 12150 RequiredType->getPointeeType()); 12151 else 12152 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 12153 12154 if (mismatch) 12155 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 12156 << ArgumentType << ArgumentKind 12157 << TypeInfo.LayoutCompatible << RequiredType 12158 << ArgumentExpr->getSourceRange() 12159 << TypeTagExpr->getSourceRange(); 12160 } 12161 12162 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 12163 CharUnits Alignment) { 12164 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 12165 } 12166 12167 void Sema::DiagnoseMisalignedMembers() { 12168 for (MisalignedMember &m : MisalignedMembers) { 12169 const NamedDecl *ND = m.RD; 12170 if (ND->getName().empty()) { 12171 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 12172 ND = TD; 12173 } 12174 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 12175 << m.MD << ND << m.E->getSourceRange(); 12176 } 12177 MisalignedMembers.clear(); 12178 } 12179 12180 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 12181 E = E->IgnoreParens(); 12182 if (!T->isPointerType() && !T->isIntegerType()) 12183 return; 12184 if (isa<UnaryOperator>(E) && 12185 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 12186 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 12187 if (isa<MemberExpr>(Op)) { 12188 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 12189 MisalignedMember(Op)); 12190 if (MA != MisalignedMembers.end() && 12191 (T->isIntegerType() || 12192 (T->isPointerType() && 12193 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment))) 12194 MisalignedMembers.erase(MA); 12195 } 12196 } 12197 } 12198 12199 void Sema::RefersToMemberWithReducedAlignment( 12200 Expr *E, 12201 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 12202 Action) { 12203 const auto *ME = dyn_cast<MemberExpr>(E); 12204 if (!ME) 12205 return; 12206 12207 // No need to check expressions with an __unaligned-qualified type. 12208 if (E->getType().getQualifiers().hasUnaligned()) 12209 return; 12210 12211 // For a chain of MemberExpr like "a.b.c.d" this list 12212 // will keep FieldDecl's like [d, c, b]. 12213 SmallVector<FieldDecl *, 4> ReverseMemberChain; 12214 const MemberExpr *TopME = nullptr; 12215 bool AnyIsPacked = false; 12216 do { 12217 QualType BaseType = ME->getBase()->getType(); 12218 if (ME->isArrow()) 12219 BaseType = BaseType->getPointeeType(); 12220 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 12221 if (RD->isInvalidDecl()) 12222 return; 12223 12224 ValueDecl *MD = ME->getMemberDecl(); 12225 auto *FD = dyn_cast<FieldDecl>(MD); 12226 // We do not care about non-data members. 12227 if (!FD || FD->isInvalidDecl()) 12228 return; 12229 12230 AnyIsPacked = 12231 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 12232 ReverseMemberChain.push_back(FD); 12233 12234 TopME = ME; 12235 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 12236 } while (ME); 12237 assert(TopME && "We did not compute a topmost MemberExpr!"); 12238 12239 // Not the scope of this diagnostic. 12240 if (!AnyIsPacked) 12241 return; 12242 12243 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 12244 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 12245 // TODO: The innermost base of the member expression may be too complicated. 12246 // For now, just disregard these cases. This is left for future 12247 // improvement. 12248 if (!DRE && !isa<CXXThisExpr>(TopBase)) 12249 return; 12250 12251 // Alignment expected by the whole expression. 12252 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 12253 12254 // No need to do anything else with this case. 12255 if (ExpectedAlignment.isOne()) 12256 return; 12257 12258 // Synthesize offset of the whole access. 12259 CharUnits Offset; 12260 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 12261 I++) { 12262 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 12263 } 12264 12265 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 12266 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 12267 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 12268 12269 // The base expression of the innermost MemberExpr may give 12270 // stronger guarantees than the class containing the member. 12271 if (DRE && !TopME->isArrow()) { 12272 const ValueDecl *VD = DRE->getDecl(); 12273 if (!VD->getType()->isReferenceType()) 12274 CompleteObjectAlignment = 12275 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 12276 } 12277 12278 // Check if the synthesized offset fulfills the alignment. 12279 if (Offset % ExpectedAlignment != 0 || 12280 // It may fulfill the offset it but the effective alignment may still be 12281 // lower than the expected expression alignment. 12282 CompleteObjectAlignment < ExpectedAlignment) { 12283 // If this happens, we want to determine a sensible culprit of this. 12284 // Intuitively, watching the chain of member expressions from right to 12285 // left, we start with the required alignment (as required by the field 12286 // type) but some packed attribute in that chain has reduced the alignment. 12287 // It may happen that another packed structure increases it again. But if 12288 // we are here such increase has not been enough. So pointing the first 12289 // FieldDecl that either is packed or else its RecordDecl is, 12290 // seems reasonable. 12291 FieldDecl *FD = nullptr; 12292 CharUnits Alignment; 12293 for (FieldDecl *FDI : ReverseMemberChain) { 12294 if (FDI->hasAttr<PackedAttr>() || 12295 FDI->getParent()->hasAttr<PackedAttr>()) { 12296 FD = FDI; 12297 Alignment = std::min( 12298 Context.getTypeAlignInChars(FD->getType()), 12299 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 12300 break; 12301 } 12302 } 12303 assert(FD && "We did not find a packed FieldDecl!"); 12304 Action(E, FD->getParent(), FD, Alignment); 12305 } 12306 } 12307 12308 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 12309 using namespace std::placeholders; 12310 RefersToMemberWithReducedAlignment( 12311 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 12312 _2, _3, _4)); 12313 } 12314 12315