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 // Since return type of reserve_read/write_pipe built-in function is 687 // reserve_id_t, which is not defined in the builtin def file , we used int 688 // as return type and need to override the return type of these functions. 689 Call->setType(S.Context.OCLReserveIDTy); 690 691 return false; 692 } 693 694 // \brief Performs a semantic analysis on {work_group_/sub_group_ 695 // /_}commit_{read/write}_pipe 696 // \param S Reference to the semantic analyzer. 697 // \param Call The call to the builtin function to be analyzed. 698 // \return True if a semantic error was found, false otherwise. 699 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 700 if (checkArgCount(S, Call, 2)) 701 return true; 702 703 if (checkOpenCLPipeArg(S, Call)) 704 return true; 705 706 // Check reserve_id_t. 707 if (!Call->getArg(1)->getType()->isReserveIDT()) { 708 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 709 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 710 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 711 return true; 712 } 713 714 return false; 715 } 716 717 // \brief Performs a semantic analysis on the call to built-in Pipe 718 // Query Functions. 719 // \param S Reference to the semantic analyzer. 720 // \param Call The call to the builtin function to be analyzed. 721 // \return True if a semantic error was found, false otherwise. 722 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 723 if (checkArgCount(S, Call, 1)) 724 return true; 725 726 if (!Call->getArg(0)->getType()->isPipeType()) { 727 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 728 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 729 return true; 730 } 731 732 return false; 733 } 734 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions. 735 // \brief Performs semantic analysis for the to_global/local/private call. 736 // \param S Reference to the semantic analyzer. 737 // \param BuiltinID ID of the builtin function. 738 // \param Call A pointer to the builtin call. 739 // \return True if a semantic error has been found, false otherwise. 740 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 741 CallExpr *Call) { 742 if (Call->getNumArgs() != 1) { 743 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 744 << Call->getDirectCallee() << Call->getSourceRange(); 745 return true; 746 } 747 748 auto RT = Call->getArg(0)->getType(); 749 if (!RT->isPointerType() || RT->getPointeeType() 750 .getAddressSpace() == LangAS::opencl_constant) { 751 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 752 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 753 return true; 754 } 755 756 RT = RT->getPointeeType(); 757 auto Qual = RT.getQualifiers(); 758 switch (BuiltinID) { 759 case Builtin::BIto_global: 760 Qual.setAddressSpace(LangAS::opencl_global); 761 break; 762 case Builtin::BIto_local: 763 Qual.setAddressSpace(LangAS::opencl_local); 764 break; 765 default: 766 Qual.removeAddressSpace(); 767 } 768 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 769 RT.getUnqualifiedType(), Qual))); 770 771 return false; 772 } 773 774 ExprResult 775 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 776 CallExpr *TheCall) { 777 ExprResult TheCallResult(TheCall); 778 779 // Find out if any arguments are required to be integer constant expressions. 780 unsigned ICEArguments = 0; 781 ASTContext::GetBuiltinTypeError Error; 782 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 783 if (Error != ASTContext::GE_None) 784 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 785 786 // If any arguments are required to be ICE's, check and diagnose. 787 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 788 // Skip arguments not required to be ICE's. 789 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 790 791 llvm::APSInt Result; 792 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 793 return true; 794 ICEArguments &= ~(1 << ArgNo); 795 } 796 797 switch (BuiltinID) { 798 case Builtin::BI__builtin___CFStringMakeConstantString: 799 assert(TheCall->getNumArgs() == 1 && 800 "Wrong # arguments to builtin CFStringMakeConstantString"); 801 if (CheckObjCString(TheCall->getArg(0))) 802 return ExprError(); 803 break; 804 case Builtin::BI__builtin_ms_va_start: 805 case Builtin::BI__builtin_stdarg_start: 806 case Builtin::BI__builtin_va_start: 807 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 808 return ExprError(); 809 break; 810 case Builtin::BI__va_start: { 811 switch (Context.getTargetInfo().getTriple().getArch()) { 812 case llvm::Triple::arm: 813 case llvm::Triple::thumb: 814 if (SemaBuiltinVAStartARM(TheCall)) 815 return ExprError(); 816 break; 817 default: 818 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 819 return ExprError(); 820 break; 821 } 822 break; 823 } 824 case Builtin::BI__builtin_isgreater: 825 case Builtin::BI__builtin_isgreaterequal: 826 case Builtin::BI__builtin_isless: 827 case Builtin::BI__builtin_islessequal: 828 case Builtin::BI__builtin_islessgreater: 829 case Builtin::BI__builtin_isunordered: 830 if (SemaBuiltinUnorderedCompare(TheCall)) 831 return ExprError(); 832 break; 833 case Builtin::BI__builtin_fpclassify: 834 if (SemaBuiltinFPClassification(TheCall, 6)) 835 return ExprError(); 836 break; 837 case Builtin::BI__builtin_isfinite: 838 case Builtin::BI__builtin_isinf: 839 case Builtin::BI__builtin_isinf_sign: 840 case Builtin::BI__builtin_isnan: 841 case Builtin::BI__builtin_isnormal: 842 if (SemaBuiltinFPClassification(TheCall, 1)) 843 return ExprError(); 844 break; 845 case Builtin::BI__builtin_shufflevector: 846 return SemaBuiltinShuffleVector(TheCall); 847 // TheCall will be freed by the smart pointer here, but that's fine, since 848 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 849 case Builtin::BI__builtin_prefetch: 850 if (SemaBuiltinPrefetch(TheCall)) 851 return ExprError(); 852 break; 853 case Builtin::BI__builtin_alloca_with_align: 854 if (SemaBuiltinAllocaWithAlign(TheCall)) 855 return ExprError(); 856 break; 857 case Builtin::BI__assume: 858 case Builtin::BI__builtin_assume: 859 if (SemaBuiltinAssume(TheCall)) 860 return ExprError(); 861 break; 862 case Builtin::BI__builtin_assume_aligned: 863 if (SemaBuiltinAssumeAligned(TheCall)) 864 return ExprError(); 865 break; 866 case Builtin::BI__builtin_object_size: 867 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 868 return ExprError(); 869 break; 870 case Builtin::BI__builtin_longjmp: 871 if (SemaBuiltinLongjmp(TheCall)) 872 return ExprError(); 873 break; 874 case Builtin::BI__builtin_setjmp: 875 if (SemaBuiltinSetjmp(TheCall)) 876 return ExprError(); 877 break; 878 case Builtin::BI_setjmp: 879 case Builtin::BI_setjmpex: 880 if (checkArgCount(*this, TheCall, 1)) 881 return true; 882 break; 883 884 case Builtin::BI__builtin_classify_type: 885 if (checkArgCount(*this, TheCall, 1)) return true; 886 TheCall->setType(Context.IntTy); 887 break; 888 case Builtin::BI__builtin_constant_p: 889 if (checkArgCount(*this, TheCall, 1)) return true; 890 TheCall->setType(Context.IntTy); 891 break; 892 case Builtin::BI__sync_fetch_and_add: 893 case Builtin::BI__sync_fetch_and_add_1: 894 case Builtin::BI__sync_fetch_and_add_2: 895 case Builtin::BI__sync_fetch_and_add_4: 896 case Builtin::BI__sync_fetch_and_add_8: 897 case Builtin::BI__sync_fetch_and_add_16: 898 case Builtin::BI__sync_fetch_and_sub: 899 case Builtin::BI__sync_fetch_and_sub_1: 900 case Builtin::BI__sync_fetch_and_sub_2: 901 case Builtin::BI__sync_fetch_and_sub_4: 902 case Builtin::BI__sync_fetch_and_sub_8: 903 case Builtin::BI__sync_fetch_and_sub_16: 904 case Builtin::BI__sync_fetch_and_or: 905 case Builtin::BI__sync_fetch_and_or_1: 906 case Builtin::BI__sync_fetch_and_or_2: 907 case Builtin::BI__sync_fetch_and_or_4: 908 case Builtin::BI__sync_fetch_and_or_8: 909 case Builtin::BI__sync_fetch_and_or_16: 910 case Builtin::BI__sync_fetch_and_and: 911 case Builtin::BI__sync_fetch_and_and_1: 912 case Builtin::BI__sync_fetch_and_and_2: 913 case Builtin::BI__sync_fetch_and_and_4: 914 case Builtin::BI__sync_fetch_and_and_8: 915 case Builtin::BI__sync_fetch_and_and_16: 916 case Builtin::BI__sync_fetch_and_xor: 917 case Builtin::BI__sync_fetch_and_xor_1: 918 case Builtin::BI__sync_fetch_and_xor_2: 919 case Builtin::BI__sync_fetch_and_xor_4: 920 case Builtin::BI__sync_fetch_and_xor_8: 921 case Builtin::BI__sync_fetch_and_xor_16: 922 case Builtin::BI__sync_fetch_and_nand: 923 case Builtin::BI__sync_fetch_and_nand_1: 924 case Builtin::BI__sync_fetch_and_nand_2: 925 case Builtin::BI__sync_fetch_and_nand_4: 926 case Builtin::BI__sync_fetch_and_nand_8: 927 case Builtin::BI__sync_fetch_and_nand_16: 928 case Builtin::BI__sync_add_and_fetch: 929 case Builtin::BI__sync_add_and_fetch_1: 930 case Builtin::BI__sync_add_and_fetch_2: 931 case Builtin::BI__sync_add_and_fetch_4: 932 case Builtin::BI__sync_add_and_fetch_8: 933 case Builtin::BI__sync_add_and_fetch_16: 934 case Builtin::BI__sync_sub_and_fetch: 935 case Builtin::BI__sync_sub_and_fetch_1: 936 case Builtin::BI__sync_sub_and_fetch_2: 937 case Builtin::BI__sync_sub_and_fetch_4: 938 case Builtin::BI__sync_sub_and_fetch_8: 939 case Builtin::BI__sync_sub_and_fetch_16: 940 case Builtin::BI__sync_and_and_fetch: 941 case Builtin::BI__sync_and_and_fetch_1: 942 case Builtin::BI__sync_and_and_fetch_2: 943 case Builtin::BI__sync_and_and_fetch_4: 944 case Builtin::BI__sync_and_and_fetch_8: 945 case Builtin::BI__sync_and_and_fetch_16: 946 case Builtin::BI__sync_or_and_fetch: 947 case Builtin::BI__sync_or_and_fetch_1: 948 case Builtin::BI__sync_or_and_fetch_2: 949 case Builtin::BI__sync_or_and_fetch_4: 950 case Builtin::BI__sync_or_and_fetch_8: 951 case Builtin::BI__sync_or_and_fetch_16: 952 case Builtin::BI__sync_xor_and_fetch: 953 case Builtin::BI__sync_xor_and_fetch_1: 954 case Builtin::BI__sync_xor_and_fetch_2: 955 case Builtin::BI__sync_xor_and_fetch_4: 956 case Builtin::BI__sync_xor_and_fetch_8: 957 case Builtin::BI__sync_xor_and_fetch_16: 958 case Builtin::BI__sync_nand_and_fetch: 959 case Builtin::BI__sync_nand_and_fetch_1: 960 case Builtin::BI__sync_nand_and_fetch_2: 961 case Builtin::BI__sync_nand_and_fetch_4: 962 case Builtin::BI__sync_nand_and_fetch_8: 963 case Builtin::BI__sync_nand_and_fetch_16: 964 case Builtin::BI__sync_val_compare_and_swap: 965 case Builtin::BI__sync_val_compare_and_swap_1: 966 case Builtin::BI__sync_val_compare_and_swap_2: 967 case Builtin::BI__sync_val_compare_and_swap_4: 968 case Builtin::BI__sync_val_compare_and_swap_8: 969 case Builtin::BI__sync_val_compare_and_swap_16: 970 case Builtin::BI__sync_bool_compare_and_swap: 971 case Builtin::BI__sync_bool_compare_and_swap_1: 972 case Builtin::BI__sync_bool_compare_and_swap_2: 973 case Builtin::BI__sync_bool_compare_and_swap_4: 974 case Builtin::BI__sync_bool_compare_and_swap_8: 975 case Builtin::BI__sync_bool_compare_and_swap_16: 976 case Builtin::BI__sync_lock_test_and_set: 977 case Builtin::BI__sync_lock_test_and_set_1: 978 case Builtin::BI__sync_lock_test_and_set_2: 979 case Builtin::BI__sync_lock_test_and_set_4: 980 case Builtin::BI__sync_lock_test_and_set_8: 981 case Builtin::BI__sync_lock_test_and_set_16: 982 case Builtin::BI__sync_lock_release: 983 case Builtin::BI__sync_lock_release_1: 984 case Builtin::BI__sync_lock_release_2: 985 case Builtin::BI__sync_lock_release_4: 986 case Builtin::BI__sync_lock_release_8: 987 case Builtin::BI__sync_lock_release_16: 988 case Builtin::BI__sync_swap: 989 case Builtin::BI__sync_swap_1: 990 case Builtin::BI__sync_swap_2: 991 case Builtin::BI__sync_swap_4: 992 case Builtin::BI__sync_swap_8: 993 case Builtin::BI__sync_swap_16: 994 return SemaBuiltinAtomicOverloaded(TheCallResult); 995 case Builtin::BI__builtin_nontemporal_load: 996 case Builtin::BI__builtin_nontemporal_store: 997 return SemaBuiltinNontemporalOverloaded(TheCallResult); 998 #define BUILTIN(ID, TYPE, ATTRS) 999 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1000 case Builtin::BI##ID: \ 1001 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1002 #include "clang/Basic/Builtins.def" 1003 case Builtin::BI__builtin_annotation: 1004 if (SemaBuiltinAnnotation(*this, TheCall)) 1005 return ExprError(); 1006 break; 1007 case Builtin::BI__builtin_addressof: 1008 if (SemaBuiltinAddressof(*this, TheCall)) 1009 return ExprError(); 1010 break; 1011 case Builtin::BI__builtin_add_overflow: 1012 case Builtin::BI__builtin_sub_overflow: 1013 case Builtin::BI__builtin_mul_overflow: 1014 if (SemaBuiltinOverflow(*this, TheCall)) 1015 return ExprError(); 1016 break; 1017 case Builtin::BI__builtin_operator_new: 1018 case Builtin::BI__builtin_operator_delete: 1019 if (!getLangOpts().CPlusPlus) { 1020 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 1021 << (BuiltinID == Builtin::BI__builtin_operator_new 1022 ? "__builtin_operator_new" 1023 : "__builtin_operator_delete") 1024 << "C++"; 1025 return ExprError(); 1026 } 1027 // CodeGen assumes it can find the global new and delete to call, 1028 // so ensure that they are declared. 1029 DeclareGlobalNewDelete(); 1030 break; 1031 1032 // check secure string manipulation functions where overflows 1033 // are detectable at compile time 1034 case Builtin::BI__builtin___memcpy_chk: 1035 case Builtin::BI__builtin___memmove_chk: 1036 case Builtin::BI__builtin___memset_chk: 1037 case Builtin::BI__builtin___strlcat_chk: 1038 case Builtin::BI__builtin___strlcpy_chk: 1039 case Builtin::BI__builtin___strncat_chk: 1040 case Builtin::BI__builtin___strncpy_chk: 1041 case Builtin::BI__builtin___stpncpy_chk: 1042 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 1043 break; 1044 case Builtin::BI__builtin___memccpy_chk: 1045 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 1046 break; 1047 case Builtin::BI__builtin___snprintf_chk: 1048 case Builtin::BI__builtin___vsnprintf_chk: 1049 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 1050 break; 1051 case Builtin::BI__builtin_call_with_static_chain: 1052 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1053 return ExprError(); 1054 break; 1055 case Builtin::BI__exception_code: 1056 case Builtin::BI_exception_code: 1057 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1058 diag::err_seh___except_block)) 1059 return ExprError(); 1060 break; 1061 case Builtin::BI__exception_info: 1062 case Builtin::BI_exception_info: 1063 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1064 diag::err_seh___except_filter)) 1065 return ExprError(); 1066 break; 1067 case Builtin::BI__GetExceptionInfo: 1068 if (checkArgCount(*this, TheCall, 1)) 1069 return ExprError(); 1070 1071 if (CheckCXXThrowOperand( 1072 TheCall->getLocStart(), 1073 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1074 TheCall)) 1075 return ExprError(); 1076 1077 TheCall->setType(Context.VoidPtrTy); 1078 break; 1079 // OpenCL v2.0, s6.13.16 - Pipe functions 1080 case Builtin::BIread_pipe: 1081 case Builtin::BIwrite_pipe: 1082 // Since those two functions are declared with var args, we need a semantic 1083 // check for the argument. 1084 if (SemaBuiltinRWPipe(*this, TheCall)) 1085 return ExprError(); 1086 TheCall->setType(Context.IntTy); 1087 break; 1088 case Builtin::BIreserve_read_pipe: 1089 case Builtin::BIreserve_write_pipe: 1090 case Builtin::BIwork_group_reserve_read_pipe: 1091 case Builtin::BIwork_group_reserve_write_pipe: 1092 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1093 return ExprError(); 1094 break; 1095 case Builtin::BIsub_group_reserve_read_pipe: 1096 case Builtin::BIsub_group_reserve_write_pipe: 1097 if (checkOpenCLSubgroupExt(*this, TheCall) || 1098 SemaBuiltinReserveRWPipe(*this, TheCall)) 1099 return ExprError(); 1100 break; 1101 case Builtin::BIcommit_read_pipe: 1102 case Builtin::BIcommit_write_pipe: 1103 case Builtin::BIwork_group_commit_read_pipe: 1104 case Builtin::BIwork_group_commit_write_pipe: 1105 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1106 return ExprError(); 1107 break; 1108 case Builtin::BIsub_group_commit_read_pipe: 1109 case Builtin::BIsub_group_commit_write_pipe: 1110 if (checkOpenCLSubgroupExt(*this, TheCall) || 1111 SemaBuiltinCommitRWPipe(*this, TheCall)) 1112 return ExprError(); 1113 break; 1114 case Builtin::BIget_pipe_num_packets: 1115 case Builtin::BIget_pipe_max_packets: 1116 if (SemaBuiltinPipePackets(*this, TheCall)) 1117 return ExprError(); 1118 TheCall->setType(Context.UnsignedIntTy); 1119 break; 1120 case Builtin::BIto_global: 1121 case Builtin::BIto_local: 1122 case Builtin::BIto_private: 1123 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1124 return ExprError(); 1125 break; 1126 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1127 case Builtin::BIenqueue_kernel: 1128 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1129 return ExprError(); 1130 break; 1131 case Builtin::BIget_kernel_work_group_size: 1132 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1133 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1134 return ExprError(); 1135 break; 1136 break; 1137 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1138 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1139 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1140 return ExprError(); 1141 break; 1142 case Builtin::BI__builtin_os_log_format: 1143 case Builtin::BI__builtin_os_log_format_buffer_size: 1144 if (SemaBuiltinOSLogFormat(TheCall)) { 1145 return ExprError(); 1146 } 1147 break; 1148 } 1149 1150 // Since the target specific builtins for each arch overlap, only check those 1151 // of the arch we are compiling for. 1152 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1153 switch (Context.getTargetInfo().getTriple().getArch()) { 1154 case llvm::Triple::arm: 1155 case llvm::Triple::armeb: 1156 case llvm::Triple::thumb: 1157 case llvm::Triple::thumbeb: 1158 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1159 return ExprError(); 1160 break; 1161 case llvm::Triple::aarch64: 1162 case llvm::Triple::aarch64_be: 1163 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1164 return ExprError(); 1165 break; 1166 case llvm::Triple::mips: 1167 case llvm::Triple::mipsel: 1168 case llvm::Triple::mips64: 1169 case llvm::Triple::mips64el: 1170 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1171 return ExprError(); 1172 break; 1173 case llvm::Triple::systemz: 1174 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1175 return ExprError(); 1176 break; 1177 case llvm::Triple::x86: 1178 case llvm::Triple::x86_64: 1179 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1180 return ExprError(); 1181 break; 1182 case llvm::Triple::ppc: 1183 case llvm::Triple::ppc64: 1184 case llvm::Triple::ppc64le: 1185 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1186 return ExprError(); 1187 break; 1188 default: 1189 break; 1190 } 1191 } 1192 1193 return TheCallResult; 1194 } 1195 1196 // Get the valid immediate range for the specified NEON type code. 1197 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1198 NeonTypeFlags Type(t); 1199 int IsQuad = ForceQuad ? true : Type.isQuad(); 1200 switch (Type.getEltType()) { 1201 case NeonTypeFlags::Int8: 1202 case NeonTypeFlags::Poly8: 1203 return shift ? 7 : (8 << IsQuad) - 1; 1204 case NeonTypeFlags::Int16: 1205 case NeonTypeFlags::Poly16: 1206 return shift ? 15 : (4 << IsQuad) - 1; 1207 case NeonTypeFlags::Int32: 1208 return shift ? 31 : (2 << IsQuad) - 1; 1209 case NeonTypeFlags::Int64: 1210 case NeonTypeFlags::Poly64: 1211 return shift ? 63 : (1 << IsQuad) - 1; 1212 case NeonTypeFlags::Poly128: 1213 return shift ? 127 : (1 << IsQuad) - 1; 1214 case NeonTypeFlags::Float16: 1215 assert(!shift && "cannot shift float types!"); 1216 return (4 << IsQuad) - 1; 1217 case NeonTypeFlags::Float32: 1218 assert(!shift && "cannot shift float types!"); 1219 return (2 << IsQuad) - 1; 1220 case NeonTypeFlags::Float64: 1221 assert(!shift && "cannot shift float types!"); 1222 return (1 << IsQuad) - 1; 1223 } 1224 llvm_unreachable("Invalid NeonTypeFlag!"); 1225 } 1226 1227 /// getNeonEltType - Return the QualType corresponding to the elements of 1228 /// the vector type specified by the NeonTypeFlags. This is used to check 1229 /// the pointer arguments for Neon load/store intrinsics. 1230 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1231 bool IsPolyUnsigned, bool IsInt64Long) { 1232 switch (Flags.getEltType()) { 1233 case NeonTypeFlags::Int8: 1234 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1235 case NeonTypeFlags::Int16: 1236 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1237 case NeonTypeFlags::Int32: 1238 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1239 case NeonTypeFlags::Int64: 1240 if (IsInt64Long) 1241 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1242 else 1243 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1244 : Context.LongLongTy; 1245 case NeonTypeFlags::Poly8: 1246 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1247 case NeonTypeFlags::Poly16: 1248 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1249 case NeonTypeFlags::Poly64: 1250 if (IsInt64Long) 1251 return Context.UnsignedLongTy; 1252 else 1253 return Context.UnsignedLongLongTy; 1254 case NeonTypeFlags::Poly128: 1255 break; 1256 case NeonTypeFlags::Float16: 1257 return Context.HalfTy; 1258 case NeonTypeFlags::Float32: 1259 return Context.FloatTy; 1260 case NeonTypeFlags::Float64: 1261 return Context.DoubleTy; 1262 } 1263 llvm_unreachable("Invalid NeonTypeFlag!"); 1264 } 1265 1266 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1267 llvm::APSInt Result; 1268 uint64_t mask = 0; 1269 unsigned TV = 0; 1270 int PtrArgNum = -1; 1271 bool HasConstPtr = false; 1272 switch (BuiltinID) { 1273 #define GET_NEON_OVERLOAD_CHECK 1274 #include "clang/Basic/arm_neon.inc" 1275 #undef GET_NEON_OVERLOAD_CHECK 1276 } 1277 1278 // For NEON intrinsics which are overloaded on vector element type, validate 1279 // the immediate which specifies which variant to emit. 1280 unsigned ImmArg = TheCall->getNumArgs()-1; 1281 if (mask) { 1282 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1283 return true; 1284 1285 TV = Result.getLimitedValue(64); 1286 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1287 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1288 << TheCall->getArg(ImmArg)->getSourceRange(); 1289 } 1290 1291 if (PtrArgNum >= 0) { 1292 // Check that pointer arguments have the specified type. 1293 Expr *Arg = TheCall->getArg(PtrArgNum); 1294 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1295 Arg = ICE->getSubExpr(); 1296 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1297 QualType RHSTy = RHS.get()->getType(); 1298 1299 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1300 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1301 Arch == llvm::Triple::aarch64_be; 1302 bool IsInt64Long = 1303 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1304 QualType EltTy = 1305 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1306 if (HasConstPtr) 1307 EltTy = EltTy.withConst(); 1308 QualType LHSTy = Context.getPointerType(EltTy); 1309 AssignConvertType ConvTy; 1310 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1311 if (RHS.isInvalid()) 1312 return true; 1313 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1314 RHS.get(), AA_Assigning)) 1315 return true; 1316 } 1317 1318 // For NEON intrinsics which take an immediate value as part of the 1319 // instruction, range check them here. 1320 unsigned i = 0, l = 0, u = 0; 1321 switch (BuiltinID) { 1322 default: 1323 return false; 1324 #define GET_NEON_IMMEDIATE_CHECK 1325 #include "clang/Basic/arm_neon.inc" 1326 #undef GET_NEON_IMMEDIATE_CHECK 1327 } 1328 1329 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1330 } 1331 1332 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1333 unsigned MaxWidth) { 1334 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1335 BuiltinID == ARM::BI__builtin_arm_ldaex || 1336 BuiltinID == ARM::BI__builtin_arm_strex || 1337 BuiltinID == ARM::BI__builtin_arm_stlex || 1338 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1339 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1340 BuiltinID == AArch64::BI__builtin_arm_strex || 1341 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1342 "unexpected ARM builtin"); 1343 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1344 BuiltinID == ARM::BI__builtin_arm_ldaex || 1345 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1346 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1347 1348 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1349 1350 // Ensure that we have the proper number of arguments. 1351 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1352 return true; 1353 1354 // Inspect the pointer argument of the atomic builtin. This should always be 1355 // a pointer type, whose element is an integral scalar or pointer type. 1356 // Because it is a pointer type, we don't have to worry about any implicit 1357 // casts here. 1358 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1359 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1360 if (PointerArgRes.isInvalid()) 1361 return true; 1362 PointerArg = PointerArgRes.get(); 1363 1364 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1365 if (!pointerType) { 1366 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1367 << PointerArg->getType() << PointerArg->getSourceRange(); 1368 return true; 1369 } 1370 1371 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1372 // task is to insert the appropriate casts into the AST. First work out just 1373 // what the appropriate type is. 1374 QualType ValType = pointerType->getPointeeType(); 1375 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1376 if (IsLdrex) 1377 AddrType.addConst(); 1378 1379 // Issue a warning if the cast is dodgy. 1380 CastKind CastNeeded = CK_NoOp; 1381 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1382 CastNeeded = CK_BitCast; 1383 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1384 << PointerArg->getType() 1385 << Context.getPointerType(AddrType) 1386 << AA_Passing << PointerArg->getSourceRange(); 1387 } 1388 1389 // Finally, do the cast and replace the argument with the corrected version. 1390 AddrType = Context.getPointerType(AddrType); 1391 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1392 if (PointerArgRes.isInvalid()) 1393 return true; 1394 PointerArg = PointerArgRes.get(); 1395 1396 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1397 1398 // In general, we allow ints, floats and pointers to be loaded and stored. 1399 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1400 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1401 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1402 << PointerArg->getType() << PointerArg->getSourceRange(); 1403 return true; 1404 } 1405 1406 // But ARM doesn't have instructions to deal with 128-bit versions. 1407 if (Context.getTypeSize(ValType) > MaxWidth) { 1408 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1409 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1410 << PointerArg->getType() << PointerArg->getSourceRange(); 1411 return true; 1412 } 1413 1414 switch (ValType.getObjCLifetime()) { 1415 case Qualifiers::OCL_None: 1416 case Qualifiers::OCL_ExplicitNone: 1417 // okay 1418 break; 1419 1420 case Qualifiers::OCL_Weak: 1421 case Qualifiers::OCL_Strong: 1422 case Qualifiers::OCL_Autoreleasing: 1423 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1424 << ValType << PointerArg->getSourceRange(); 1425 return true; 1426 } 1427 1428 if (IsLdrex) { 1429 TheCall->setType(ValType); 1430 return false; 1431 } 1432 1433 // Initialize the argument to be stored. 1434 ExprResult ValArg = TheCall->getArg(0); 1435 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1436 Context, ValType, /*consume*/ false); 1437 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1438 if (ValArg.isInvalid()) 1439 return true; 1440 TheCall->setArg(0, ValArg.get()); 1441 1442 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1443 // but the custom checker bypasses all default analysis. 1444 TheCall->setType(Context.IntTy); 1445 return false; 1446 } 1447 1448 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1449 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1450 BuiltinID == ARM::BI__builtin_arm_ldaex || 1451 BuiltinID == ARM::BI__builtin_arm_strex || 1452 BuiltinID == ARM::BI__builtin_arm_stlex) { 1453 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1454 } 1455 1456 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1457 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1458 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1459 } 1460 1461 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1462 BuiltinID == ARM::BI__builtin_arm_wsr64) 1463 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1464 1465 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1466 BuiltinID == ARM::BI__builtin_arm_rsrp || 1467 BuiltinID == ARM::BI__builtin_arm_wsr || 1468 BuiltinID == ARM::BI__builtin_arm_wsrp) 1469 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1470 1471 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1472 return true; 1473 1474 // For intrinsics which take an immediate value as part of the instruction, 1475 // range check them here. 1476 unsigned i = 0, l = 0, u = 0; 1477 switch (BuiltinID) { 1478 default: return false; 1479 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 1480 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 1481 case ARM::BI__builtin_arm_vcvtr_f: 1482 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 1483 case ARM::BI__builtin_arm_dmb: 1484 case ARM::BI__builtin_arm_dsb: 1485 case ARM::BI__builtin_arm_isb: 1486 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break; 1487 } 1488 1489 // FIXME: VFP Intrinsics should error if VFP not present. 1490 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1491 } 1492 1493 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1494 CallExpr *TheCall) { 1495 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1496 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1497 BuiltinID == AArch64::BI__builtin_arm_strex || 1498 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1499 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1500 } 1501 1502 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1503 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1504 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1505 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1506 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1507 } 1508 1509 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1510 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1511 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1512 1513 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1514 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1515 BuiltinID == AArch64::BI__builtin_arm_wsr || 1516 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1517 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1518 1519 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1520 return true; 1521 1522 // For intrinsics which take an immediate value as part of the instruction, 1523 // range check them here. 1524 unsigned i = 0, l = 0, u = 0; 1525 switch (BuiltinID) { 1526 default: return false; 1527 case AArch64::BI__builtin_arm_dmb: 1528 case AArch64::BI__builtin_arm_dsb: 1529 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1530 } 1531 1532 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1533 } 1534 1535 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1536 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1537 // ordering for DSP is unspecified. MSA is ordered by the data format used 1538 // by the underlying instruction i.e., df/m, df/n and then by size. 1539 // 1540 // FIXME: The size tests here should instead be tablegen'd along with the 1541 // definitions from include/clang/Basic/BuiltinsMips.def. 1542 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1543 // be too. 1544 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1545 unsigned i = 0, l = 0, u = 0, m = 0; 1546 switch (BuiltinID) { 1547 default: return false; 1548 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1549 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1550 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1551 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1552 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1553 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1554 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1555 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1556 // df/m field. 1557 // These intrinsics take an unsigned 3 bit immediate. 1558 case Mips::BI__builtin_msa_bclri_b: 1559 case Mips::BI__builtin_msa_bnegi_b: 1560 case Mips::BI__builtin_msa_bseti_b: 1561 case Mips::BI__builtin_msa_sat_s_b: 1562 case Mips::BI__builtin_msa_sat_u_b: 1563 case Mips::BI__builtin_msa_slli_b: 1564 case Mips::BI__builtin_msa_srai_b: 1565 case Mips::BI__builtin_msa_srari_b: 1566 case Mips::BI__builtin_msa_srli_b: 1567 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1568 case Mips::BI__builtin_msa_binsli_b: 1569 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1570 // These intrinsics take an unsigned 4 bit immediate. 1571 case Mips::BI__builtin_msa_bclri_h: 1572 case Mips::BI__builtin_msa_bnegi_h: 1573 case Mips::BI__builtin_msa_bseti_h: 1574 case Mips::BI__builtin_msa_sat_s_h: 1575 case Mips::BI__builtin_msa_sat_u_h: 1576 case Mips::BI__builtin_msa_slli_h: 1577 case Mips::BI__builtin_msa_srai_h: 1578 case Mips::BI__builtin_msa_srari_h: 1579 case Mips::BI__builtin_msa_srli_h: 1580 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1581 case Mips::BI__builtin_msa_binsli_h: 1582 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 1583 // These intrinsics take an unsigned 5 bit immedate. 1584 // The first block of intrinsics actually have an unsigned 5 bit field, 1585 // not a df/n field. 1586 case Mips::BI__builtin_msa_clei_u_b: 1587 case Mips::BI__builtin_msa_clei_u_h: 1588 case Mips::BI__builtin_msa_clei_u_w: 1589 case Mips::BI__builtin_msa_clei_u_d: 1590 case Mips::BI__builtin_msa_clti_u_b: 1591 case Mips::BI__builtin_msa_clti_u_h: 1592 case Mips::BI__builtin_msa_clti_u_w: 1593 case Mips::BI__builtin_msa_clti_u_d: 1594 case Mips::BI__builtin_msa_maxi_u_b: 1595 case Mips::BI__builtin_msa_maxi_u_h: 1596 case Mips::BI__builtin_msa_maxi_u_w: 1597 case Mips::BI__builtin_msa_maxi_u_d: 1598 case Mips::BI__builtin_msa_mini_u_b: 1599 case Mips::BI__builtin_msa_mini_u_h: 1600 case Mips::BI__builtin_msa_mini_u_w: 1601 case Mips::BI__builtin_msa_mini_u_d: 1602 case Mips::BI__builtin_msa_addvi_b: 1603 case Mips::BI__builtin_msa_addvi_h: 1604 case Mips::BI__builtin_msa_addvi_w: 1605 case Mips::BI__builtin_msa_addvi_d: 1606 case Mips::BI__builtin_msa_bclri_w: 1607 case Mips::BI__builtin_msa_bnegi_w: 1608 case Mips::BI__builtin_msa_bseti_w: 1609 case Mips::BI__builtin_msa_sat_s_w: 1610 case Mips::BI__builtin_msa_sat_u_w: 1611 case Mips::BI__builtin_msa_slli_w: 1612 case Mips::BI__builtin_msa_srai_w: 1613 case Mips::BI__builtin_msa_srari_w: 1614 case Mips::BI__builtin_msa_srli_w: 1615 case Mips::BI__builtin_msa_srlri_w: 1616 case Mips::BI__builtin_msa_subvi_b: 1617 case Mips::BI__builtin_msa_subvi_h: 1618 case Mips::BI__builtin_msa_subvi_w: 1619 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 1620 case Mips::BI__builtin_msa_binsli_w: 1621 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 1622 // These intrinsics take an unsigned 6 bit immediate. 1623 case Mips::BI__builtin_msa_bclri_d: 1624 case Mips::BI__builtin_msa_bnegi_d: 1625 case Mips::BI__builtin_msa_bseti_d: 1626 case Mips::BI__builtin_msa_sat_s_d: 1627 case Mips::BI__builtin_msa_sat_u_d: 1628 case Mips::BI__builtin_msa_slli_d: 1629 case Mips::BI__builtin_msa_srai_d: 1630 case Mips::BI__builtin_msa_srari_d: 1631 case Mips::BI__builtin_msa_srli_d: 1632 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 1633 case Mips::BI__builtin_msa_binsli_d: 1634 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 1635 // These intrinsics take a signed 5 bit immediate. 1636 case Mips::BI__builtin_msa_ceqi_b: 1637 case Mips::BI__builtin_msa_ceqi_h: 1638 case Mips::BI__builtin_msa_ceqi_w: 1639 case Mips::BI__builtin_msa_ceqi_d: 1640 case Mips::BI__builtin_msa_clti_s_b: 1641 case Mips::BI__builtin_msa_clti_s_h: 1642 case Mips::BI__builtin_msa_clti_s_w: 1643 case Mips::BI__builtin_msa_clti_s_d: 1644 case Mips::BI__builtin_msa_clei_s_b: 1645 case Mips::BI__builtin_msa_clei_s_h: 1646 case Mips::BI__builtin_msa_clei_s_w: 1647 case Mips::BI__builtin_msa_clei_s_d: 1648 case Mips::BI__builtin_msa_maxi_s_b: 1649 case Mips::BI__builtin_msa_maxi_s_h: 1650 case Mips::BI__builtin_msa_maxi_s_w: 1651 case Mips::BI__builtin_msa_maxi_s_d: 1652 case Mips::BI__builtin_msa_mini_s_b: 1653 case Mips::BI__builtin_msa_mini_s_h: 1654 case Mips::BI__builtin_msa_mini_s_w: 1655 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 1656 // These intrinsics take an unsigned 8 bit immediate. 1657 case Mips::BI__builtin_msa_andi_b: 1658 case Mips::BI__builtin_msa_nori_b: 1659 case Mips::BI__builtin_msa_ori_b: 1660 case Mips::BI__builtin_msa_shf_b: 1661 case Mips::BI__builtin_msa_shf_h: 1662 case Mips::BI__builtin_msa_shf_w: 1663 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 1664 case Mips::BI__builtin_msa_bseli_b: 1665 case Mips::BI__builtin_msa_bmnzi_b: 1666 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 1667 // df/n format 1668 // These intrinsics take an unsigned 4 bit immediate. 1669 case Mips::BI__builtin_msa_copy_s_b: 1670 case Mips::BI__builtin_msa_copy_u_b: 1671 case Mips::BI__builtin_msa_insve_b: 1672 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 1673 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 1674 // These intrinsics take an unsigned 3 bit immediate. 1675 case Mips::BI__builtin_msa_copy_s_h: 1676 case Mips::BI__builtin_msa_copy_u_h: 1677 case Mips::BI__builtin_msa_insve_h: 1678 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 1679 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 1680 // These intrinsics take an unsigned 2 bit immediate. 1681 case Mips::BI__builtin_msa_copy_s_w: 1682 case Mips::BI__builtin_msa_copy_u_w: 1683 case Mips::BI__builtin_msa_insve_w: 1684 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 1685 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 1686 // These intrinsics take an unsigned 1 bit immediate. 1687 case Mips::BI__builtin_msa_copy_s_d: 1688 case Mips::BI__builtin_msa_copy_u_d: 1689 case Mips::BI__builtin_msa_insve_d: 1690 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 1691 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 1692 // Memory offsets and immediate loads. 1693 // These intrinsics take a signed 10 bit immediate. 1694 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 1695 case Mips::BI__builtin_msa_ldi_h: 1696 case Mips::BI__builtin_msa_ldi_w: 1697 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 1698 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 1699 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 1700 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 1701 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 1702 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 1703 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 1704 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 1705 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 1706 } 1707 1708 if (!m) 1709 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1710 1711 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 1712 SemaBuiltinConstantArgMultiple(TheCall, i, m); 1713 } 1714 1715 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1716 unsigned i = 0, l = 0, u = 0; 1717 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 1718 BuiltinID == PPC::BI__builtin_divdeu || 1719 BuiltinID == PPC::BI__builtin_bpermd; 1720 bool IsTarget64Bit = Context.getTargetInfo() 1721 .getTypeWidth(Context 1722 .getTargetInfo() 1723 .getIntPtrType()) == 64; 1724 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 1725 BuiltinID == PPC::BI__builtin_divweu || 1726 BuiltinID == PPC::BI__builtin_divde || 1727 BuiltinID == PPC::BI__builtin_divdeu; 1728 1729 if (Is64BitBltin && !IsTarget64Bit) 1730 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 1731 << TheCall->getSourceRange(); 1732 1733 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 1734 (BuiltinID == PPC::BI__builtin_bpermd && 1735 !Context.getTargetInfo().hasFeature("bpermd"))) 1736 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 1737 << TheCall->getSourceRange(); 1738 1739 switch (BuiltinID) { 1740 default: return false; 1741 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 1742 case PPC::BI__builtin_altivec_crypto_vshasigmad: 1743 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1744 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1745 case PPC::BI__builtin_tbegin: 1746 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 1747 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 1748 case PPC::BI__builtin_tabortwc: 1749 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 1750 case PPC::BI__builtin_tabortwci: 1751 case PPC::BI__builtin_tabortdci: 1752 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 1753 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 1754 case PPC::BI__builtin_vsx_xxpermdi: 1755 case PPC::BI__builtin_vsx_xxsldwi: 1756 return SemaBuiltinVSX(TheCall); 1757 } 1758 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1759 } 1760 1761 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 1762 CallExpr *TheCall) { 1763 if (BuiltinID == SystemZ::BI__builtin_tabort) { 1764 Expr *Arg = TheCall->getArg(0); 1765 llvm::APSInt AbortCode(32); 1766 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 1767 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 1768 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 1769 << Arg->getSourceRange(); 1770 } 1771 1772 // For intrinsics which take an immediate value as part of the instruction, 1773 // range check them here. 1774 unsigned i = 0, l = 0, u = 0; 1775 switch (BuiltinID) { 1776 default: return false; 1777 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 1778 case SystemZ::BI__builtin_s390_verimb: 1779 case SystemZ::BI__builtin_s390_verimh: 1780 case SystemZ::BI__builtin_s390_verimf: 1781 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 1782 case SystemZ::BI__builtin_s390_vfaeb: 1783 case SystemZ::BI__builtin_s390_vfaeh: 1784 case SystemZ::BI__builtin_s390_vfaef: 1785 case SystemZ::BI__builtin_s390_vfaebs: 1786 case SystemZ::BI__builtin_s390_vfaehs: 1787 case SystemZ::BI__builtin_s390_vfaefs: 1788 case SystemZ::BI__builtin_s390_vfaezb: 1789 case SystemZ::BI__builtin_s390_vfaezh: 1790 case SystemZ::BI__builtin_s390_vfaezf: 1791 case SystemZ::BI__builtin_s390_vfaezbs: 1792 case SystemZ::BI__builtin_s390_vfaezhs: 1793 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 1794 case SystemZ::BI__builtin_s390_vfisb: 1795 case SystemZ::BI__builtin_s390_vfidb: 1796 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 1797 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1798 case SystemZ::BI__builtin_s390_vftcisb: 1799 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 1800 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 1801 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 1802 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 1803 case SystemZ::BI__builtin_s390_vstrcb: 1804 case SystemZ::BI__builtin_s390_vstrch: 1805 case SystemZ::BI__builtin_s390_vstrcf: 1806 case SystemZ::BI__builtin_s390_vstrczb: 1807 case SystemZ::BI__builtin_s390_vstrczh: 1808 case SystemZ::BI__builtin_s390_vstrczf: 1809 case SystemZ::BI__builtin_s390_vstrcbs: 1810 case SystemZ::BI__builtin_s390_vstrchs: 1811 case SystemZ::BI__builtin_s390_vstrcfs: 1812 case SystemZ::BI__builtin_s390_vstrczbs: 1813 case SystemZ::BI__builtin_s390_vstrczhs: 1814 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 1815 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 1816 case SystemZ::BI__builtin_s390_vfminsb: 1817 case SystemZ::BI__builtin_s390_vfmaxsb: 1818 case SystemZ::BI__builtin_s390_vfmindb: 1819 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 1820 } 1821 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1822 } 1823 1824 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 1825 /// This checks that the target supports __builtin_cpu_supports and 1826 /// that the string argument is constant and valid. 1827 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 1828 Expr *Arg = TheCall->getArg(0); 1829 1830 // Check if the argument is a string literal. 1831 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1832 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1833 << Arg->getSourceRange(); 1834 1835 // Check the contents of the string. 1836 StringRef Feature = 1837 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1838 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 1839 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 1840 << Arg->getSourceRange(); 1841 return false; 1842 } 1843 1844 // Check if the rounding mode is legal. 1845 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 1846 // Indicates if this instruction has rounding control or just SAE. 1847 bool HasRC = false; 1848 1849 unsigned ArgNum = 0; 1850 switch (BuiltinID) { 1851 default: 1852 return false; 1853 case X86::BI__builtin_ia32_vcvttsd2si32: 1854 case X86::BI__builtin_ia32_vcvttsd2si64: 1855 case X86::BI__builtin_ia32_vcvttsd2usi32: 1856 case X86::BI__builtin_ia32_vcvttsd2usi64: 1857 case X86::BI__builtin_ia32_vcvttss2si32: 1858 case X86::BI__builtin_ia32_vcvttss2si64: 1859 case X86::BI__builtin_ia32_vcvttss2usi32: 1860 case X86::BI__builtin_ia32_vcvttss2usi64: 1861 ArgNum = 1; 1862 break; 1863 case X86::BI__builtin_ia32_cvtps2pd512_mask: 1864 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 1865 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 1866 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 1867 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 1868 case X86::BI__builtin_ia32_cvttps2dq512_mask: 1869 case X86::BI__builtin_ia32_cvttps2qq512_mask: 1870 case X86::BI__builtin_ia32_cvttps2udq512_mask: 1871 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 1872 case X86::BI__builtin_ia32_exp2pd_mask: 1873 case X86::BI__builtin_ia32_exp2ps_mask: 1874 case X86::BI__builtin_ia32_getexppd512_mask: 1875 case X86::BI__builtin_ia32_getexpps512_mask: 1876 case X86::BI__builtin_ia32_rcp28pd_mask: 1877 case X86::BI__builtin_ia32_rcp28ps_mask: 1878 case X86::BI__builtin_ia32_rsqrt28pd_mask: 1879 case X86::BI__builtin_ia32_rsqrt28ps_mask: 1880 case X86::BI__builtin_ia32_vcomisd: 1881 case X86::BI__builtin_ia32_vcomiss: 1882 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 1883 ArgNum = 3; 1884 break; 1885 case X86::BI__builtin_ia32_cmppd512_mask: 1886 case X86::BI__builtin_ia32_cmpps512_mask: 1887 case X86::BI__builtin_ia32_cmpsd_mask: 1888 case X86::BI__builtin_ia32_cmpss_mask: 1889 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 1890 case X86::BI__builtin_ia32_getexpsd128_round_mask: 1891 case X86::BI__builtin_ia32_getexpss128_round_mask: 1892 case X86::BI__builtin_ia32_maxpd512_mask: 1893 case X86::BI__builtin_ia32_maxps512_mask: 1894 case X86::BI__builtin_ia32_maxsd_round_mask: 1895 case X86::BI__builtin_ia32_maxss_round_mask: 1896 case X86::BI__builtin_ia32_minpd512_mask: 1897 case X86::BI__builtin_ia32_minps512_mask: 1898 case X86::BI__builtin_ia32_minsd_round_mask: 1899 case X86::BI__builtin_ia32_minss_round_mask: 1900 case X86::BI__builtin_ia32_rcp28sd_round_mask: 1901 case X86::BI__builtin_ia32_rcp28ss_round_mask: 1902 case X86::BI__builtin_ia32_reducepd512_mask: 1903 case X86::BI__builtin_ia32_reduceps512_mask: 1904 case X86::BI__builtin_ia32_rndscalepd_mask: 1905 case X86::BI__builtin_ia32_rndscaleps_mask: 1906 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 1907 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 1908 ArgNum = 4; 1909 break; 1910 case X86::BI__builtin_ia32_fixupimmpd512_mask: 1911 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 1912 case X86::BI__builtin_ia32_fixupimmps512_mask: 1913 case X86::BI__builtin_ia32_fixupimmps512_maskz: 1914 case X86::BI__builtin_ia32_fixupimmsd_mask: 1915 case X86::BI__builtin_ia32_fixupimmsd_maskz: 1916 case X86::BI__builtin_ia32_fixupimmss_mask: 1917 case X86::BI__builtin_ia32_fixupimmss_maskz: 1918 case X86::BI__builtin_ia32_rangepd512_mask: 1919 case X86::BI__builtin_ia32_rangeps512_mask: 1920 case X86::BI__builtin_ia32_rangesd128_round_mask: 1921 case X86::BI__builtin_ia32_rangess128_round_mask: 1922 case X86::BI__builtin_ia32_reducesd_mask: 1923 case X86::BI__builtin_ia32_reducess_mask: 1924 case X86::BI__builtin_ia32_rndscalesd_round_mask: 1925 case X86::BI__builtin_ia32_rndscaless_round_mask: 1926 ArgNum = 5; 1927 break; 1928 case X86::BI__builtin_ia32_vcvtsd2si64: 1929 case X86::BI__builtin_ia32_vcvtsd2si32: 1930 case X86::BI__builtin_ia32_vcvtsd2usi32: 1931 case X86::BI__builtin_ia32_vcvtsd2usi64: 1932 case X86::BI__builtin_ia32_vcvtss2si32: 1933 case X86::BI__builtin_ia32_vcvtss2si64: 1934 case X86::BI__builtin_ia32_vcvtss2usi32: 1935 case X86::BI__builtin_ia32_vcvtss2usi64: 1936 ArgNum = 1; 1937 HasRC = true; 1938 break; 1939 case X86::BI__builtin_ia32_cvtsi2sd64: 1940 case X86::BI__builtin_ia32_cvtsi2ss32: 1941 case X86::BI__builtin_ia32_cvtsi2ss64: 1942 case X86::BI__builtin_ia32_cvtusi2sd64: 1943 case X86::BI__builtin_ia32_cvtusi2ss32: 1944 case X86::BI__builtin_ia32_cvtusi2ss64: 1945 ArgNum = 2; 1946 HasRC = true; 1947 break; 1948 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 1949 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 1950 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 1951 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 1952 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 1953 case X86::BI__builtin_ia32_cvtps2qq512_mask: 1954 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 1955 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 1956 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 1957 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 1958 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 1959 case X86::BI__builtin_ia32_sqrtpd512_mask: 1960 case X86::BI__builtin_ia32_sqrtps512_mask: 1961 ArgNum = 3; 1962 HasRC = true; 1963 break; 1964 case X86::BI__builtin_ia32_addpd512_mask: 1965 case X86::BI__builtin_ia32_addps512_mask: 1966 case X86::BI__builtin_ia32_divpd512_mask: 1967 case X86::BI__builtin_ia32_divps512_mask: 1968 case X86::BI__builtin_ia32_mulpd512_mask: 1969 case X86::BI__builtin_ia32_mulps512_mask: 1970 case X86::BI__builtin_ia32_subpd512_mask: 1971 case X86::BI__builtin_ia32_subps512_mask: 1972 case X86::BI__builtin_ia32_addss_round_mask: 1973 case X86::BI__builtin_ia32_addsd_round_mask: 1974 case X86::BI__builtin_ia32_divss_round_mask: 1975 case X86::BI__builtin_ia32_divsd_round_mask: 1976 case X86::BI__builtin_ia32_mulss_round_mask: 1977 case X86::BI__builtin_ia32_mulsd_round_mask: 1978 case X86::BI__builtin_ia32_subss_round_mask: 1979 case X86::BI__builtin_ia32_subsd_round_mask: 1980 case X86::BI__builtin_ia32_scalefpd512_mask: 1981 case X86::BI__builtin_ia32_scalefps512_mask: 1982 case X86::BI__builtin_ia32_scalefsd_round_mask: 1983 case X86::BI__builtin_ia32_scalefss_round_mask: 1984 case X86::BI__builtin_ia32_getmantpd512_mask: 1985 case X86::BI__builtin_ia32_getmantps512_mask: 1986 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 1987 case X86::BI__builtin_ia32_sqrtsd_round_mask: 1988 case X86::BI__builtin_ia32_sqrtss_round_mask: 1989 case X86::BI__builtin_ia32_vfmaddpd512_mask: 1990 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 1991 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 1992 case X86::BI__builtin_ia32_vfmaddps512_mask: 1993 case X86::BI__builtin_ia32_vfmaddps512_mask3: 1994 case X86::BI__builtin_ia32_vfmaddps512_maskz: 1995 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 1996 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 1997 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 1998 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 1999 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 2000 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 2001 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 2002 case X86::BI__builtin_ia32_vfmsubps512_mask3: 2003 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 2004 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 2005 case X86::BI__builtin_ia32_vfnmaddpd512_mask: 2006 case X86::BI__builtin_ia32_vfnmaddps512_mask: 2007 case X86::BI__builtin_ia32_vfnmsubpd512_mask: 2008 case X86::BI__builtin_ia32_vfnmsubpd512_mask3: 2009 case X86::BI__builtin_ia32_vfnmsubps512_mask: 2010 case X86::BI__builtin_ia32_vfnmsubps512_mask3: 2011 case X86::BI__builtin_ia32_vfmaddsd3_mask: 2012 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 2013 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 2014 case X86::BI__builtin_ia32_vfmaddss3_mask: 2015 case X86::BI__builtin_ia32_vfmaddss3_maskz: 2016 case X86::BI__builtin_ia32_vfmaddss3_mask3: 2017 ArgNum = 4; 2018 HasRC = true; 2019 break; 2020 case X86::BI__builtin_ia32_getmantsd_round_mask: 2021 case X86::BI__builtin_ia32_getmantss_round_mask: 2022 ArgNum = 5; 2023 HasRC = true; 2024 break; 2025 } 2026 2027 llvm::APSInt Result; 2028 2029 // We can't check the value of a dependent argument. 2030 Expr *Arg = TheCall->getArg(ArgNum); 2031 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2032 return false; 2033 2034 // Check constant-ness first. 2035 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2036 return true; 2037 2038 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 2039 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 2040 // combined with ROUND_NO_EXC. 2041 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 2042 Result == 8/*ROUND_NO_EXC*/ || 2043 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 2044 return false; 2045 2046 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 2047 << Arg->getSourceRange(); 2048 } 2049 2050 // Check if the gather/scatter scale is legal. 2051 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 2052 CallExpr *TheCall) { 2053 unsigned ArgNum = 0; 2054 switch (BuiltinID) { 2055 default: 2056 return false; 2057 case X86::BI__builtin_ia32_gatherpfdpd: 2058 case X86::BI__builtin_ia32_gatherpfdps: 2059 case X86::BI__builtin_ia32_gatherpfqpd: 2060 case X86::BI__builtin_ia32_gatherpfqps: 2061 case X86::BI__builtin_ia32_scatterpfdpd: 2062 case X86::BI__builtin_ia32_scatterpfdps: 2063 case X86::BI__builtin_ia32_scatterpfqpd: 2064 case X86::BI__builtin_ia32_scatterpfqps: 2065 ArgNum = 3; 2066 break; 2067 case X86::BI__builtin_ia32_gatherd_pd: 2068 case X86::BI__builtin_ia32_gatherd_pd256: 2069 case X86::BI__builtin_ia32_gatherq_pd: 2070 case X86::BI__builtin_ia32_gatherq_pd256: 2071 case X86::BI__builtin_ia32_gatherd_ps: 2072 case X86::BI__builtin_ia32_gatherd_ps256: 2073 case X86::BI__builtin_ia32_gatherq_ps: 2074 case X86::BI__builtin_ia32_gatherq_ps256: 2075 case X86::BI__builtin_ia32_gatherd_q: 2076 case X86::BI__builtin_ia32_gatherd_q256: 2077 case X86::BI__builtin_ia32_gatherq_q: 2078 case X86::BI__builtin_ia32_gatherq_q256: 2079 case X86::BI__builtin_ia32_gatherd_d: 2080 case X86::BI__builtin_ia32_gatherd_d256: 2081 case X86::BI__builtin_ia32_gatherq_d: 2082 case X86::BI__builtin_ia32_gatherq_d256: 2083 case X86::BI__builtin_ia32_gather3div2df: 2084 case X86::BI__builtin_ia32_gather3div2di: 2085 case X86::BI__builtin_ia32_gather3div4df: 2086 case X86::BI__builtin_ia32_gather3div4di: 2087 case X86::BI__builtin_ia32_gather3div4sf: 2088 case X86::BI__builtin_ia32_gather3div4si: 2089 case X86::BI__builtin_ia32_gather3div8sf: 2090 case X86::BI__builtin_ia32_gather3div8si: 2091 case X86::BI__builtin_ia32_gather3siv2df: 2092 case X86::BI__builtin_ia32_gather3siv2di: 2093 case X86::BI__builtin_ia32_gather3siv4df: 2094 case X86::BI__builtin_ia32_gather3siv4di: 2095 case X86::BI__builtin_ia32_gather3siv4sf: 2096 case X86::BI__builtin_ia32_gather3siv4si: 2097 case X86::BI__builtin_ia32_gather3siv8sf: 2098 case X86::BI__builtin_ia32_gather3siv8si: 2099 case X86::BI__builtin_ia32_gathersiv8df: 2100 case X86::BI__builtin_ia32_gathersiv16sf: 2101 case X86::BI__builtin_ia32_gatherdiv8df: 2102 case X86::BI__builtin_ia32_gatherdiv16sf: 2103 case X86::BI__builtin_ia32_gathersiv8di: 2104 case X86::BI__builtin_ia32_gathersiv16si: 2105 case X86::BI__builtin_ia32_gatherdiv8di: 2106 case X86::BI__builtin_ia32_gatherdiv16si: 2107 case X86::BI__builtin_ia32_scatterdiv2df: 2108 case X86::BI__builtin_ia32_scatterdiv2di: 2109 case X86::BI__builtin_ia32_scatterdiv4df: 2110 case X86::BI__builtin_ia32_scatterdiv4di: 2111 case X86::BI__builtin_ia32_scatterdiv4sf: 2112 case X86::BI__builtin_ia32_scatterdiv4si: 2113 case X86::BI__builtin_ia32_scatterdiv8sf: 2114 case X86::BI__builtin_ia32_scatterdiv8si: 2115 case X86::BI__builtin_ia32_scattersiv2df: 2116 case X86::BI__builtin_ia32_scattersiv2di: 2117 case X86::BI__builtin_ia32_scattersiv4df: 2118 case X86::BI__builtin_ia32_scattersiv4di: 2119 case X86::BI__builtin_ia32_scattersiv4sf: 2120 case X86::BI__builtin_ia32_scattersiv4si: 2121 case X86::BI__builtin_ia32_scattersiv8sf: 2122 case X86::BI__builtin_ia32_scattersiv8si: 2123 case X86::BI__builtin_ia32_scattersiv8df: 2124 case X86::BI__builtin_ia32_scattersiv16sf: 2125 case X86::BI__builtin_ia32_scatterdiv8df: 2126 case X86::BI__builtin_ia32_scatterdiv16sf: 2127 case X86::BI__builtin_ia32_scattersiv8di: 2128 case X86::BI__builtin_ia32_scattersiv16si: 2129 case X86::BI__builtin_ia32_scatterdiv8di: 2130 case X86::BI__builtin_ia32_scatterdiv16si: 2131 ArgNum = 4; 2132 break; 2133 } 2134 2135 llvm::APSInt Result; 2136 2137 // We can't check the value of a dependent argument. 2138 Expr *Arg = TheCall->getArg(ArgNum); 2139 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2140 return false; 2141 2142 // Check constant-ness first. 2143 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2144 return true; 2145 2146 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 2147 return false; 2148 2149 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale) 2150 << Arg->getSourceRange(); 2151 } 2152 2153 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2154 if (BuiltinID == X86::BI__builtin_cpu_supports) 2155 return SemaBuiltinCpuSupports(*this, TheCall); 2156 2157 // If the intrinsic has rounding or SAE make sure its valid. 2158 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 2159 return true; 2160 2161 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 2162 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 2163 return true; 2164 2165 // For intrinsics which take an immediate value as part of the instruction, 2166 // range check them here. 2167 int i = 0, l = 0, u = 0; 2168 switch (BuiltinID) { 2169 default: 2170 return false; 2171 case X86::BI_mm_prefetch: 2172 i = 1; l = 0; u = 3; 2173 break; 2174 case X86::BI__builtin_ia32_sha1rnds4: 2175 case X86::BI__builtin_ia32_shuf_f32x4_256_mask: 2176 case X86::BI__builtin_ia32_shuf_f64x2_256_mask: 2177 case X86::BI__builtin_ia32_shuf_i32x4_256_mask: 2178 case X86::BI__builtin_ia32_shuf_i64x2_256_mask: 2179 i = 2; l = 0; u = 3; 2180 break; 2181 case X86::BI__builtin_ia32_vpermil2pd: 2182 case X86::BI__builtin_ia32_vpermil2pd256: 2183 case X86::BI__builtin_ia32_vpermil2ps: 2184 case X86::BI__builtin_ia32_vpermil2ps256: 2185 i = 3; l = 0; u = 3; 2186 break; 2187 case X86::BI__builtin_ia32_cmpb128_mask: 2188 case X86::BI__builtin_ia32_cmpw128_mask: 2189 case X86::BI__builtin_ia32_cmpd128_mask: 2190 case X86::BI__builtin_ia32_cmpq128_mask: 2191 case X86::BI__builtin_ia32_cmpb256_mask: 2192 case X86::BI__builtin_ia32_cmpw256_mask: 2193 case X86::BI__builtin_ia32_cmpd256_mask: 2194 case X86::BI__builtin_ia32_cmpq256_mask: 2195 case X86::BI__builtin_ia32_cmpb512_mask: 2196 case X86::BI__builtin_ia32_cmpw512_mask: 2197 case X86::BI__builtin_ia32_cmpd512_mask: 2198 case X86::BI__builtin_ia32_cmpq512_mask: 2199 case X86::BI__builtin_ia32_ucmpb128_mask: 2200 case X86::BI__builtin_ia32_ucmpw128_mask: 2201 case X86::BI__builtin_ia32_ucmpd128_mask: 2202 case X86::BI__builtin_ia32_ucmpq128_mask: 2203 case X86::BI__builtin_ia32_ucmpb256_mask: 2204 case X86::BI__builtin_ia32_ucmpw256_mask: 2205 case X86::BI__builtin_ia32_ucmpd256_mask: 2206 case X86::BI__builtin_ia32_ucmpq256_mask: 2207 case X86::BI__builtin_ia32_ucmpb512_mask: 2208 case X86::BI__builtin_ia32_ucmpw512_mask: 2209 case X86::BI__builtin_ia32_ucmpd512_mask: 2210 case X86::BI__builtin_ia32_ucmpq512_mask: 2211 case X86::BI__builtin_ia32_vpcomub: 2212 case X86::BI__builtin_ia32_vpcomuw: 2213 case X86::BI__builtin_ia32_vpcomud: 2214 case X86::BI__builtin_ia32_vpcomuq: 2215 case X86::BI__builtin_ia32_vpcomb: 2216 case X86::BI__builtin_ia32_vpcomw: 2217 case X86::BI__builtin_ia32_vpcomd: 2218 case X86::BI__builtin_ia32_vpcomq: 2219 i = 2; l = 0; u = 7; 2220 break; 2221 case X86::BI__builtin_ia32_roundps: 2222 case X86::BI__builtin_ia32_roundpd: 2223 case X86::BI__builtin_ia32_roundps256: 2224 case X86::BI__builtin_ia32_roundpd256: 2225 i = 1; l = 0; u = 15; 2226 break; 2227 case X86::BI__builtin_ia32_roundss: 2228 case X86::BI__builtin_ia32_roundsd: 2229 case X86::BI__builtin_ia32_rangepd128_mask: 2230 case X86::BI__builtin_ia32_rangepd256_mask: 2231 case X86::BI__builtin_ia32_rangepd512_mask: 2232 case X86::BI__builtin_ia32_rangeps128_mask: 2233 case X86::BI__builtin_ia32_rangeps256_mask: 2234 case X86::BI__builtin_ia32_rangeps512_mask: 2235 case X86::BI__builtin_ia32_getmantsd_round_mask: 2236 case X86::BI__builtin_ia32_getmantss_round_mask: 2237 i = 2; l = 0; u = 15; 2238 break; 2239 case X86::BI__builtin_ia32_cmpps: 2240 case X86::BI__builtin_ia32_cmpss: 2241 case X86::BI__builtin_ia32_cmppd: 2242 case X86::BI__builtin_ia32_cmpsd: 2243 case X86::BI__builtin_ia32_cmpps256: 2244 case X86::BI__builtin_ia32_cmppd256: 2245 case X86::BI__builtin_ia32_cmpps128_mask: 2246 case X86::BI__builtin_ia32_cmppd128_mask: 2247 case X86::BI__builtin_ia32_cmpps256_mask: 2248 case X86::BI__builtin_ia32_cmppd256_mask: 2249 case X86::BI__builtin_ia32_cmpps512_mask: 2250 case X86::BI__builtin_ia32_cmppd512_mask: 2251 case X86::BI__builtin_ia32_cmpsd_mask: 2252 case X86::BI__builtin_ia32_cmpss_mask: 2253 i = 2; l = 0; u = 31; 2254 break; 2255 case X86::BI__builtin_ia32_xabort: 2256 i = 0; l = -128; u = 255; 2257 break; 2258 case X86::BI__builtin_ia32_pshufw: 2259 case X86::BI__builtin_ia32_aeskeygenassist128: 2260 i = 1; l = -128; u = 255; 2261 break; 2262 case X86::BI__builtin_ia32_vcvtps2ph: 2263 case X86::BI__builtin_ia32_vcvtps2ph256: 2264 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2265 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2266 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2267 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2268 case X86::BI__builtin_ia32_rndscaleps_mask: 2269 case X86::BI__builtin_ia32_rndscalepd_mask: 2270 case X86::BI__builtin_ia32_reducepd128_mask: 2271 case X86::BI__builtin_ia32_reducepd256_mask: 2272 case X86::BI__builtin_ia32_reducepd512_mask: 2273 case X86::BI__builtin_ia32_reduceps128_mask: 2274 case X86::BI__builtin_ia32_reduceps256_mask: 2275 case X86::BI__builtin_ia32_reduceps512_mask: 2276 case X86::BI__builtin_ia32_prold512_mask: 2277 case X86::BI__builtin_ia32_prolq512_mask: 2278 case X86::BI__builtin_ia32_prold128_mask: 2279 case X86::BI__builtin_ia32_prold256_mask: 2280 case X86::BI__builtin_ia32_prolq128_mask: 2281 case X86::BI__builtin_ia32_prolq256_mask: 2282 case X86::BI__builtin_ia32_prord128_mask: 2283 case X86::BI__builtin_ia32_prord256_mask: 2284 case X86::BI__builtin_ia32_prorq128_mask: 2285 case X86::BI__builtin_ia32_prorq256_mask: 2286 case X86::BI__builtin_ia32_fpclasspd128_mask: 2287 case X86::BI__builtin_ia32_fpclasspd256_mask: 2288 case X86::BI__builtin_ia32_fpclassps128_mask: 2289 case X86::BI__builtin_ia32_fpclassps256_mask: 2290 case X86::BI__builtin_ia32_fpclassps512_mask: 2291 case X86::BI__builtin_ia32_fpclasspd512_mask: 2292 case X86::BI__builtin_ia32_fpclasssd_mask: 2293 case X86::BI__builtin_ia32_fpclassss_mask: 2294 i = 1; l = 0; u = 255; 2295 break; 2296 case X86::BI__builtin_ia32_palignr: 2297 case X86::BI__builtin_ia32_insertps128: 2298 case X86::BI__builtin_ia32_dpps: 2299 case X86::BI__builtin_ia32_dppd: 2300 case X86::BI__builtin_ia32_dpps256: 2301 case X86::BI__builtin_ia32_mpsadbw128: 2302 case X86::BI__builtin_ia32_mpsadbw256: 2303 case X86::BI__builtin_ia32_pcmpistrm128: 2304 case X86::BI__builtin_ia32_pcmpistri128: 2305 case X86::BI__builtin_ia32_pcmpistria128: 2306 case X86::BI__builtin_ia32_pcmpistric128: 2307 case X86::BI__builtin_ia32_pcmpistrio128: 2308 case X86::BI__builtin_ia32_pcmpistris128: 2309 case X86::BI__builtin_ia32_pcmpistriz128: 2310 case X86::BI__builtin_ia32_pclmulqdq128: 2311 case X86::BI__builtin_ia32_vperm2f128_pd256: 2312 case X86::BI__builtin_ia32_vperm2f128_ps256: 2313 case X86::BI__builtin_ia32_vperm2f128_si256: 2314 case X86::BI__builtin_ia32_permti256: 2315 i = 2; l = -128; u = 255; 2316 break; 2317 case X86::BI__builtin_ia32_palignr128: 2318 case X86::BI__builtin_ia32_palignr256: 2319 case X86::BI__builtin_ia32_palignr512_mask: 2320 case X86::BI__builtin_ia32_vcomisd: 2321 case X86::BI__builtin_ia32_vcomiss: 2322 case X86::BI__builtin_ia32_shuf_f32x4_mask: 2323 case X86::BI__builtin_ia32_shuf_f64x2_mask: 2324 case X86::BI__builtin_ia32_shuf_i32x4_mask: 2325 case X86::BI__builtin_ia32_shuf_i64x2_mask: 2326 case X86::BI__builtin_ia32_dbpsadbw128_mask: 2327 case X86::BI__builtin_ia32_dbpsadbw256_mask: 2328 case X86::BI__builtin_ia32_dbpsadbw512_mask: 2329 i = 2; l = 0; u = 255; 2330 break; 2331 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2332 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2333 case X86::BI__builtin_ia32_fixupimmps512_mask: 2334 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2335 case X86::BI__builtin_ia32_fixupimmsd_mask: 2336 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2337 case X86::BI__builtin_ia32_fixupimmss_mask: 2338 case X86::BI__builtin_ia32_fixupimmss_maskz: 2339 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2340 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2341 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2342 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2343 case X86::BI__builtin_ia32_fixupimmps128_mask: 2344 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2345 case X86::BI__builtin_ia32_fixupimmps256_mask: 2346 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2347 case X86::BI__builtin_ia32_pternlogd512_mask: 2348 case X86::BI__builtin_ia32_pternlogd512_maskz: 2349 case X86::BI__builtin_ia32_pternlogq512_mask: 2350 case X86::BI__builtin_ia32_pternlogq512_maskz: 2351 case X86::BI__builtin_ia32_pternlogd128_mask: 2352 case X86::BI__builtin_ia32_pternlogd128_maskz: 2353 case X86::BI__builtin_ia32_pternlogd256_mask: 2354 case X86::BI__builtin_ia32_pternlogd256_maskz: 2355 case X86::BI__builtin_ia32_pternlogq128_mask: 2356 case X86::BI__builtin_ia32_pternlogq128_maskz: 2357 case X86::BI__builtin_ia32_pternlogq256_mask: 2358 case X86::BI__builtin_ia32_pternlogq256_maskz: 2359 i = 3; l = 0; u = 255; 2360 break; 2361 case X86::BI__builtin_ia32_gatherpfdpd: 2362 case X86::BI__builtin_ia32_gatherpfdps: 2363 case X86::BI__builtin_ia32_gatherpfqpd: 2364 case X86::BI__builtin_ia32_gatherpfqps: 2365 case X86::BI__builtin_ia32_scatterpfdpd: 2366 case X86::BI__builtin_ia32_scatterpfdps: 2367 case X86::BI__builtin_ia32_scatterpfqpd: 2368 case X86::BI__builtin_ia32_scatterpfqps: 2369 i = 4; l = 2; u = 3; 2370 break; 2371 case X86::BI__builtin_ia32_pcmpestrm128: 2372 case X86::BI__builtin_ia32_pcmpestri128: 2373 case X86::BI__builtin_ia32_pcmpestria128: 2374 case X86::BI__builtin_ia32_pcmpestric128: 2375 case X86::BI__builtin_ia32_pcmpestrio128: 2376 case X86::BI__builtin_ia32_pcmpestris128: 2377 case X86::BI__builtin_ia32_pcmpestriz128: 2378 i = 4; l = -128; u = 255; 2379 break; 2380 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2381 case X86::BI__builtin_ia32_rndscaless_round_mask: 2382 i = 4; l = 0; u = 255; 2383 break; 2384 } 2385 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2386 } 2387 2388 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2389 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2390 /// Returns true when the format fits the function and the FormatStringInfo has 2391 /// been populated. 2392 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2393 FormatStringInfo *FSI) { 2394 FSI->HasVAListArg = Format->getFirstArg() == 0; 2395 FSI->FormatIdx = Format->getFormatIdx() - 1; 2396 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2397 2398 // The way the format attribute works in GCC, the implicit this argument 2399 // of member functions is counted. However, it doesn't appear in our own 2400 // lists, so decrement format_idx in that case. 2401 if (IsCXXMember) { 2402 if(FSI->FormatIdx == 0) 2403 return false; 2404 --FSI->FormatIdx; 2405 if (FSI->FirstDataArg != 0) 2406 --FSI->FirstDataArg; 2407 } 2408 return true; 2409 } 2410 2411 /// Checks if a the given expression evaluates to null. 2412 /// 2413 /// \brief Returns true if the value evaluates to null. 2414 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2415 // If the expression has non-null type, it doesn't evaluate to null. 2416 if (auto nullability 2417 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2418 if (*nullability == NullabilityKind::NonNull) 2419 return false; 2420 } 2421 2422 // As a special case, transparent unions initialized with zero are 2423 // considered null for the purposes of the nonnull attribute. 2424 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2425 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2426 if (const CompoundLiteralExpr *CLE = 2427 dyn_cast<CompoundLiteralExpr>(Expr)) 2428 if (const InitListExpr *ILE = 2429 dyn_cast<InitListExpr>(CLE->getInitializer())) 2430 Expr = ILE->getInit(0); 2431 } 2432 2433 bool Result; 2434 return (!Expr->isValueDependent() && 2435 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2436 !Result); 2437 } 2438 2439 static void CheckNonNullArgument(Sema &S, 2440 const Expr *ArgExpr, 2441 SourceLocation CallSiteLoc) { 2442 if (CheckNonNullExpr(S, ArgExpr)) 2443 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2444 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2445 } 2446 2447 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2448 FormatStringInfo FSI; 2449 if ((GetFormatStringType(Format) == FST_NSString) && 2450 getFormatStringInfo(Format, false, &FSI)) { 2451 Idx = FSI.FormatIdx; 2452 return true; 2453 } 2454 return false; 2455 } 2456 /// \brief Diagnose use of %s directive in an NSString which is being passed 2457 /// as formatting string to formatting method. 2458 static void 2459 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 2460 const NamedDecl *FDecl, 2461 Expr **Args, 2462 unsigned NumArgs) { 2463 unsigned Idx = 0; 2464 bool Format = false; 2465 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 2466 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 2467 Idx = 2; 2468 Format = true; 2469 } 2470 else 2471 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2472 if (S.GetFormatNSStringIdx(I, Idx)) { 2473 Format = true; 2474 break; 2475 } 2476 } 2477 if (!Format || NumArgs <= Idx) 2478 return; 2479 const Expr *FormatExpr = Args[Idx]; 2480 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2481 FormatExpr = CSCE->getSubExpr(); 2482 const StringLiteral *FormatString; 2483 if (const ObjCStringLiteral *OSL = 2484 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2485 FormatString = OSL->getString(); 2486 else 2487 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2488 if (!FormatString) 2489 return; 2490 if (S.FormatStringHasSArg(FormatString)) { 2491 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2492 << "%s" << 1 << 1; 2493 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2494 << FDecl->getDeclName(); 2495 } 2496 } 2497 2498 /// Determine whether the given type has a non-null nullability annotation. 2499 static bool isNonNullType(ASTContext &ctx, QualType type) { 2500 if (auto nullability = type->getNullability(ctx)) 2501 return *nullability == NullabilityKind::NonNull; 2502 2503 return false; 2504 } 2505 2506 static void CheckNonNullArguments(Sema &S, 2507 const NamedDecl *FDecl, 2508 const FunctionProtoType *Proto, 2509 ArrayRef<const Expr *> Args, 2510 SourceLocation CallSiteLoc) { 2511 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2512 2513 // Check the attributes attached to the method/function itself. 2514 llvm::SmallBitVector NonNullArgs; 2515 if (FDecl) { 2516 // Handle the nonnull attribute on the function/method declaration itself. 2517 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2518 if (!NonNull->args_size()) { 2519 // Easy case: all pointer arguments are nonnull. 2520 for (const auto *Arg : Args) 2521 if (S.isValidPointerAttrType(Arg->getType())) 2522 CheckNonNullArgument(S, Arg, CallSiteLoc); 2523 return; 2524 } 2525 2526 for (unsigned Val : NonNull->args()) { 2527 if (Val >= Args.size()) 2528 continue; 2529 if (NonNullArgs.empty()) 2530 NonNullArgs.resize(Args.size()); 2531 NonNullArgs.set(Val); 2532 } 2533 } 2534 } 2535 2536 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2537 // Handle the nonnull attribute on the parameters of the 2538 // function/method. 2539 ArrayRef<ParmVarDecl*> parms; 2540 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2541 parms = FD->parameters(); 2542 else 2543 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2544 2545 unsigned ParamIndex = 0; 2546 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2547 I != E; ++I, ++ParamIndex) { 2548 const ParmVarDecl *PVD = *I; 2549 if (PVD->hasAttr<NonNullAttr>() || 2550 isNonNullType(S.Context, PVD->getType())) { 2551 if (NonNullArgs.empty()) 2552 NonNullArgs.resize(Args.size()); 2553 2554 NonNullArgs.set(ParamIndex); 2555 } 2556 } 2557 } else { 2558 // If we have a non-function, non-method declaration but no 2559 // function prototype, try to dig out the function prototype. 2560 if (!Proto) { 2561 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2562 QualType type = VD->getType().getNonReferenceType(); 2563 if (auto pointerType = type->getAs<PointerType>()) 2564 type = pointerType->getPointeeType(); 2565 else if (auto blockType = type->getAs<BlockPointerType>()) 2566 type = blockType->getPointeeType(); 2567 // FIXME: data member pointers? 2568 2569 // Dig out the function prototype, if there is one. 2570 Proto = type->getAs<FunctionProtoType>(); 2571 } 2572 } 2573 2574 // Fill in non-null argument information from the nullability 2575 // information on the parameter types (if we have them). 2576 if (Proto) { 2577 unsigned Index = 0; 2578 for (auto paramType : Proto->getParamTypes()) { 2579 if (isNonNullType(S.Context, paramType)) { 2580 if (NonNullArgs.empty()) 2581 NonNullArgs.resize(Args.size()); 2582 2583 NonNullArgs.set(Index); 2584 } 2585 2586 ++Index; 2587 } 2588 } 2589 } 2590 2591 // Check for non-null arguments. 2592 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2593 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2594 if (NonNullArgs[ArgIndex]) 2595 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2596 } 2597 } 2598 2599 /// Handles the checks for format strings, non-POD arguments to vararg 2600 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 2601 /// attributes. 2602 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2603 const Expr *ThisArg, ArrayRef<const Expr *> Args, 2604 bool IsMemberFunction, SourceLocation Loc, 2605 SourceRange Range, VariadicCallType CallType) { 2606 // FIXME: We should check as much as we can in the template definition. 2607 if (CurContext->isDependentContext()) 2608 return; 2609 2610 // Printf and scanf checking. 2611 llvm::SmallBitVector CheckedVarArgs; 2612 if (FDecl) { 2613 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2614 // Only create vector if there are format attributes. 2615 CheckedVarArgs.resize(Args.size()); 2616 2617 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2618 CheckedVarArgs); 2619 } 2620 } 2621 2622 // Refuse POD arguments that weren't caught by the format string 2623 // checks above. 2624 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 2625 if (CallType != VariadicDoesNotApply && 2626 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 2627 unsigned NumParams = Proto ? Proto->getNumParams() 2628 : FDecl && isa<FunctionDecl>(FDecl) 2629 ? cast<FunctionDecl>(FDecl)->getNumParams() 2630 : FDecl && isa<ObjCMethodDecl>(FDecl) 2631 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2632 : 0; 2633 2634 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2635 // Args[ArgIdx] can be null in malformed code. 2636 if (const Expr *Arg = Args[ArgIdx]) { 2637 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 2638 checkVariadicArgument(Arg, CallType); 2639 } 2640 } 2641 } 2642 2643 if (FDecl || Proto) { 2644 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 2645 2646 // Type safety checking. 2647 if (FDecl) { 2648 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 2649 CheckArgumentWithTypeTag(I, Args.data()); 2650 } 2651 } 2652 2653 if (FD) 2654 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 2655 } 2656 2657 /// CheckConstructorCall - Check a constructor call for correctness and safety 2658 /// properties not enforced by the C type system. 2659 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 2660 ArrayRef<const Expr *> Args, 2661 const FunctionProtoType *Proto, 2662 SourceLocation Loc) { 2663 VariadicCallType CallType = 2664 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 2665 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 2666 Loc, SourceRange(), CallType); 2667 } 2668 2669 /// CheckFunctionCall - Check a direct function call for various correctness 2670 /// and safety properties not strictly enforced by the C type system. 2671 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2672 const FunctionProtoType *Proto) { 2673 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 2674 isa<CXXMethodDecl>(FDecl); 2675 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 2676 IsMemberOperatorCall; 2677 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 2678 TheCall->getCallee()); 2679 Expr** Args = TheCall->getArgs(); 2680 unsigned NumArgs = TheCall->getNumArgs(); 2681 2682 Expr *ImplicitThis = nullptr; 2683 if (IsMemberOperatorCall) { 2684 // If this is a call to a member operator, hide the first argument 2685 // from checkCall. 2686 // FIXME: Our choice of AST representation here is less than ideal. 2687 ImplicitThis = Args[0]; 2688 ++Args; 2689 --NumArgs; 2690 } else if (IsMemberFunction) 2691 ImplicitThis = 2692 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 2693 2694 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 2695 IsMemberFunction, TheCall->getRParenLoc(), 2696 TheCall->getCallee()->getSourceRange(), CallType); 2697 2698 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 2699 // None of the checks below are needed for functions that don't have 2700 // simple names (e.g., C++ conversion functions). 2701 if (!FnInfo) 2702 return false; 2703 2704 CheckAbsoluteValueFunction(TheCall, FDecl); 2705 CheckMaxUnsignedZero(TheCall, FDecl); 2706 2707 if (getLangOpts().ObjC1) 2708 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 2709 2710 unsigned CMId = FDecl->getMemoryFunctionKind(); 2711 if (CMId == 0) 2712 return false; 2713 2714 // Handle memory setting and copying functions. 2715 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 2716 CheckStrlcpycatArguments(TheCall, FnInfo); 2717 else if (CMId == Builtin::BIstrncat) 2718 CheckStrncatArguments(TheCall, FnInfo); 2719 else 2720 CheckMemaccessArguments(TheCall, CMId, FnInfo); 2721 2722 return false; 2723 } 2724 2725 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 2726 ArrayRef<const Expr *> Args) { 2727 VariadicCallType CallType = 2728 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 2729 2730 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 2731 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 2732 CallType); 2733 2734 return false; 2735 } 2736 2737 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2738 const FunctionProtoType *Proto) { 2739 QualType Ty; 2740 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 2741 Ty = V->getType().getNonReferenceType(); 2742 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 2743 Ty = F->getType().getNonReferenceType(); 2744 else 2745 return false; 2746 2747 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 2748 !Ty->isFunctionProtoType()) 2749 return false; 2750 2751 VariadicCallType CallType; 2752 if (!Proto || !Proto->isVariadic()) { 2753 CallType = VariadicDoesNotApply; 2754 } else if (Ty->isBlockPointerType()) { 2755 CallType = VariadicBlock; 2756 } else { // Ty->isFunctionPointerType() 2757 CallType = VariadicFunction; 2758 } 2759 2760 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 2761 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2762 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2763 TheCall->getCallee()->getSourceRange(), CallType); 2764 2765 return false; 2766 } 2767 2768 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2769 /// such as function pointers returned from functions. 2770 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 2771 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 2772 TheCall->getCallee()); 2773 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 2774 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2775 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2776 TheCall->getCallee()->getSourceRange(), CallType); 2777 2778 return false; 2779 } 2780 2781 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 2782 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 2783 return false; 2784 2785 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 2786 switch (Op) { 2787 case AtomicExpr::AO__c11_atomic_init: 2788 case AtomicExpr::AO__opencl_atomic_init: 2789 llvm_unreachable("There is no ordering argument for an init"); 2790 2791 case AtomicExpr::AO__c11_atomic_load: 2792 case AtomicExpr::AO__opencl_atomic_load: 2793 case AtomicExpr::AO__atomic_load_n: 2794 case AtomicExpr::AO__atomic_load: 2795 return OrderingCABI != llvm::AtomicOrderingCABI::release && 2796 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2797 2798 case AtomicExpr::AO__c11_atomic_store: 2799 case AtomicExpr::AO__opencl_atomic_store: 2800 case AtomicExpr::AO__atomic_store: 2801 case AtomicExpr::AO__atomic_store_n: 2802 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 2803 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 2804 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2805 2806 default: 2807 return true; 2808 } 2809 } 2810 2811 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 2812 AtomicExpr::AtomicOp Op) { 2813 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 2814 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2815 2816 // All the non-OpenCL operations take one of the following forms. 2817 // The OpenCL operations take the __c11 forms with one extra argument for 2818 // synchronization scope. 2819 enum { 2820 // C __c11_atomic_init(A *, C) 2821 Init, 2822 // C __c11_atomic_load(A *, int) 2823 Load, 2824 // void __atomic_load(A *, CP, int) 2825 LoadCopy, 2826 // void __atomic_store(A *, CP, int) 2827 Copy, 2828 // C __c11_atomic_add(A *, M, int) 2829 Arithmetic, 2830 // C __atomic_exchange_n(A *, CP, int) 2831 Xchg, 2832 // void __atomic_exchange(A *, C *, CP, int) 2833 GNUXchg, 2834 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 2835 C11CmpXchg, 2836 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 2837 GNUCmpXchg 2838 } Form = Init; 2839 const unsigned NumForm = GNUCmpXchg + 1; 2840 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 2841 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 2842 // where: 2843 // C is an appropriate type, 2844 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 2845 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 2846 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 2847 // the int parameters are for orderings. 2848 2849 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 2850 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 2851 "need to update code for modified forms"); 2852 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 2853 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 2854 AtomicExpr::AO__atomic_load, 2855 "need to update code for modified C11 atomics"); 2856 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 2857 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 2858 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 2859 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 2860 IsOpenCL; 2861 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 2862 Op == AtomicExpr::AO__atomic_store_n || 2863 Op == AtomicExpr::AO__atomic_exchange_n || 2864 Op == AtomicExpr::AO__atomic_compare_exchange_n; 2865 bool IsAddSub = false; 2866 2867 switch (Op) { 2868 case AtomicExpr::AO__c11_atomic_init: 2869 case AtomicExpr::AO__opencl_atomic_init: 2870 Form = Init; 2871 break; 2872 2873 case AtomicExpr::AO__c11_atomic_load: 2874 case AtomicExpr::AO__opencl_atomic_load: 2875 case AtomicExpr::AO__atomic_load_n: 2876 Form = Load; 2877 break; 2878 2879 case AtomicExpr::AO__atomic_load: 2880 Form = LoadCopy; 2881 break; 2882 2883 case AtomicExpr::AO__c11_atomic_store: 2884 case AtomicExpr::AO__opencl_atomic_store: 2885 case AtomicExpr::AO__atomic_store: 2886 case AtomicExpr::AO__atomic_store_n: 2887 Form = Copy; 2888 break; 2889 2890 case AtomicExpr::AO__c11_atomic_fetch_add: 2891 case AtomicExpr::AO__c11_atomic_fetch_sub: 2892 case AtomicExpr::AO__opencl_atomic_fetch_add: 2893 case AtomicExpr::AO__opencl_atomic_fetch_sub: 2894 case AtomicExpr::AO__opencl_atomic_fetch_min: 2895 case AtomicExpr::AO__opencl_atomic_fetch_max: 2896 case AtomicExpr::AO__atomic_fetch_add: 2897 case AtomicExpr::AO__atomic_fetch_sub: 2898 case AtomicExpr::AO__atomic_add_fetch: 2899 case AtomicExpr::AO__atomic_sub_fetch: 2900 IsAddSub = true; 2901 // Fall through. 2902 case AtomicExpr::AO__c11_atomic_fetch_and: 2903 case AtomicExpr::AO__c11_atomic_fetch_or: 2904 case AtomicExpr::AO__c11_atomic_fetch_xor: 2905 case AtomicExpr::AO__opencl_atomic_fetch_and: 2906 case AtomicExpr::AO__opencl_atomic_fetch_or: 2907 case AtomicExpr::AO__opencl_atomic_fetch_xor: 2908 case AtomicExpr::AO__atomic_fetch_and: 2909 case AtomicExpr::AO__atomic_fetch_or: 2910 case AtomicExpr::AO__atomic_fetch_xor: 2911 case AtomicExpr::AO__atomic_fetch_nand: 2912 case AtomicExpr::AO__atomic_and_fetch: 2913 case AtomicExpr::AO__atomic_or_fetch: 2914 case AtomicExpr::AO__atomic_xor_fetch: 2915 case AtomicExpr::AO__atomic_nand_fetch: 2916 Form = Arithmetic; 2917 break; 2918 2919 case AtomicExpr::AO__c11_atomic_exchange: 2920 case AtomicExpr::AO__opencl_atomic_exchange: 2921 case AtomicExpr::AO__atomic_exchange_n: 2922 Form = Xchg; 2923 break; 2924 2925 case AtomicExpr::AO__atomic_exchange: 2926 Form = GNUXchg; 2927 break; 2928 2929 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 2930 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 2931 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 2932 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 2933 Form = C11CmpXchg; 2934 break; 2935 2936 case AtomicExpr::AO__atomic_compare_exchange: 2937 case AtomicExpr::AO__atomic_compare_exchange_n: 2938 Form = GNUCmpXchg; 2939 break; 2940 } 2941 2942 unsigned AdjustedNumArgs = NumArgs[Form]; 2943 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 2944 ++AdjustedNumArgs; 2945 // Check we have the right number of arguments. 2946 if (TheCall->getNumArgs() < AdjustedNumArgs) { 2947 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 2948 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 2949 << TheCall->getCallee()->getSourceRange(); 2950 return ExprError(); 2951 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 2952 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(), 2953 diag::err_typecheck_call_too_many_args) 2954 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 2955 << TheCall->getCallee()->getSourceRange(); 2956 return ExprError(); 2957 } 2958 2959 // Inspect the first argument of the atomic operation. 2960 Expr *Ptr = TheCall->getArg(0); 2961 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 2962 if (ConvertedPtr.isInvalid()) 2963 return ExprError(); 2964 2965 Ptr = ConvertedPtr.get(); 2966 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 2967 if (!pointerType) { 2968 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 2969 << Ptr->getType() << Ptr->getSourceRange(); 2970 return ExprError(); 2971 } 2972 2973 // For a __c11 builtin, this should be a pointer to an _Atomic type. 2974 QualType AtomTy = pointerType->getPointeeType(); // 'A' 2975 QualType ValType = AtomTy; // 'C' 2976 if (IsC11) { 2977 if (!AtomTy->isAtomicType()) { 2978 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 2979 << Ptr->getType() << Ptr->getSourceRange(); 2980 return ExprError(); 2981 } 2982 if (AtomTy.isConstQualified() || 2983 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 2984 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 2985 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 2986 << Ptr->getSourceRange(); 2987 return ExprError(); 2988 } 2989 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 2990 } else if (Form != Load && Form != LoadCopy) { 2991 if (ValType.isConstQualified()) { 2992 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 2993 << Ptr->getType() << Ptr->getSourceRange(); 2994 return ExprError(); 2995 } 2996 } 2997 2998 // For an arithmetic operation, the implied arithmetic must be well-formed. 2999 if (Form == Arithmetic) { 3000 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 3001 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 3002 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3003 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3004 return ExprError(); 3005 } 3006 if (!IsAddSub && !ValType->isIntegerType()) { 3007 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 3008 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3009 return ExprError(); 3010 } 3011 if (IsC11 && ValType->isPointerType() && 3012 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 3013 diag::err_incomplete_type)) { 3014 return ExprError(); 3015 } 3016 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 3017 // For __atomic_*_n operations, the value type must be a scalar integral or 3018 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 3019 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3020 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3021 return ExprError(); 3022 } 3023 3024 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 3025 !AtomTy->isScalarType()) { 3026 // For GNU atomics, require a trivially-copyable type. This is not part of 3027 // the GNU atomics specification, but we enforce it for sanity. 3028 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 3029 << Ptr->getType() << Ptr->getSourceRange(); 3030 return ExprError(); 3031 } 3032 3033 switch (ValType.getObjCLifetime()) { 3034 case Qualifiers::OCL_None: 3035 case Qualifiers::OCL_ExplicitNone: 3036 // okay 3037 break; 3038 3039 case Qualifiers::OCL_Weak: 3040 case Qualifiers::OCL_Strong: 3041 case Qualifiers::OCL_Autoreleasing: 3042 // FIXME: Can this happen? By this point, ValType should be known 3043 // to be trivially copyable. 3044 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3045 << ValType << Ptr->getSourceRange(); 3046 return ExprError(); 3047 } 3048 3049 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 3050 // volatile-ness of the pointee-type inject itself into the result or the 3051 // other operands. Similarly atomic_load can take a pointer to a const 'A'. 3052 ValType.removeLocalVolatile(); 3053 ValType.removeLocalConst(); 3054 QualType ResultType = ValType; 3055 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 3056 Form == Init) 3057 ResultType = Context.VoidTy; 3058 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 3059 ResultType = Context.BoolTy; 3060 3061 // The type of a parameter passed 'by value'. In the GNU atomics, such 3062 // arguments are actually passed as pointers. 3063 QualType ByValType = ValType; // 'CP' 3064 if (!IsC11 && !IsN) 3065 ByValType = Ptr->getType(); 3066 3067 // The first argument --- the pointer --- has a fixed type; we 3068 // deduce the types of the rest of the arguments accordingly. Walk 3069 // the remaining arguments, converting them to the deduced value type. 3070 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) { 3071 QualType Ty; 3072 if (i < NumVals[Form] + 1) { 3073 switch (i) { 3074 case 1: 3075 // The second argument is the non-atomic operand. For arithmetic, this 3076 // is always passed by value, and for a compare_exchange it is always 3077 // passed by address. For the rest, GNU uses by-address and C11 uses 3078 // by-value. 3079 assert(Form != Load); 3080 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 3081 Ty = ValType; 3082 else if (Form == Copy || Form == Xchg) 3083 Ty = ByValType; 3084 else if (Form == Arithmetic) 3085 Ty = Context.getPointerDiffType(); 3086 else { 3087 Expr *ValArg = TheCall->getArg(i); 3088 // Treat this argument as _Nonnull as we want to show a warning if 3089 // NULL is passed into it. 3090 CheckNonNullArgument(*this, ValArg, DRE->getLocStart()); 3091 unsigned AS = 0; 3092 // Keep address space of non-atomic pointer type. 3093 if (const PointerType *PtrTy = 3094 ValArg->getType()->getAs<PointerType>()) { 3095 AS = PtrTy->getPointeeType().getAddressSpace(); 3096 } 3097 Ty = Context.getPointerType( 3098 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 3099 } 3100 break; 3101 case 2: 3102 // The third argument to compare_exchange / GNU exchange is a 3103 // (pointer to a) desired value. 3104 Ty = ByValType; 3105 break; 3106 case 3: 3107 // The fourth argument to GNU compare_exchange is a 'weak' flag. 3108 Ty = Context.BoolTy; 3109 break; 3110 } 3111 } else { 3112 // The order(s) and scope are always converted to int. 3113 Ty = Context.IntTy; 3114 } 3115 3116 InitializedEntity Entity = 3117 InitializedEntity::InitializeParameter(Context, Ty, false); 3118 ExprResult Arg = TheCall->getArg(i); 3119 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3120 if (Arg.isInvalid()) 3121 return true; 3122 TheCall->setArg(i, Arg.get()); 3123 } 3124 3125 Expr *Scope; 3126 if (Form != Init) { 3127 if (IsOpenCL) { 3128 Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 3129 llvm::APSInt Result(32); 3130 if (!Scope->isIntegerConstantExpr(Result, Context)) 3131 Diag(Scope->getLocStart(), 3132 diag::err_atomic_op_has_non_constant_synch_scope) 3133 << Scope->getSourceRange(); 3134 else if (!isValidSyncScopeValue(Result.getZExtValue())) 3135 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope) 3136 << Scope->getSourceRange(); 3137 } else { 3138 Scope = IntegerLiteral::Create( 3139 Context, 3140 llvm::APInt(Context.getTypeSize(Context.IntTy), 3141 static_cast<unsigned>(SyncScope::OpenCLAllSVMDevices)), 3142 Context.IntTy, SourceLocation()); 3143 } 3144 } 3145 3146 // Permute the arguments into a 'consistent' order. 3147 SmallVector<Expr*, 5> SubExprs; 3148 SubExprs.push_back(Ptr); 3149 switch (Form) { 3150 case Init: 3151 // Note, AtomicExpr::getVal1() has a special case for this atomic. 3152 SubExprs.push_back(TheCall->getArg(1)); // Val1 3153 break; 3154 case Load: 3155 SubExprs.push_back(TheCall->getArg(1)); // Order 3156 SubExprs.push_back(Scope); // Scope 3157 break; 3158 case LoadCopy: 3159 case Copy: 3160 case Arithmetic: 3161 case Xchg: 3162 SubExprs.push_back(TheCall->getArg(2)); // Order 3163 SubExprs.push_back(Scope); // Scope 3164 SubExprs.push_back(TheCall->getArg(1)); // Val1 3165 break; 3166 case GNUXchg: 3167 // Note, AtomicExpr::getVal2() has a special case for this atomic. 3168 SubExprs.push_back(TheCall->getArg(3)); // Order 3169 SubExprs.push_back(Scope); // Scope 3170 SubExprs.push_back(TheCall->getArg(1)); // Val1 3171 SubExprs.push_back(TheCall->getArg(2)); // Val2 3172 break; 3173 case C11CmpXchg: 3174 SubExprs.push_back(TheCall->getArg(3)); // Order 3175 SubExprs.push_back(Scope); // Scope 3176 SubExprs.push_back(TheCall->getArg(1)); // Val1 3177 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 3178 SubExprs.push_back(TheCall->getArg(2)); // Val2 3179 break; 3180 case GNUCmpXchg: 3181 SubExprs.push_back(TheCall->getArg(4)); // Order 3182 SubExprs.push_back(Scope); // Scope 3183 SubExprs.push_back(TheCall->getArg(1)); // Val1 3184 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 3185 SubExprs.push_back(TheCall->getArg(2)); // Val2 3186 SubExprs.push_back(TheCall->getArg(3)); // Weak 3187 break; 3188 } 3189 3190 if (SubExprs.size() >= 2 && Form != Init) { 3191 llvm::APSInt Result(32); 3192 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 3193 !isValidOrderingForOp(Result.getSExtValue(), Op)) 3194 Diag(SubExprs[1]->getLocStart(), 3195 diag::warn_atomic_op_has_invalid_memory_order) 3196 << SubExprs[1]->getSourceRange(); 3197 } 3198 3199 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 3200 SubExprs, ResultType, Op, 3201 TheCall->getRParenLoc()); 3202 3203 if ((Op == AtomicExpr::AO__c11_atomic_load || 3204 Op == AtomicExpr::AO__c11_atomic_store || 3205 Op == AtomicExpr::AO__opencl_atomic_load || 3206 Op == AtomicExpr::AO__opencl_atomic_store ) && 3207 Context.AtomicUsesUnsupportedLibcall(AE)) 3208 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) 3209 << ((Op == AtomicExpr::AO__c11_atomic_load || 3210 Op == AtomicExpr::AO__opencl_atomic_load) 3211 ? 0 : 1); 3212 3213 return AE; 3214 } 3215 3216 /// checkBuiltinArgument - Given a call to a builtin function, perform 3217 /// normal type-checking on the given argument, updating the call in 3218 /// place. This is useful when a builtin function requires custom 3219 /// type-checking for some of its arguments but not necessarily all of 3220 /// them. 3221 /// 3222 /// Returns true on error. 3223 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 3224 FunctionDecl *Fn = E->getDirectCallee(); 3225 assert(Fn && "builtin call without direct callee!"); 3226 3227 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 3228 InitializedEntity Entity = 3229 InitializedEntity::InitializeParameter(S.Context, Param); 3230 3231 ExprResult Arg = E->getArg(0); 3232 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 3233 if (Arg.isInvalid()) 3234 return true; 3235 3236 E->setArg(ArgIndex, Arg.get()); 3237 return false; 3238 } 3239 3240 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 3241 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 3242 /// type of its first argument. The main ActOnCallExpr routines have already 3243 /// promoted the types of arguments because all of these calls are prototyped as 3244 /// void(...). 3245 /// 3246 /// This function goes through and does final semantic checking for these 3247 /// builtins, 3248 ExprResult 3249 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3250 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3251 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3252 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3253 3254 // Ensure that we have at least one argument to do type inference from. 3255 if (TheCall->getNumArgs() < 1) { 3256 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3257 << 0 << 1 << TheCall->getNumArgs() 3258 << TheCall->getCallee()->getSourceRange(); 3259 return ExprError(); 3260 } 3261 3262 // Inspect the first argument of the atomic builtin. This should always be 3263 // a pointer type, whose element is an integral scalar or pointer type. 3264 // Because it is a pointer type, we don't have to worry about any implicit 3265 // casts here. 3266 // FIXME: We don't allow floating point scalars as input. 3267 Expr *FirstArg = TheCall->getArg(0); 3268 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3269 if (FirstArgResult.isInvalid()) 3270 return ExprError(); 3271 FirstArg = FirstArgResult.get(); 3272 TheCall->setArg(0, FirstArg); 3273 3274 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3275 if (!pointerType) { 3276 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3277 << FirstArg->getType() << FirstArg->getSourceRange(); 3278 return ExprError(); 3279 } 3280 3281 QualType ValType = pointerType->getPointeeType(); 3282 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3283 !ValType->isBlockPointerType()) { 3284 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3285 << FirstArg->getType() << FirstArg->getSourceRange(); 3286 return ExprError(); 3287 } 3288 3289 switch (ValType.getObjCLifetime()) { 3290 case Qualifiers::OCL_None: 3291 case Qualifiers::OCL_ExplicitNone: 3292 // okay 3293 break; 3294 3295 case Qualifiers::OCL_Weak: 3296 case Qualifiers::OCL_Strong: 3297 case Qualifiers::OCL_Autoreleasing: 3298 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3299 << ValType << FirstArg->getSourceRange(); 3300 return ExprError(); 3301 } 3302 3303 // Strip any qualifiers off ValType. 3304 ValType = ValType.getUnqualifiedType(); 3305 3306 // The majority of builtins return a value, but a few have special return 3307 // types, so allow them to override appropriately below. 3308 QualType ResultType = ValType; 3309 3310 // We need to figure out which concrete builtin this maps onto. For example, 3311 // __sync_fetch_and_add with a 2 byte object turns into 3312 // __sync_fetch_and_add_2. 3313 #define BUILTIN_ROW(x) \ 3314 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3315 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3316 3317 static const unsigned BuiltinIndices[][5] = { 3318 BUILTIN_ROW(__sync_fetch_and_add), 3319 BUILTIN_ROW(__sync_fetch_and_sub), 3320 BUILTIN_ROW(__sync_fetch_and_or), 3321 BUILTIN_ROW(__sync_fetch_and_and), 3322 BUILTIN_ROW(__sync_fetch_and_xor), 3323 BUILTIN_ROW(__sync_fetch_and_nand), 3324 3325 BUILTIN_ROW(__sync_add_and_fetch), 3326 BUILTIN_ROW(__sync_sub_and_fetch), 3327 BUILTIN_ROW(__sync_and_and_fetch), 3328 BUILTIN_ROW(__sync_or_and_fetch), 3329 BUILTIN_ROW(__sync_xor_and_fetch), 3330 BUILTIN_ROW(__sync_nand_and_fetch), 3331 3332 BUILTIN_ROW(__sync_val_compare_and_swap), 3333 BUILTIN_ROW(__sync_bool_compare_and_swap), 3334 BUILTIN_ROW(__sync_lock_test_and_set), 3335 BUILTIN_ROW(__sync_lock_release), 3336 BUILTIN_ROW(__sync_swap) 3337 }; 3338 #undef BUILTIN_ROW 3339 3340 // Determine the index of the size. 3341 unsigned SizeIndex; 3342 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3343 case 1: SizeIndex = 0; break; 3344 case 2: SizeIndex = 1; break; 3345 case 4: SizeIndex = 2; break; 3346 case 8: SizeIndex = 3; break; 3347 case 16: SizeIndex = 4; break; 3348 default: 3349 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3350 << FirstArg->getType() << FirstArg->getSourceRange(); 3351 return ExprError(); 3352 } 3353 3354 // Each of these builtins has one pointer argument, followed by some number of 3355 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3356 // that we ignore. Find out which row of BuiltinIndices to read from as well 3357 // as the number of fixed args. 3358 unsigned BuiltinID = FDecl->getBuiltinID(); 3359 unsigned BuiltinIndex, NumFixed = 1; 3360 bool WarnAboutSemanticsChange = false; 3361 switch (BuiltinID) { 3362 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3363 case Builtin::BI__sync_fetch_and_add: 3364 case Builtin::BI__sync_fetch_and_add_1: 3365 case Builtin::BI__sync_fetch_and_add_2: 3366 case Builtin::BI__sync_fetch_and_add_4: 3367 case Builtin::BI__sync_fetch_and_add_8: 3368 case Builtin::BI__sync_fetch_and_add_16: 3369 BuiltinIndex = 0; 3370 break; 3371 3372 case Builtin::BI__sync_fetch_and_sub: 3373 case Builtin::BI__sync_fetch_and_sub_1: 3374 case Builtin::BI__sync_fetch_and_sub_2: 3375 case Builtin::BI__sync_fetch_and_sub_4: 3376 case Builtin::BI__sync_fetch_and_sub_8: 3377 case Builtin::BI__sync_fetch_and_sub_16: 3378 BuiltinIndex = 1; 3379 break; 3380 3381 case Builtin::BI__sync_fetch_and_or: 3382 case Builtin::BI__sync_fetch_and_or_1: 3383 case Builtin::BI__sync_fetch_and_or_2: 3384 case Builtin::BI__sync_fetch_and_or_4: 3385 case Builtin::BI__sync_fetch_and_or_8: 3386 case Builtin::BI__sync_fetch_and_or_16: 3387 BuiltinIndex = 2; 3388 break; 3389 3390 case Builtin::BI__sync_fetch_and_and: 3391 case Builtin::BI__sync_fetch_and_and_1: 3392 case Builtin::BI__sync_fetch_and_and_2: 3393 case Builtin::BI__sync_fetch_and_and_4: 3394 case Builtin::BI__sync_fetch_and_and_8: 3395 case Builtin::BI__sync_fetch_and_and_16: 3396 BuiltinIndex = 3; 3397 break; 3398 3399 case Builtin::BI__sync_fetch_and_xor: 3400 case Builtin::BI__sync_fetch_and_xor_1: 3401 case Builtin::BI__sync_fetch_and_xor_2: 3402 case Builtin::BI__sync_fetch_and_xor_4: 3403 case Builtin::BI__sync_fetch_and_xor_8: 3404 case Builtin::BI__sync_fetch_and_xor_16: 3405 BuiltinIndex = 4; 3406 break; 3407 3408 case Builtin::BI__sync_fetch_and_nand: 3409 case Builtin::BI__sync_fetch_and_nand_1: 3410 case Builtin::BI__sync_fetch_and_nand_2: 3411 case Builtin::BI__sync_fetch_and_nand_4: 3412 case Builtin::BI__sync_fetch_and_nand_8: 3413 case Builtin::BI__sync_fetch_and_nand_16: 3414 BuiltinIndex = 5; 3415 WarnAboutSemanticsChange = true; 3416 break; 3417 3418 case Builtin::BI__sync_add_and_fetch: 3419 case Builtin::BI__sync_add_and_fetch_1: 3420 case Builtin::BI__sync_add_and_fetch_2: 3421 case Builtin::BI__sync_add_and_fetch_4: 3422 case Builtin::BI__sync_add_and_fetch_8: 3423 case Builtin::BI__sync_add_and_fetch_16: 3424 BuiltinIndex = 6; 3425 break; 3426 3427 case Builtin::BI__sync_sub_and_fetch: 3428 case Builtin::BI__sync_sub_and_fetch_1: 3429 case Builtin::BI__sync_sub_and_fetch_2: 3430 case Builtin::BI__sync_sub_and_fetch_4: 3431 case Builtin::BI__sync_sub_and_fetch_8: 3432 case Builtin::BI__sync_sub_and_fetch_16: 3433 BuiltinIndex = 7; 3434 break; 3435 3436 case Builtin::BI__sync_and_and_fetch: 3437 case Builtin::BI__sync_and_and_fetch_1: 3438 case Builtin::BI__sync_and_and_fetch_2: 3439 case Builtin::BI__sync_and_and_fetch_4: 3440 case Builtin::BI__sync_and_and_fetch_8: 3441 case Builtin::BI__sync_and_and_fetch_16: 3442 BuiltinIndex = 8; 3443 break; 3444 3445 case Builtin::BI__sync_or_and_fetch: 3446 case Builtin::BI__sync_or_and_fetch_1: 3447 case Builtin::BI__sync_or_and_fetch_2: 3448 case Builtin::BI__sync_or_and_fetch_4: 3449 case Builtin::BI__sync_or_and_fetch_8: 3450 case Builtin::BI__sync_or_and_fetch_16: 3451 BuiltinIndex = 9; 3452 break; 3453 3454 case Builtin::BI__sync_xor_and_fetch: 3455 case Builtin::BI__sync_xor_and_fetch_1: 3456 case Builtin::BI__sync_xor_and_fetch_2: 3457 case Builtin::BI__sync_xor_and_fetch_4: 3458 case Builtin::BI__sync_xor_and_fetch_8: 3459 case Builtin::BI__sync_xor_and_fetch_16: 3460 BuiltinIndex = 10; 3461 break; 3462 3463 case Builtin::BI__sync_nand_and_fetch: 3464 case Builtin::BI__sync_nand_and_fetch_1: 3465 case Builtin::BI__sync_nand_and_fetch_2: 3466 case Builtin::BI__sync_nand_and_fetch_4: 3467 case Builtin::BI__sync_nand_and_fetch_8: 3468 case Builtin::BI__sync_nand_and_fetch_16: 3469 BuiltinIndex = 11; 3470 WarnAboutSemanticsChange = true; 3471 break; 3472 3473 case Builtin::BI__sync_val_compare_and_swap: 3474 case Builtin::BI__sync_val_compare_and_swap_1: 3475 case Builtin::BI__sync_val_compare_and_swap_2: 3476 case Builtin::BI__sync_val_compare_and_swap_4: 3477 case Builtin::BI__sync_val_compare_and_swap_8: 3478 case Builtin::BI__sync_val_compare_and_swap_16: 3479 BuiltinIndex = 12; 3480 NumFixed = 2; 3481 break; 3482 3483 case Builtin::BI__sync_bool_compare_and_swap: 3484 case Builtin::BI__sync_bool_compare_and_swap_1: 3485 case Builtin::BI__sync_bool_compare_and_swap_2: 3486 case Builtin::BI__sync_bool_compare_and_swap_4: 3487 case Builtin::BI__sync_bool_compare_and_swap_8: 3488 case Builtin::BI__sync_bool_compare_and_swap_16: 3489 BuiltinIndex = 13; 3490 NumFixed = 2; 3491 ResultType = Context.BoolTy; 3492 break; 3493 3494 case Builtin::BI__sync_lock_test_and_set: 3495 case Builtin::BI__sync_lock_test_and_set_1: 3496 case Builtin::BI__sync_lock_test_and_set_2: 3497 case Builtin::BI__sync_lock_test_and_set_4: 3498 case Builtin::BI__sync_lock_test_and_set_8: 3499 case Builtin::BI__sync_lock_test_and_set_16: 3500 BuiltinIndex = 14; 3501 break; 3502 3503 case Builtin::BI__sync_lock_release: 3504 case Builtin::BI__sync_lock_release_1: 3505 case Builtin::BI__sync_lock_release_2: 3506 case Builtin::BI__sync_lock_release_4: 3507 case Builtin::BI__sync_lock_release_8: 3508 case Builtin::BI__sync_lock_release_16: 3509 BuiltinIndex = 15; 3510 NumFixed = 0; 3511 ResultType = Context.VoidTy; 3512 break; 3513 3514 case Builtin::BI__sync_swap: 3515 case Builtin::BI__sync_swap_1: 3516 case Builtin::BI__sync_swap_2: 3517 case Builtin::BI__sync_swap_4: 3518 case Builtin::BI__sync_swap_8: 3519 case Builtin::BI__sync_swap_16: 3520 BuiltinIndex = 16; 3521 break; 3522 } 3523 3524 // Now that we know how many fixed arguments we expect, first check that we 3525 // have at least that many. 3526 if (TheCall->getNumArgs() < 1+NumFixed) { 3527 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3528 << 0 << 1+NumFixed << TheCall->getNumArgs() 3529 << TheCall->getCallee()->getSourceRange(); 3530 return ExprError(); 3531 } 3532 3533 if (WarnAboutSemanticsChange) { 3534 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 3535 << TheCall->getCallee()->getSourceRange(); 3536 } 3537 3538 // Get the decl for the concrete builtin from this, we can tell what the 3539 // concrete integer type we should convert to is. 3540 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 3541 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 3542 FunctionDecl *NewBuiltinDecl; 3543 if (NewBuiltinID == BuiltinID) 3544 NewBuiltinDecl = FDecl; 3545 else { 3546 // Perform builtin lookup to avoid redeclaring it. 3547 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3548 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3549 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3550 assert(Res.getFoundDecl()); 3551 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3552 if (!NewBuiltinDecl) 3553 return ExprError(); 3554 } 3555 3556 // The first argument --- the pointer --- has a fixed type; we 3557 // deduce the types of the rest of the arguments accordingly. Walk 3558 // the remaining arguments, converting them to the deduced value type. 3559 for (unsigned i = 0; i != NumFixed; ++i) { 3560 ExprResult Arg = TheCall->getArg(i+1); 3561 3562 // GCC does an implicit conversion to the pointer or integer ValType. This 3563 // can fail in some cases (1i -> int**), check for this error case now. 3564 // Initialize the argument. 3565 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3566 ValType, /*consume*/ false); 3567 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3568 if (Arg.isInvalid()) 3569 return ExprError(); 3570 3571 // Okay, we have something that *can* be converted to the right type. Check 3572 // to see if there is a potentially weird extension going on here. This can 3573 // happen when you do an atomic operation on something like an char* and 3574 // pass in 42. The 42 gets converted to char. This is even more strange 3575 // for things like 45.123 -> char, etc. 3576 // FIXME: Do this check. 3577 TheCall->setArg(i+1, Arg.get()); 3578 } 3579 3580 ASTContext& Context = this->getASTContext(); 3581 3582 // Create a new DeclRefExpr to refer to the new decl. 3583 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3584 Context, 3585 DRE->getQualifierLoc(), 3586 SourceLocation(), 3587 NewBuiltinDecl, 3588 /*enclosing*/ false, 3589 DRE->getLocation(), 3590 Context.BuiltinFnTy, 3591 DRE->getValueKind()); 3592 3593 // Set the callee in the CallExpr. 3594 // FIXME: This loses syntactic information. 3595 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3596 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3597 CK_BuiltinFnToFnPtr); 3598 TheCall->setCallee(PromotedCall.get()); 3599 3600 // Change the result type of the call to match the original value type. This 3601 // is arbitrary, but the codegen for these builtins ins design to handle it 3602 // gracefully. 3603 TheCall->setType(ResultType); 3604 3605 return TheCallResult; 3606 } 3607 3608 /// SemaBuiltinNontemporalOverloaded - We have a call to 3609 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 3610 /// overloaded function based on the pointer type of its last argument. 3611 /// 3612 /// This function goes through and does final semantic checking for these 3613 /// builtins. 3614 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 3615 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3616 DeclRefExpr *DRE = 3617 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3618 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3619 unsigned BuiltinID = FDecl->getBuiltinID(); 3620 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 3621 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 3622 "Unexpected nontemporal load/store builtin!"); 3623 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 3624 unsigned numArgs = isStore ? 2 : 1; 3625 3626 // Ensure that we have the proper number of arguments. 3627 if (checkArgCount(*this, TheCall, numArgs)) 3628 return ExprError(); 3629 3630 // Inspect the last argument of the nontemporal builtin. This should always 3631 // be a pointer type, from which we imply the type of the memory access. 3632 // Because it is a pointer type, we don't have to worry about any implicit 3633 // casts here. 3634 Expr *PointerArg = TheCall->getArg(numArgs - 1); 3635 ExprResult PointerArgResult = 3636 DefaultFunctionArrayLvalueConversion(PointerArg); 3637 3638 if (PointerArgResult.isInvalid()) 3639 return ExprError(); 3640 PointerArg = PointerArgResult.get(); 3641 TheCall->setArg(numArgs - 1, PointerArg); 3642 3643 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3644 if (!pointerType) { 3645 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 3646 << PointerArg->getType() << PointerArg->getSourceRange(); 3647 return ExprError(); 3648 } 3649 3650 QualType ValType = pointerType->getPointeeType(); 3651 3652 // Strip any qualifiers off ValType. 3653 ValType = ValType.getUnqualifiedType(); 3654 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3655 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 3656 !ValType->isVectorType()) { 3657 Diag(DRE->getLocStart(), 3658 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 3659 << PointerArg->getType() << PointerArg->getSourceRange(); 3660 return ExprError(); 3661 } 3662 3663 if (!isStore) { 3664 TheCall->setType(ValType); 3665 return TheCallResult; 3666 } 3667 3668 ExprResult ValArg = TheCall->getArg(0); 3669 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3670 Context, ValType, /*consume*/ false); 3671 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3672 if (ValArg.isInvalid()) 3673 return ExprError(); 3674 3675 TheCall->setArg(0, ValArg.get()); 3676 TheCall->setType(Context.VoidTy); 3677 return TheCallResult; 3678 } 3679 3680 /// CheckObjCString - Checks that the argument to the builtin 3681 /// CFString constructor is correct 3682 /// Note: It might also make sense to do the UTF-16 conversion here (would 3683 /// simplify the backend). 3684 bool Sema::CheckObjCString(Expr *Arg) { 3685 Arg = Arg->IgnoreParenCasts(); 3686 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 3687 3688 if (!Literal || !Literal->isAscii()) { 3689 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 3690 << Arg->getSourceRange(); 3691 return true; 3692 } 3693 3694 if (Literal->containsNonAsciiOrNull()) { 3695 StringRef String = Literal->getString(); 3696 unsigned NumBytes = String.size(); 3697 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 3698 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 3699 llvm::UTF16 *ToPtr = &ToBuf[0]; 3700 3701 llvm::ConversionResult Result = 3702 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 3703 ToPtr + NumBytes, llvm::strictConversion); 3704 // Check for conversion failure. 3705 if (Result != llvm::conversionOK) 3706 Diag(Arg->getLocStart(), 3707 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 3708 } 3709 return false; 3710 } 3711 3712 /// CheckObjCString - Checks that the format string argument to the os_log() 3713 /// and os_trace() functions is correct, and converts it to const char *. 3714 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 3715 Arg = Arg->IgnoreParenCasts(); 3716 auto *Literal = dyn_cast<StringLiteral>(Arg); 3717 if (!Literal) { 3718 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 3719 Literal = ObjcLiteral->getString(); 3720 } 3721 } 3722 3723 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 3724 return ExprError( 3725 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 3726 << Arg->getSourceRange()); 3727 } 3728 3729 ExprResult Result(Literal); 3730 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 3731 InitializedEntity Entity = 3732 InitializedEntity::InitializeParameter(Context, ResultTy, false); 3733 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 3734 return Result; 3735 } 3736 3737 /// Check that the user is calling the appropriate va_start builtin for the 3738 /// target and calling convention. 3739 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 3740 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 3741 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 3742 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 3743 bool IsWindows = TT.isOSWindows(); 3744 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 3745 if (IsX64 || IsAArch64) { 3746 clang::CallingConv CC = CC_C; 3747 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 3748 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3749 if (IsMSVAStart) { 3750 // Don't allow this in System V ABI functions. 3751 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 3752 return S.Diag(Fn->getLocStart(), 3753 diag::err_ms_va_start_used_in_sysv_function); 3754 } else { 3755 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 3756 // On x64 Windows, don't allow this in System V ABI functions. 3757 // (Yes, that means there's no corresponding way to support variadic 3758 // System V ABI functions on Windows.) 3759 if ((IsWindows && CC == CC_X86_64SysV) || 3760 (!IsWindows && CC == CC_Win64)) 3761 return S.Diag(Fn->getLocStart(), 3762 diag::err_va_start_used_in_wrong_abi_function) 3763 << !IsWindows; 3764 } 3765 return false; 3766 } 3767 3768 if (IsMSVAStart) 3769 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only); 3770 return false; 3771 } 3772 3773 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 3774 ParmVarDecl **LastParam = nullptr) { 3775 // Determine whether the current function, block, or obj-c method is variadic 3776 // and get its parameter list. 3777 bool IsVariadic = false; 3778 ArrayRef<ParmVarDecl *> Params; 3779 DeclContext *Caller = S.CurContext; 3780 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 3781 IsVariadic = Block->isVariadic(); 3782 Params = Block->parameters(); 3783 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 3784 IsVariadic = FD->isVariadic(); 3785 Params = FD->parameters(); 3786 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 3787 IsVariadic = MD->isVariadic(); 3788 // FIXME: This isn't correct for methods (results in bogus warning). 3789 Params = MD->parameters(); 3790 } else if (isa<CapturedDecl>(Caller)) { 3791 // We don't support va_start in a CapturedDecl. 3792 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt); 3793 return true; 3794 } else { 3795 // This must be some other declcontext that parses exprs. 3796 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function); 3797 return true; 3798 } 3799 3800 if (!IsVariadic) { 3801 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function); 3802 return true; 3803 } 3804 3805 if (LastParam) 3806 *LastParam = Params.empty() ? nullptr : Params.back(); 3807 3808 return false; 3809 } 3810 3811 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 3812 /// for validity. Emit an error and return true on failure; return false 3813 /// on success. 3814 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 3815 Expr *Fn = TheCall->getCallee(); 3816 3817 if (checkVAStartABI(*this, BuiltinID, Fn)) 3818 return true; 3819 3820 if (TheCall->getNumArgs() > 2) { 3821 Diag(TheCall->getArg(2)->getLocStart(), 3822 diag::err_typecheck_call_too_many_args) 3823 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3824 << Fn->getSourceRange() 3825 << SourceRange(TheCall->getArg(2)->getLocStart(), 3826 (*(TheCall->arg_end()-1))->getLocEnd()); 3827 return true; 3828 } 3829 3830 if (TheCall->getNumArgs() < 2) { 3831 return Diag(TheCall->getLocEnd(), 3832 diag::err_typecheck_call_too_few_args_at_least) 3833 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 3834 } 3835 3836 // Type-check the first argument normally. 3837 if (checkBuiltinArgument(*this, TheCall, 0)) 3838 return true; 3839 3840 // Check that the current function is variadic, and get its last parameter. 3841 ParmVarDecl *LastParam; 3842 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 3843 return true; 3844 3845 // Verify that the second argument to the builtin is the last argument of the 3846 // current function or method. 3847 bool SecondArgIsLastNamedArgument = false; 3848 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 3849 3850 // These are valid if SecondArgIsLastNamedArgument is false after the next 3851 // block. 3852 QualType Type; 3853 SourceLocation ParamLoc; 3854 bool IsCRegister = false; 3855 3856 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 3857 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 3858 SecondArgIsLastNamedArgument = PV == LastParam; 3859 3860 Type = PV->getType(); 3861 ParamLoc = PV->getLocation(); 3862 IsCRegister = 3863 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 3864 } 3865 } 3866 3867 if (!SecondArgIsLastNamedArgument) 3868 Diag(TheCall->getArg(1)->getLocStart(), 3869 diag::warn_second_arg_of_va_start_not_last_named_param); 3870 else if (IsCRegister || Type->isReferenceType() || 3871 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 3872 // Promotable integers are UB, but enumerations need a bit of 3873 // extra checking to see what their promotable type actually is. 3874 if (!Type->isPromotableIntegerType()) 3875 return false; 3876 if (!Type->isEnumeralType()) 3877 return true; 3878 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 3879 return !(ED && 3880 Context.typesAreCompatible(ED->getPromotionType(), Type)); 3881 }()) { 3882 unsigned Reason = 0; 3883 if (Type->isReferenceType()) Reason = 1; 3884 else if (IsCRegister) Reason = 2; 3885 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 3886 Diag(ParamLoc, diag::note_parameter_type) << Type; 3887 } 3888 3889 TheCall->setType(Context.VoidTy); 3890 return false; 3891 } 3892 3893 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) { 3894 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 3895 // const char *named_addr); 3896 3897 Expr *Func = Call->getCallee(); 3898 3899 if (Call->getNumArgs() < 3) 3900 return Diag(Call->getLocEnd(), 3901 diag::err_typecheck_call_too_few_args_at_least) 3902 << 0 /*function call*/ << 3 << Call->getNumArgs(); 3903 3904 // Type-check the first argument normally. 3905 if (checkBuiltinArgument(*this, Call, 0)) 3906 return true; 3907 3908 // Check that the current function is variadic. 3909 if (checkVAStartIsInVariadicFunction(*this, Func)) 3910 return true; 3911 3912 const struct { 3913 unsigned ArgNo; 3914 QualType Type; 3915 } ArgumentTypes[] = { 3916 { 1, Context.getPointerType(Context.CharTy.withConst()) }, 3917 { 2, Context.getSizeType() }, 3918 }; 3919 3920 for (const auto &AT : ArgumentTypes) { 3921 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens(); 3922 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType()) 3923 continue; 3924 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible) 3925 << Arg->getType() << AT.Type << 1 /* different class */ 3926 << 0 /* qualifier difference */ << 3 /* parameter mismatch */ 3927 << AT.ArgNo + 1 << Arg->getType() << AT.Type; 3928 } 3929 3930 return false; 3931 } 3932 3933 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 3934 /// friends. This is declared to take (...), so we have to check everything. 3935 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 3936 if (TheCall->getNumArgs() < 2) 3937 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3938 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 3939 if (TheCall->getNumArgs() > 2) 3940 return Diag(TheCall->getArg(2)->getLocStart(), 3941 diag::err_typecheck_call_too_many_args) 3942 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3943 << SourceRange(TheCall->getArg(2)->getLocStart(), 3944 (*(TheCall->arg_end()-1))->getLocEnd()); 3945 3946 ExprResult OrigArg0 = TheCall->getArg(0); 3947 ExprResult OrigArg1 = TheCall->getArg(1); 3948 3949 // Do standard promotions between the two arguments, returning their common 3950 // type. 3951 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 3952 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 3953 return true; 3954 3955 // Make sure any conversions are pushed back into the call; this is 3956 // type safe since unordered compare builtins are declared as "_Bool 3957 // foo(...)". 3958 TheCall->setArg(0, OrigArg0.get()); 3959 TheCall->setArg(1, OrigArg1.get()); 3960 3961 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 3962 return false; 3963 3964 // If the common type isn't a real floating type, then the arguments were 3965 // invalid for this operation. 3966 if (Res.isNull() || !Res->isRealFloatingType()) 3967 return Diag(OrigArg0.get()->getLocStart(), 3968 diag::err_typecheck_call_invalid_ordered_compare) 3969 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 3970 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 3971 3972 return false; 3973 } 3974 3975 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 3976 /// __builtin_isnan and friends. This is declared to take (...), so we have 3977 /// to check everything. We expect the last argument to be a floating point 3978 /// value. 3979 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 3980 if (TheCall->getNumArgs() < NumArgs) 3981 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3982 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 3983 if (TheCall->getNumArgs() > NumArgs) 3984 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 3985 diag::err_typecheck_call_too_many_args) 3986 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 3987 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 3988 (*(TheCall->arg_end()-1))->getLocEnd()); 3989 3990 Expr *OrigArg = TheCall->getArg(NumArgs-1); 3991 3992 if (OrigArg->isTypeDependent()) 3993 return false; 3994 3995 // This operation requires a non-_Complex floating-point number. 3996 if (!OrigArg->getType()->isRealFloatingType()) 3997 return Diag(OrigArg->getLocStart(), 3998 diag::err_typecheck_call_invalid_unary_fp) 3999 << OrigArg->getType() << OrigArg->getSourceRange(); 4000 4001 // If this is an implicit conversion from float -> float or double, remove it. 4002 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 4003 // Only remove standard FloatCasts, leaving other casts inplace 4004 if (Cast->getCastKind() == CK_FloatingCast) { 4005 Expr *CastArg = Cast->getSubExpr(); 4006 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 4007 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 4008 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) && 4009 "promotion from float to either float or double is the only expected cast here"); 4010 Cast->setSubExpr(nullptr); 4011 TheCall->setArg(NumArgs-1, CastArg); 4012 } 4013 } 4014 } 4015 4016 return false; 4017 } 4018 4019 // Customized Sema Checking for VSX builtins that have the following signature: 4020 // vector [...] builtinName(vector [...], vector [...], const int); 4021 // Which takes the same type of vectors (any legal vector type) for the first 4022 // two arguments and takes compile time constant for the third argument. 4023 // Example builtins are : 4024 // vector double vec_xxpermdi(vector double, vector double, int); 4025 // vector short vec_xxsldwi(vector short, vector short, int); 4026 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 4027 unsigned ExpectedNumArgs = 3; 4028 if (TheCall->getNumArgs() < ExpectedNumArgs) 4029 return Diag(TheCall->getLocEnd(), 4030 diag::err_typecheck_call_too_few_args_at_least) 4031 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4032 << TheCall->getSourceRange(); 4033 4034 if (TheCall->getNumArgs() > ExpectedNumArgs) 4035 return Diag(TheCall->getLocEnd(), 4036 diag::err_typecheck_call_too_many_args_at_most) 4037 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4038 << TheCall->getSourceRange(); 4039 4040 // Check the third argument is a compile time constant 4041 llvm::APSInt Value; 4042 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 4043 return Diag(TheCall->getLocStart(), 4044 diag::err_vsx_builtin_nonconstant_argument) 4045 << 3 /* argument index */ << TheCall->getDirectCallee() 4046 << SourceRange(TheCall->getArg(2)->getLocStart(), 4047 TheCall->getArg(2)->getLocEnd()); 4048 4049 QualType Arg1Ty = TheCall->getArg(0)->getType(); 4050 QualType Arg2Ty = TheCall->getArg(1)->getType(); 4051 4052 // Check the type of argument 1 and argument 2 are vectors. 4053 SourceLocation BuiltinLoc = TheCall->getLocStart(); 4054 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 4055 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 4056 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 4057 << TheCall->getDirectCallee() 4058 << SourceRange(TheCall->getArg(0)->getLocStart(), 4059 TheCall->getArg(1)->getLocEnd()); 4060 } 4061 4062 // Check the first two arguments are the same type. 4063 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 4064 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 4065 << TheCall->getDirectCallee() 4066 << SourceRange(TheCall->getArg(0)->getLocStart(), 4067 TheCall->getArg(1)->getLocEnd()); 4068 } 4069 4070 // When default clang type checking is turned off and the customized type 4071 // checking is used, the returning type of the function must be explicitly 4072 // set. Otherwise it is _Bool by default. 4073 TheCall->setType(Arg1Ty); 4074 4075 return false; 4076 } 4077 4078 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 4079 // This is declared to take (...), so we have to check everything. 4080 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 4081 if (TheCall->getNumArgs() < 2) 4082 return ExprError(Diag(TheCall->getLocEnd(), 4083 diag::err_typecheck_call_too_few_args_at_least) 4084 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4085 << TheCall->getSourceRange()); 4086 4087 // Determine which of the following types of shufflevector we're checking: 4088 // 1) unary, vector mask: (lhs, mask) 4089 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 4090 QualType resType = TheCall->getArg(0)->getType(); 4091 unsigned numElements = 0; 4092 4093 if (!TheCall->getArg(0)->isTypeDependent() && 4094 !TheCall->getArg(1)->isTypeDependent()) { 4095 QualType LHSType = TheCall->getArg(0)->getType(); 4096 QualType RHSType = TheCall->getArg(1)->getType(); 4097 4098 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 4099 return ExprError(Diag(TheCall->getLocStart(), 4100 diag::err_vec_builtin_non_vector) 4101 << TheCall->getDirectCallee() 4102 << SourceRange(TheCall->getArg(0)->getLocStart(), 4103 TheCall->getArg(1)->getLocEnd())); 4104 4105 numElements = LHSType->getAs<VectorType>()->getNumElements(); 4106 unsigned numResElements = TheCall->getNumArgs() - 2; 4107 4108 // Check to see if we have a call with 2 vector arguments, the unary shuffle 4109 // with mask. If so, verify that RHS is an integer vector type with the 4110 // same number of elts as lhs. 4111 if (TheCall->getNumArgs() == 2) { 4112 if (!RHSType->hasIntegerRepresentation() || 4113 RHSType->getAs<VectorType>()->getNumElements() != numElements) 4114 return ExprError(Diag(TheCall->getLocStart(), 4115 diag::err_vec_builtin_incompatible_vector) 4116 << TheCall->getDirectCallee() 4117 << SourceRange(TheCall->getArg(1)->getLocStart(), 4118 TheCall->getArg(1)->getLocEnd())); 4119 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 4120 return ExprError(Diag(TheCall->getLocStart(), 4121 diag::err_vec_builtin_incompatible_vector) 4122 << TheCall->getDirectCallee() 4123 << SourceRange(TheCall->getArg(0)->getLocStart(), 4124 TheCall->getArg(1)->getLocEnd())); 4125 } else if (numElements != numResElements) { 4126 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 4127 resType = Context.getVectorType(eltType, numResElements, 4128 VectorType::GenericVector); 4129 } 4130 } 4131 4132 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 4133 if (TheCall->getArg(i)->isTypeDependent() || 4134 TheCall->getArg(i)->isValueDependent()) 4135 continue; 4136 4137 llvm::APSInt Result(32); 4138 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 4139 return ExprError(Diag(TheCall->getLocStart(), 4140 diag::err_shufflevector_nonconstant_argument) 4141 << TheCall->getArg(i)->getSourceRange()); 4142 4143 // Allow -1 which will be translated to undef in the IR. 4144 if (Result.isSigned() && Result.isAllOnesValue()) 4145 continue; 4146 4147 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 4148 return ExprError(Diag(TheCall->getLocStart(), 4149 diag::err_shufflevector_argument_too_large) 4150 << TheCall->getArg(i)->getSourceRange()); 4151 } 4152 4153 SmallVector<Expr*, 32> exprs; 4154 4155 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 4156 exprs.push_back(TheCall->getArg(i)); 4157 TheCall->setArg(i, nullptr); 4158 } 4159 4160 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 4161 TheCall->getCallee()->getLocStart(), 4162 TheCall->getRParenLoc()); 4163 } 4164 4165 /// SemaConvertVectorExpr - Handle __builtin_convertvector 4166 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 4167 SourceLocation BuiltinLoc, 4168 SourceLocation RParenLoc) { 4169 ExprValueKind VK = VK_RValue; 4170 ExprObjectKind OK = OK_Ordinary; 4171 QualType DstTy = TInfo->getType(); 4172 QualType SrcTy = E->getType(); 4173 4174 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 4175 return ExprError(Diag(BuiltinLoc, 4176 diag::err_convertvector_non_vector) 4177 << E->getSourceRange()); 4178 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 4179 return ExprError(Diag(BuiltinLoc, 4180 diag::err_convertvector_non_vector_type)); 4181 4182 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 4183 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 4184 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 4185 if (SrcElts != DstElts) 4186 return ExprError(Diag(BuiltinLoc, 4187 diag::err_convertvector_incompatible_vector) 4188 << E->getSourceRange()); 4189 } 4190 4191 return new (Context) 4192 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4193 } 4194 4195 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 4196 // This is declared to take (const void*, ...) and can take two 4197 // optional constant int args. 4198 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 4199 unsigned NumArgs = TheCall->getNumArgs(); 4200 4201 if (NumArgs > 3) 4202 return Diag(TheCall->getLocEnd(), 4203 diag::err_typecheck_call_too_many_args_at_most) 4204 << 0 /*function call*/ << 3 << NumArgs 4205 << TheCall->getSourceRange(); 4206 4207 // Argument 0 is checked for us and the remaining arguments must be 4208 // constant integers. 4209 for (unsigned i = 1; i != NumArgs; ++i) 4210 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 4211 return true; 4212 4213 return false; 4214 } 4215 4216 /// SemaBuiltinAssume - Handle __assume (MS Extension). 4217 // __assume does not evaluate its arguments, and should warn if its argument 4218 // has side effects. 4219 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 4220 Expr *Arg = TheCall->getArg(0); 4221 if (Arg->isInstantiationDependent()) return false; 4222 4223 if (Arg->HasSideEffects(Context)) 4224 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 4225 << Arg->getSourceRange() 4226 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 4227 4228 return false; 4229 } 4230 4231 /// Handle __builtin_alloca_with_align. This is declared 4232 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 4233 /// than 8. 4234 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 4235 // The alignment must be a constant integer. 4236 Expr *Arg = TheCall->getArg(1); 4237 4238 // We can't check the value of a dependent argument. 4239 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4240 if (const auto *UE = 4241 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 4242 if (UE->getKind() == UETT_AlignOf) 4243 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 4244 << Arg->getSourceRange(); 4245 4246 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 4247 4248 if (!Result.isPowerOf2()) 4249 return Diag(TheCall->getLocStart(), 4250 diag::err_alignment_not_power_of_two) 4251 << Arg->getSourceRange(); 4252 4253 if (Result < Context.getCharWidth()) 4254 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 4255 << (unsigned)Context.getCharWidth() 4256 << Arg->getSourceRange(); 4257 4258 if (Result > INT32_MAX) 4259 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 4260 << INT32_MAX 4261 << Arg->getSourceRange(); 4262 } 4263 4264 return false; 4265 } 4266 4267 /// Handle __builtin_assume_aligned. This is declared 4268 /// as (const void*, size_t, ...) and can take one optional constant int arg. 4269 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 4270 unsigned NumArgs = TheCall->getNumArgs(); 4271 4272 if (NumArgs > 3) 4273 return Diag(TheCall->getLocEnd(), 4274 diag::err_typecheck_call_too_many_args_at_most) 4275 << 0 /*function call*/ << 3 << NumArgs 4276 << TheCall->getSourceRange(); 4277 4278 // The alignment must be a constant integer. 4279 Expr *Arg = TheCall->getArg(1); 4280 4281 // We can't check the value of a dependent argument. 4282 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4283 llvm::APSInt Result; 4284 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4285 return true; 4286 4287 if (!Result.isPowerOf2()) 4288 return Diag(TheCall->getLocStart(), 4289 diag::err_alignment_not_power_of_two) 4290 << Arg->getSourceRange(); 4291 } 4292 4293 if (NumArgs > 2) { 4294 ExprResult Arg(TheCall->getArg(2)); 4295 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4296 Context.getSizeType(), false); 4297 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4298 if (Arg.isInvalid()) return true; 4299 TheCall->setArg(2, Arg.get()); 4300 } 4301 4302 return false; 4303 } 4304 4305 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 4306 unsigned BuiltinID = 4307 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 4308 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 4309 4310 unsigned NumArgs = TheCall->getNumArgs(); 4311 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 4312 if (NumArgs < NumRequiredArgs) { 4313 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4314 << 0 /* function call */ << NumRequiredArgs << NumArgs 4315 << TheCall->getSourceRange(); 4316 } 4317 if (NumArgs >= NumRequiredArgs + 0x100) { 4318 return Diag(TheCall->getLocEnd(), 4319 diag::err_typecheck_call_too_many_args_at_most) 4320 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 4321 << TheCall->getSourceRange(); 4322 } 4323 unsigned i = 0; 4324 4325 // For formatting call, check buffer arg. 4326 if (!IsSizeCall) { 4327 ExprResult Arg(TheCall->getArg(i)); 4328 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4329 Context, Context.VoidPtrTy, false); 4330 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4331 if (Arg.isInvalid()) 4332 return true; 4333 TheCall->setArg(i, Arg.get()); 4334 i++; 4335 } 4336 4337 // Check string literal arg. 4338 unsigned FormatIdx = i; 4339 { 4340 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4341 if (Arg.isInvalid()) 4342 return true; 4343 TheCall->setArg(i, Arg.get()); 4344 i++; 4345 } 4346 4347 // Make sure variadic args are scalar. 4348 unsigned FirstDataArg = i; 4349 while (i < NumArgs) { 4350 ExprResult Arg = DefaultVariadicArgumentPromotion( 4351 TheCall->getArg(i), VariadicFunction, nullptr); 4352 if (Arg.isInvalid()) 4353 return true; 4354 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4355 if (ArgSize.getQuantity() >= 0x100) { 4356 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4357 << i << (int)ArgSize.getQuantity() << 0xff 4358 << TheCall->getSourceRange(); 4359 } 4360 TheCall->setArg(i, Arg.get()); 4361 i++; 4362 } 4363 4364 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4365 // call to avoid duplicate diagnostics. 4366 if (!IsSizeCall) { 4367 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4368 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4369 bool Success = CheckFormatArguments( 4370 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4371 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4372 CheckedVarArgs); 4373 if (!Success) 4374 return true; 4375 } 4376 4377 if (IsSizeCall) { 4378 TheCall->setType(Context.getSizeType()); 4379 } else { 4380 TheCall->setType(Context.VoidPtrTy); 4381 } 4382 return false; 4383 } 4384 4385 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4386 /// TheCall is a constant expression. 4387 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4388 llvm::APSInt &Result) { 4389 Expr *Arg = TheCall->getArg(ArgNum); 4390 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4391 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4392 4393 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4394 4395 if (!Arg->isIntegerConstantExpr(Result, Context)) 4396 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 4397 << FDecl->getDeclName() << Arg->getSourceRange(); 4398 4399 return false; 4400 } 4401 4402 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 4403 /// TheCall is a constant expression in the range [Low, High]. 4404 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 4405 int Low, int High) { 4406 llvm::APSInt Result; 4407 4408 // We can't check the value of a dependent argument. 4409 Expr *Arg = TheCall->getArg(ArgNum); 4410 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4411 return false; 4412 4413 // Check constant-ness first. 4414 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4415 return true; 4416 4417 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 4418 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 4419 << Low << High << Arg->getSourceRange(); 4420 4421 return false; 4422 } 4423 4424 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 4425 /// TheCall is a constant expression is a multiple of Num.. 4426 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 4427 unsigned Num) { 4428 llvm::APSInt Result; 4429 4430 // We can't check the value of a dependent argument. 4431 Expr *Arg = TheCall->getArg(ArgNum); 4432 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4433 return false; 4434 4435 // Check constant-ness first. 4436 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4437 return true; 4438 4439 if (Result.getSExtValue() % Num != 0) 4440 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 4441 << Num << Arg->getSourceRange(); 4442 4443 return false; 4444 } 4445 4446 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 4447 /// TheCall is an ARM/AArch64 special register string literal. 4448 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 4449 int ArgNum, unsigned ExpectedFieldNum, 4450 bool AllowName) { 4451 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 4452 BuiltinID == ARM::BI__builtin_arm_wsr64 || 4453 BuiltinID == ARM::BI__builtin_arm_rsr || 4454 BuiltinID == ARM::BI__builtin_arm_rsrp || 4455 BuiltinID == ARM::BI__builtin_arm_wsr || 4456 BuiltinID == ARM::BI__builtin_arm_wsrp; 4457 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 4458 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 4459 BuiltinID == AArch64::BI__builtin_arm_rsr || 4460 BuiltinID == AArch64::BI__builtin_arm_rsrp || 4461 BuiltinID == AArch64::BI__builtin_arm_wsr || 4462 BuiltinID == AArch64::BI__builtin_arm_wsrp; 4463 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 4464 4465 // We can't check the value of a dependent argument. 4466 Expr *Arg = TheCall->getArg(ArgNum); 4467 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4468 return false; 4469 4470 // Check if the argument is a string literal. 4471 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4472 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 4473 << Arg->getSourceRange(); 4474 4475 // Check the type of special register given. 4476 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4477 SmallVector<StringRef, 6> Fields; 4478 Reg.split(Fields, ":"); 4479 4480 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 4481 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4482 << Arg->getSourceRange(); 4483 4484 // If the string is the name of a register then we cannot check that it is 4485 // valid here but if the string is of one the forms described in ACLE then we 4486 // can check that the supplied fields are integers and within the valid 4487 // ranges. 4488 if (Fields.size() > 1) { 4489 bool FiveFields = Fields.size() == 5; 4490 4491 bool ValidString = true; 4492 if (IsARMBuiltin) { 4493 ValidString &= Fields[0].startswith_lower("cp") || 4494 Fields[0].startswith_lower("p"); 4495 if (ValidString) 4496 Fields[0] = 4497 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 4498 4499 ValidString &= Fields[2].startswith_lower("c"); 4500 if (ValidString) 4501 Fields[2] = Fields[2].drop_front(1); 4502 4503 if (FiveFields) { 4504 ValidString &= Fields[3].startswith_lower("c"); 4505 if (ValidString) 4506 Fields[3] = Fields[3].drop_front(1); 4507 } 4508 } 4509 4510 SmallVector<int, 5> Ranges; 4511 if (FiveFields) 4512 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 4513 else 4514 Ranges.append({15, 7, 15}); 4515 4516 for (unsigned i=0; i<Fields.size(); ++i) { 4517 int IntField; 4518 ValidString &= !Fields[i].getAsInteger(10, IntField); 4519 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 4520 } 4521 4522 if (!ValidString) 4523 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4524 << Arg->getSourceRange(); 4525 4526 } else if (IsAArch64Builtin && Fields.size() == 1) { 4527 // If the register name is one of those that appear in the condition below 4528 // and the special register builtin being used is one of the write builtins, 4529 // then we require that the argument provided for writing to the register 4530 // is an integer constant expression. This is because it will be lowered to 4531 // an MSR (immediate) instruction, so we need to know the immediate at 4532 // compile time. 4533 if (TheCall->getNumArgs() != 2) 4534 return false; 4535 4536 std::string RegLower = Reg.lower(); 4537 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 4538 RegLower != "pan" && RegLower != "uao") 4539 return false; 4540 4541 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4542 } 4543 4544 return false; 4545 } 4546 4547 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 4548 /// This checks that the target supports __builtin_longjmp and 4549 /// that val is a constant 1. 4550 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 4551 if (!Context.getTargetInfo().hasSjLjLowering()) 4552 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 4553 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4554 4555 Expr *Arg = TheCall->getArg(1); 4556 llvm::APSInt Result; 4557 4558 // TODO: This is less than ideal. Overload this to take a value. 4559 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4560 return true; 4561 4562 if (Result != 1) 4563 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 4564 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 4565 4566 return false; 4567 } 4568 4569 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 4570 /// This checks that the target supports __builtin_setjmp. 4571 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 4572 if (!Context.getTargetInfo().hasSjLjLowering()) 4573 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 4574 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4575 return false; 4576 } 4577 4578 namespace { 4579 class UncoveredArgHandler { 4580 enum { Unknown = -1, AllCovered = -2 }; 4581 signed FirstUncoveredArg; 4582 SmallVector<const Expr *, 4> DiagnosticExprs; 4583 4584 public: 4585 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { } 4586 4587 bool hasUncoveredArg() const { 4588 return (FirstUncoveredArg >= 0); 4589 } 4590 4591 unsigned getUncoveredArg() const { 4592 assert(hasUncoveredArg() && "no uncovered argument"); 4593 return FirstUncoveredArg; 4594 } 4595 4596 void setAllCovered() { 4597 // A string has been found with all arguments covered, so clear out 4598 // the diagnostics. 4599 DiagnosticExprs.clear(); 4600 FirstUncoveredArg = AllCovered; 4601 } 4602 4603 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 4604 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 4605 4606 // Don't update if a previous string covers all arguments. 4607 if (FirstUncoveredArg == AllCovered) 4608 return; 4609 4610 // UncoveredArgHandler tracks the highest uncovered argument index 4611 // and with it all the strings that match this index. 4612 if (NewFirstUncoveredArg == FirstUncoveredArg) 4613 DiagnosticExprs.push_back(StrExpr); 4614 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 4615 DiagnosticExprs.clear(); 4616 DiagnosticExprs.push_back(StrExpr); 4617 FirstUncoveredArg = NewFirstUncoveredArg; 4618 } 4619 } 4620 4621 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 4622 }; 4623 4624 enum StringLiteralCheckType { 4625 SLCT_NotALiteral, 4626 SLCT_UncheckedLiteral, 4627 SLCT_CheckedLiteral 4628 }; 4629 } // end anonymous namespace 4630 4631 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 4632 BinaryOperatorKind BinOpKind, 4633 bool AddendIsRight) { 4634 unsigned BitWidth = Offset.getBitWidth(); 4635 unsigned AddendBitWidth = Addend.getBitWidth(); 4636 // There might be negative interim results. 4637 if (Addend.isUnsigned()) { 4638 Addend = Addend.zext(++AddendBitWidth); 4639 Addend.setIsSigned(true); 4640 } 4641 // Adjust the bit width of the APSInts. 4642 if (AddendBitWidth > BitWidth) { 4643 Offset = Offset.sext(AddendBitWidth); 4644 BitWidth = AddendBitWidth; 4645 } else if (BitWidth > AddendBitWidth) { 4646 Addend = Addend.sext(BitWidth); 4647 } 4648 4649 bool Ov = false; 4650 llvm::APSInt ResOffset = Offset; 4651 if (BinOpKind == BO_Add) 4652 ResOffset = Offset.sadd_ov(Addend, Ov); 4653 else { 4654 assert(AddendIsRight && BinOpKind == BO_Sub && 4655 "operator must be add or sub with addend on the right"); 4656 ResOffset = Offset.ssub_ov(Addend, Ov); 4657 } 4658 4659 // We add an offset to a pointer here so we should support an offset as big as 4660 // possible. 4661 if (Ov) { 4662 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big"); 4663 Offset = Offset.sext(2 * BitWidth); 4664 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 4665 return; 4666 } 4667 4668 Offset = ResOffset; 4669 } 4670 4671 namespace { 4672 // This is a wrapper class around StringLiteral to support offsetted string 4673 // literals as format strings. It takes the offset into account when returning 4674 // the string and its length or the source locations to display notes correctly. 4675 class FormatStringLiteral { 4676 const StringLiteral *FExpr; 4677 int64_t Offset; 4678 4679 public: 4680 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 4681 : FExpr(fexpr), Offset(Offset) {} 4682 4683 StringRef getString() const { 4684 return FExpr->getString().drop_front(Offset); 4685 } 4686 4687 unsigned getByteLength() const { 4688 return FExpr->getByteLength() - getCharByteWidth() * Offset; 4689 } 4690 unsigned getLength() const { return FExpr->getLength() - Offset; } 4691 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 4692 4693 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 4694 4695 QualType getType() const { return FExpr->getType(); } 4696 4697 bool isAscii() const { return FExpr->isAscii(); } 4698 bool isWide() const { return FExpr->isWide(); } 4699 bool isUTF8() const { return FExpr->isUTF8(); } 4700 bool isUTF16() const { return FExpr->isUTF16(); } 4701 bool isUTF32() const { return FExpr->isUTF32(); } 4702 bool isPascal() const { return FExpr->isPascal(); } 4703 4704 SourceLocation getLocationOfByte( 4705 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 4706 const TargetInfo &Target, unsigned *StartToken = nullptr, 4707 unsigned *StartTokenByteOffset = nullptr) const { 4708 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 4709 StartToken, StartTokenByteOffset); 4710 } 4711 4712 SourceLocation getLocStart() const LLVM_READONLY { 4713 return FExpr->getLocStart().getLocWithOffset(Offset); 4714 } 4715 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 4716 }; 4717 } // end anonymous namespace 4718 4719 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 4720 const Expr *OrigFormatExpr, 4721 ArrayRef<const Expr *> Args, 4722 bool HasVAListArg, unsigned format_idx, 4723 unsigned firstDataArg, 4724 Sema::FormatStringType Type, 4725 bool inFunctionCall, 4726 Sema::VariadicCallType CallType, 4727 llvm::SmallBitVector &CheckedVarArgs, 4728 UncoveredArgHandler &UncoveredArg); 4729 4730 // Determine if an expression is a string literal or constant string. 4731 // If this function returns false on the arguments to a function expecting a 4732 // format string, we will usually need to emit a warning. 4733 // True string literals are then checked by CheckFormatString. 4734 static StringLiteralCheckType 4735 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 4736 bool HasVAListArg, unsigned format_idx, 4737 unsigned firstDataArg, Sema::FormatStringType Type, 4738 Sema::VariadicCallType CallType, bool InFunctionCall, 4739 llvm::SmallBitVector &CheckedVarArgs, 4740 UncoveredArgHandler &UncoveredArg, 4741 llvm::APSInt Offset) { 4742 tryAgain: 4743 assert(Offset.isSigned() && "invalid offset"); 4744 4745 if (E->isTypeDependent() || E->isValueDependent()) 4746 return SLCT_NotALiteral; 4747 4748 E = E->IgnoreParenCasts(); 4749 4750 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 4751 // Technically -Wformat-nonliteral does not warn about this case. 4752 // The behavior of printf and friends in this case is implementation 4753 // dependent. Ideally if the format string cannot be null then 4754 // it should have a 'nonnull' attribute in the function prototype. 4755 return SLCT_UncheckedLiteral; 4756 4757 switch (E->getStmtClass()) { 4758 case Stmt::BinaryConditionalOperatorClass: 4759 case Stmt::ConditionalOperatorClass: { 4760 // The expression is a literal if both sub-expressions were, and it was 4761 // completely checked only if both sub-expressions were checked. 4762 const AbstractConditionalOperator *C = 4763 cast<AbstractConditionalOperator>(E); 4764 4765 // Determine whether it is necessary to check both sub-expressions, for 4766 // example, because the condition expression is a constant that can be 4767 // evaluated at compile time. 4768 bool CheckLeft = true, CheckRight = true; 4769 4770 bool Cond; 4771 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 4772 if (Cond) 4773 CheckRight = false; 4774 else 4775 CheckLeft = false; 4776 } 4777 4778 // We need to maintain the offsets for the right and the left hand side 4779 // separately to check if every possible indexed expression is a valid 4780 // string literal. They might have different offsets for different string 4781 // literals in the end. 4782 StringLiteralCheckType Left; 4783 if (!CheckLeft) 4784 Left = SLCT_UncheckedLiteral; 4785 else { 4786 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 4787 HasVAListArg, format_idx, firstDataArg, 4788 Type, CallType, InFunctionCall, 4789 CheckedVarArgs, UncoveredArg, Offset); 4790 if (Left == SLCT_NotALiteral || !CheckRight) { 4791 return Left; 4792 } 4793 } 4794 4795 StringLiteralCheckType Right = 4796 checkFormatStringExpr(S, C->getFalseExpr(), Args, 4797 HasVAListArg, format_idx, firstDataArg, 4798 Type, CallType, InFunctionCall, CheckedVarArgs, 4799 UncoveredArg, Offset); 4800 4801 return (CheckLeft && Left < Right) ? Left : Right; 4802 } 4803 4804 case Stmt::ImplicitCastExprClass: { 4805 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4806 goto tryAgain; 4807 } 4808 4809 case Stmt::OpaqueValueExprClass: 4810 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 4811 E = src; 4812 goto tryAgain; 4813 } 4814 return SLCT_NotALiteral; 4815 4816 case Stmt::PredefinedExprClass: 4817 // While __func__, etc., are technically not string literals, they 4818 // cannot contain format specifiers and thus are not a security 4819 // liability. 4820 return SLCT_UncheckedLiteral; 4821 4822 case Stmt::DeclRefExprClass: { 4823 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 4824 4825 // As an exception, do not flag errors for variables binding to 4826 // const string literals. 4827 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 4828 bool isConstant = false; 4829 QualType T = DR->getType(); 4830 4831 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 4832 isConstant = AT->getElementType().isConstant(S.Context); 4833 } else if (const PointerType *PT = T->getAs<PointerType>()) { 4834 isConstant = T.isConstant(S.Context) && 4835 PT->getPointeeType().isConstant(S.Context); 4836 } else if (T->isObjCObjectPointerType()) { 4837 // In ObjC, there is usually no "const ObjectPointer" type, 4838 // so don't check if the pointee type is constant. 4839 isConstant = T.isConstant(S.Context); 4840 } 4841 4842 if (isConstant) { 4843 if (const Expr *Init = VD->getAnyInitializer()) { 4844 // Look through initializers like const char c[] = { "foo" } 4845 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4846 if (InitList->isStringLiteralInit()) 4847 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 4848 } 4849 return checkFormatStringExpr(S, Init, Args, 4850 HasVAListArg, format_idx, 4851 firstDataArg, Type, CallType, 4852 /*InFunctionCall*/ false, CheckedVarArgs, 4853 UncoveredArg, Offset); 4854 } 4855 } 4856 4857 // For vprintf* functions (i.e., HasVAListArg==true), we add a 4858 // special check to see if the format string is a function parameter 4859 // of the function calling the printf function. If the function 4860 // has an attribute indicating it is a printf-like function, then we 4861 // should suppress warnings concerning non-literals being used in a call 4862 // to a vprintf function. For example: 4863 // 4864 // void 4865 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 4866 // va_list ap; 4867 // va_start(ap, fmt); 4868 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 4869 // ... 4870 // } 4871 if (HasVAListArg) { 4872 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 4873 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 4874 int PVIndex = PV->getFunctionScopeIndex() + 1; 4875 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 4876 // adjust for implicit parameter 4877 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4878 if (MD->isInstance()) 4879 ++PVIndex; 4880 // We also check if the formats are compatible. 4881 // We can't pass a 'scanf' string to a 'printf' function. 4882 if (PVIndex == PVFormat->getFormatIdx() && 4883 Type == S.GetFormatStringType(PVFormat)) 4884 return SLCT_UncheckedLiteral; 4885 } 4886 } 4887 } 4888 } 4889 } 4890 4891 return SLCT_NotALiteral; 4892 } 4893 4894 case Stmt::CallExprClass: 4895 case Stmt::CXXMemberCallExprClass: { 4896 const CallExpr *CE = cast<CallExpr>(E); 4897 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 4898 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 4899 unsigned ArgIndex = FA->getFormatIdx(); 4900 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4901 if (MD->isInstance()) 4902 --ArgIndex; 4903 const Expr *Arg = CE->getArg(ArgIndex - 1); 4904 4905 return checkFormatStringExpr(S, Arg, Args, 4906 HasVAListArg, format_idx, firstDataArg, 4907 Type, CallType, InFunctionCall, 4908 CheckedVarArgs, UncoveredArg, Offset); 4909 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 4910 unsigned BuiltinID = FD->getBuiltinID(); 4911 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 4912 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 4913 const Expr *Arg = CE->getArg(0); 4914 return checkFormatStringExpr(S, Arg, Args, 4915 HasVAListArg, format_idx, 4916 firstDataArg, Type, CallType, 4917 InFunctionCall, CheckedVarArgs, 4918 UncoveredArg, Offset); 4919 } 4920 } 4921 } 4922 4923 return SLCT_NotALiteral; 4924 } 4925 case Stmt::ObjCMessageExprClass: { 4926 const auto *ME = cast<ObjCMessageExpr>(E); 4927 if (const auto *ND = ME->getMethodDecl()) { 4928 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 4929 unsigned ArgIndex = FA->getFormatIdx(); 4930 const Expr *Arg = ME->getArg(ArgIndex - 1); 4931 return checkFormatStringExpr( 4932 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 4933 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 4934 } 4935 } 4936 4937 return SLCT_NotALiteral; 4938 } 4939 case Stmt::ObjCStringLiteralClass: 4940 case Stmt::StringLiteralClass: { 4941 const StringLiteral *StrE = nullptr; 4942 4943 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 4944 StrE = ObjCFExpr->getString(); 4945 else 4946 StrE = cast<StringLiteral>(E); 4947 4948 if (StrE) { 4949 if (Offset.isNegative() || Offset > StrE->getLength()) { 4950 // TODO: It would be better to have an explicit warning for out of 4951 // bounds literals. 4952 return SLCT_NotALiteral; 4953 } 4954 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 4955 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 4956 firstDataArg, Type, InFunctionCall, CallType, 4957 CheckedVarArgs, UncoveredArg); 4958 return SLCT_CheckedLiteral; 4959 } 4960 4961 return SLCT_NotALiteral; 4962 } 4963 case Stmt::BinaryOperatorClass: { 4964 llvm::APSInt LResult; 4965 llvm::APSInt RResult; 4966 4967 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 4968 4969 // A string literal + an int offset is still a string literal. 4970 if (BinOp->isAdditiveOp()) { 4971 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 4972 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 4973 4974 if (LIsInt != RIsInt) { 4975 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 4976 4977 if (LIsInt) { 4978 if (BinOpKind == BO_Add) { 4979 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 4980 E = BinOp->getRHS(); 4981 goto tryAgain; 4982 } 4983 } else { 4984 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 4985 E = BinOp->getLHS(); 4986 goto tryAgain; 4987 } 4988 } 4989 } 4990 4991 return SLCT_NotALiteral; 4992 } 4993 case Stmt::UnaryOperatorClass: { 4994 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 4995 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 4996 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) { 4997 llvm::APSInt IndexResult; 4998 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 4999 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 5000 E = ASE->getBase(); 5001 goto tryAgain; 5002 } 5003 } 5004 5005 return SLCT_NotALiteral; 5006 } 5007 5008 default: 5009 return SLCT_NotALiteral; 5010 } 5011 } 5012 5013 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 5014 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 5015 .Case("scanf", FST_Scanf) 5016 .Cases("printf", "printf0", FST_Printf) 5017 .Cases("NSString", "CFString", FST_NSString) 5018 .Case("strftime", FST_Strftime) 5019 .Case("strfmon", FST_Strfmon) 5020 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 5021 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 5022 .Case("os_trace", FST_OSLog) 5023 .Case("os_log", FST_OSLog) 5024 .Default(FST_Unknown); 5025 } 5026 5027 /// CheckFormatArguments - Check calls to printf and scanf (and similar 5028 /// functions) for correct use of format strings. 5029 /// Returns true if a format string has been fully checked. 5030 bool Sema::CheckFormatArguments(const FormatAttr *Format, 5031 ArrayRef<const Expr *> Args, 5032 bool IsCXXMember, 5033 VariadicCallType CallType, 5034 SourceLocation Loc, SourceRange Range, 5035 llvm::SmallBitVector &CheckedVarArgs) { 5036 FormatStringInfo FSI; 5037 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 5038 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 5039 FSI.FirstDataArg, GetFormatStringType(Format), 5040 CallType, Loc, Range, CheckedVarArgs); 5041 return false; 5042 } 5043 5044 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 5045 bool HasVAListArg, unsigned format_idx, 5046 unsigned firstDataArg, FormatStringType Type, 5047 VariadicCallType CallType, 5048 SourceLocation Loc, SourceRange Range, 5049 llvm::SmallBitVector &CheckedVarArgs) { 5050 // CHECK: printf/scanf-like function is called with no format string. 5051 if (format_idx >= Args.size()) { 5052 Diag(Loc, diag::warn_missing_format_string) << Range; 5053 return false; 5054 } 5055 5056 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 5057 5058 // CHECK: format string is not a string literal. 5059 // 5060 // Dynamically generated format strings are difficult to 5061 // automatically vet at compile time. Requiring that format strings 5062 // are string literals: (1) permits the checking of format strings by 5063 // the compiler and thereby (2) can practically remove the source of 5064 // many format string exploits. 5065 5066 // Format string can be either ObjC string (e.g. @"%d") or 5067 // C string (e.g. "%d") 5068 // ObjC string uses the same format specifiers as C string, so we can use 5069 // the same format string checking logic for both ObjC and C strings. 5070 UncoveredArgHandler UncoveredArg; 5071 StringLiteralCheckType CT = 5072 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 5073 format_idx, firstDataArg, Type, CallType, 5074 /*IsFunctionCall*/ true, CheckedVarArgs, 5075 UncoveredArg, 5076 /*no string offset*/ llvm::APSInt(64, false) = 0); 5077 5078 // Generate a diagnostic where an uncovered argument is detected. 5079 if (UncoveredArg.hasUncoveredArg()) { 5080 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 5081 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 5082 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 5083 } 5084 5085 if (CT != SLCT_NotALiteral) 5086 // Literal format string found, check done! 5087 return CT == SLCT_CheckedLiteral; 5088 5089 // Strftime is particular as it always uses a single 'time' argument, 5090 // so it is safe to pass a non-literal string. 5091 if (Type == FST_Strftime) 5092 return false; 5093 5094 // Do not emit diag when the string param is a macro expansion and the 5095 // format is either NSString or CFString. This is a hack to prevent 5096 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 5097 // which are usually used in place of NS and CF string literals. 5098 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 5099 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 5100 return false; 5101 5102 // If there are no arguments specified, warn with -Wformat-security, otherwise 5103 // warn only with -Wformat-nonliteral. 5104 if (Args.size() == firstDataArg) { 5105 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 5106 << OrigFormatExpr->getSourceRange(); 5107 switch (Type) { 5108 default: 5109 break; 5110 case FST_Kprintf: 5111 case FST_FreeBSDKPrintf: 5112 case FST_Printf: 5113 Diag(FormatLoc, diag::note_format_security_fixit) 5114 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 5115 break; 5116 case FST_NSString: 5117 Diag(FormatLoc, diag::note_format_security_fixit) 5118 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 5119 break; 5120 } 5121 } else { 5122 Diag(FormatLoc, diag::warn_format_nonliteral) 5123 << OrigFormatExpr->getSourceRange(); 5124 } 5125 return false; 5126 } 5127 5128 namespace { 5129 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 5130 protected: 5131 Sema &S; 5132 const FormatStringLiteral *FExpr; 5133 const Expr *OrigFormatExpr; 5134 const Sema::FormatStringType FSType; 5135 const unsigned FirstDataArg; 5136 const unsigned NumDataArgs; 5137 const char *Beg; // Start of format string. 5138 const bool HasVAListArg; 5139 ArrayRef<const Expr *> Args; 5140 unsigned FormatIdx; 5141 llvm::SmallBitVector CoveredArgs; 5142 bool usesPositionalArgs; 5143 bool atFirstArg; 5144 bool inFunctionCall; 5145 Sema::VariadicCallType CallType; 5146 llvm::SmallBitVector &CheckedVarArgs; 5147 UncoveredArgHandler &UncoveredArg; 5148 5149 public: 5150 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 5151 const Expr *origFormatExpr, 5152 const Sema::FormatStringType type, unsigned firstDataArg, 5153 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5154 ArrayRef<const Expr *> Args, unsigned formatIdx, 5155 bool inFunctionCall, Sema::VariadicCallType callType, 5156 llvm::SmallBitVector &CheckedVarArgs, 5157 UncoveredArgHandler &UncoveredArg) 5158 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 5159 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 5160 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 5161 usesPositionalArgs(false), atFirstArg(true), 5162 inFunctionCall(inFunctionCall), CallType(callType), 5163 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 5164 CoveredArgs.resize(numDataArgs); 5165 CoveredArgs.reset(); 5166 } 5167 5168 void DoneProcessing(); 5169 5170 void HandleIncompleteSpecifier(const char *startSpecifier, 5171 unsigned specifierLen) override; 5172 5173 void HandleInvalidLengthModifier( 5174 const analyze_format_string::FormatSpecifier &FS, 5175 const analyze_format_string::ConversionSpecifier &CS, 5176 const char *startSpecifier, unsigned specifierLen, 5177 unsigned DiagID); 5178 5179 void HandleNonStandardLengthModifier( 5180 const analyze_format_string::FormatSpecifier &FS, 5181 const char *startSpecifier, unsigned specifierLen); 5182 5183 void HandleNonStandardConversionSpecifier( 5184 const analyze_format_string::ConversionSpecifier &CS, 5185 const char *startSpecifier, unsigned specifierLen); 5186 5187 void HandlePosition(const char *startPos, unsigned posLen) override; 5188 5189 void HandleInvalidPosition(const char *startSpecifier, 5190 unsigned specifierLen, 5191 analyze_format_string::PositionContext p) override; 5192 5193 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 5194 5195 void HandleNullChar(const char *nullCharacter) override; 5196 5197 template <typename Range> 5198 static void 5199 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 5200 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 5201 bool IsStringLocation, Range StringRange, 5202 ArrayRef<FixItHint> Fixit = None); 5203 5204 protected: 5205 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 5206 const char *startSpec, 5207 unsigned specifierLen, 5208 const char *csStart, unsigned csLen); 5209 5210 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 5211 const char *startSpec, 5212 unsigned specifierLen); 5213 5214 SourceRange getFormatStringRange(); 5215 CharSourceRange getSpecifierRange(const char *startSpecifier, 5216 unsigned specifierLen); 5217 SourceLocation getLocationOfByte(const char *x); 5218 5219 const Expr *getDataArg(unsigned i) const; 5220 5221 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 5222 const analyze_format_string::ConversionSpecifier &CS, 5223 const char *startSpecifier, unsigned specifierLen, 5224 unsigned argIndex); 5225 5226 template <typename Range> 5227 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5228 bool IsStringLocation, Range StringRange, 5229 ArrayRef<FixItHint> Fixit = None); 5230 }; 5231 } // end anonymous namespace 5232 5233 SourceRange CheckFormatHandler::getFormatStringRange() { 5234 return OrigFormatExpr->getSourceRange(); 5235 } 5236 5237 CharSourceRange CheckFormatHandler:: 5238 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 5239 SourceLocation Start = getLocationOfByte(startSpecifier); 5240 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 5241 5242 // Advance the end SourceLocation by one due to half-open ranges. 5243 End = End.getLocWithOffset(1); 5244 5245 return CharSourceRange::getCharRange(Start, End); 5246 } 5247 5248 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 5249 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 5250 S.getLangOpts(), S.Context.getTargetInfo()); 5251 } 5252 5253 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 5254 unsigned specifierLen){ 5255 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 5256 getLocationOfByte(startSpecifier), 5257 /*IsStringLocation*/true, 5258 getSpecifierRange(startSpecifier, specifierLen)); 5259 } 5260 5261 void CheckFormatHandler::HandleInvalidLengthModifier( 5262 const analyze_format_string::FormatSpecifier &FS, 5263 const analyze_format_string::ConversionSpecifier &CS, 5264 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 5265 using namespace analyze_format_string; 5266 5267 const LengthModifier &LM = FS.getLengthModifier(); 5268 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5269 5270 // See if we know how to fix this length modifier. 5271 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5272 if (FixedLM) { 5273 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5274 getLocationOfByte(LM.getStart()), 5275 /*IsStringLocation*/true, 5276 getSpecifierRange(startSpecifier, specifierLen)); 5277 5278 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5279 << FixedLM->toString() 5280 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5281 5282 } else { 5283 FixItHint Hint; 5284 if (DiagID == diag::warn_format_nonsensical_length) 5285 Hint = FixItHint::CreateRemoval(LMRange); 5286 5287 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5288 getLocationOfByte(LM.getStart()), 5289 /*IsStringLocation*/true, 5290 getSpecifierRange(startSpecifier, specifierLen), 5291 Hint); 5292 } 5293 } 5294 5295 void CheckFormatHandler::HandleNonStandardLengthModifier( 5296 const analyze_format_string::FormatSpecifier &FS, 5297 const char *startSpecifier, unsigned specifierLen) { 5298 using namespace analyze_format_string; 5299 5300 const LengthModifier &LM = FS.getLengthModifier(); 5301 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5302 5303 // See if we know how to fix this length modifier. 5304 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5305 if (FixedLM) { 5306 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5307 << LM.toString() << 0, 5308 getLocationOfByte(LM.getStart()), 5309 /*IsStringLocation*/true, 5310 getSpecifierRange(startSpecifier, specifierLen)); 5311 5312 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5313 << FixedLM->toString() 5314 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5315 5316 } else { 5317 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5318 << LM.toString() << 0, 5319 getLocationOfByte(LM.getStart()), 5320 /*IsStringLocation*/true, 5321 getSpecifierRange(startSpecifier, specifierLen)); 5322 } 5323 } 5324 5325 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5326 const analyze_format_string::ConversionSpecifier &CS, 5327 const char *startSpecifier, unsigned specifierLen) { 5328 using namespace analyze_format_string; 5329 5330 // See if we know how to fix this conversion specifier. 5331 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5332 if (FixedCS) { 5333 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5334 << CS.toString() << /*conversion specifier*/1, 5335 getLocationOfByte(CS.getStart()), 5336 /*IsStringLocation*/true, 5337 getSpecifierRange(startSpecifier, specifierLen)); 5338 5339 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5340 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5341 << FixedCS->toString() 5342 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5343 } else { 5344 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5345 << CS.toString() << /*conversion specifier*/1, 5346 getLocationOfByte(CS.getStart()), 5347 /*IsStringLocation*/true, 5348 getSpecifierRange(startSpecifier, specifierLen)); 5349 } 5350 } 5351 5352 void CheckFormatHandler::HandlePosition(const char *startPos, 5353 unsigned posLen) { 5354 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5355 getLocationOfByte(startPos), 5356 /*IsStringLocation*/true, 5357 getSpecifierRange(startPos, posLen)); 5358 } 5359 5360 void 5361 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5362 analyze_format_string::PositionContext p) { 5363 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5364 << (unsigned) p, 5365 getLocationOfByte(startPos), /*IsStringLocation*/true, 5366 getSpecifierRange(startPos, posLen)); 5367 } 5368 5369 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5370 unsigned posLen) { 5371 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5372 getLocationOfByte(startPos), 5373 /*IsStringLocation*/true, 5374 getSpecifierRange(startPos, posLen)); 5375 } 5376 5377 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5378 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5379 // The presence of a null character is likely an error. 5380 EmitFormatDiagnostic( 5381 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5382 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5383 getFormatStringRange()); 5384 } 5385 } 5386 5387 // Note that this may return NULL if there was an error parsing or building 5388 // one of the argument expressions. 5389 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5390 return Args[FirstDataArg + i]; 5391 } 5392 5393 void CheckFormatHandler::DoneProcessing() { 5394 // Does the number of data arguments exceed the number of 5395 // format conversions in the format string? 5396 if (!HasVAListArg) { 5397 // Find any arguments that weren't covered. 5398 CoveredArgs.flip(); 5399 signed notCoveredArg = CoveredArgs.find_first(); 5400 if (notCoveredArg >= 0) { 5401 assert((unsigned)notCoveredArg < NumDataArgs); 5402 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 5403 } else { 5404 UncoveredArg.setAllCovered(); 5405 } 5406 } 5407 } 5408 5409 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 5410 const Expr *ArgExpr) { 5411 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 5412 "Invalid state"); 5413 5414 if (!ArgExpr) 5415 return; 5416 5417 SourceLocation Loc = ArgExpr->getLocStart(); 5418 5419 if (S.getSourceManager().isInSystemMacro(Loc)) 5420 return; 5421 5422 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 5423 for (auto E : DiagnosticExprs) 5424 PDiag << E->getSourceRange(); 5425 5426 CheckFormatHandler::EmitFormatDiagnostic( 5427 S, IsFunctionCall, DiagnosticExprs[0], 5428 PDiag, Loc, /*IsStringLocation*/false, 5429 DiagnosticExprs[0]->getSourceRange()); 5430 } 5431 5432 bool 5433 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 5434 SourceLocation Loc, 5435 const char *startSpec, 5436 unsigned specifierLen, 5437 const char *csStart, 5438 unsigned csLen) { 5439 bool keepGoing = true; 5440 if (argIndex < NumDataArgs) { 5441 // Consider the argument coverered, even though the specifier doesn't 5442 // make sense. 5443 CoveredArgs.set(argIndex); 5444 } 5445 else { 5446 // If argIndex exceeds the number of data arguments we 5447 // don't issue a warning because that is just a cascade of warnings (and 5448 // they may have intended '%%' anyway). We don't want to continue processing 5449 // the format string after this point, however, as we will like just get 5450 // gibberish when trying to match arguments. 5451 keepGoing = false; 5452 } 5453 5454 StringRef Specifier(csStart, csLen); 5455 5456 // If the specifier in non-printable, it could be the first byte of a UTF-8 5457 // sequence. In that case, print the UTF-8 code point. If not, print the byte 5458 // hex value. 5459 std::string CodePointStr; 5460 if (!llvm::sys::locale::isPrint(*csStart)) { 5461 llvm::UTF32 CodePoint; 5462 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 5463 const llvm::UTF8 *E = 5464 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 5465 llvm::ConversionResult Result = 5466 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 5467 5468 if (Result != llvm::conversionOK) { 5469 unsigned char FirstChar = *csStart; 5470 CodePoint = (llvm::UTF32)FirstChar; 5471 } 5472 5473 llvm::raw_string_ostream OS(CodePointStr); 5474 if (CodePoint < 256) 5475 OS << "\\x" << llvm::format("%02x", CodePoint); 5476 else if (CodePoint <= 0xFFFF) 5477 OS << "\\u" << llvm::format("%04x", CodePoint); 5478 else 5479 OS << "\\U" << llvm::format("%08x", CodePoint); 5480 OS.flush(); 5481 Specifier = CodePointStr; 5482 } 5483 5484 EmitFormatDiagnostic( 5485 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 5486 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 5487 5488 return keepGoing; 5489 } 5490 5491 void 5492 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 5493 const char *startSpec, 5494 unsigned specifierLen) { 5495 EmitFormatDiagnostic( 5496 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 5497 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 5498 } 5499 5500 bool 5501 CheckFormatHandler::CheckNumArgs( 5502 const analyze_format_string::FormatSpecifier &FS, 5503 const analyze_format_string::ConversionSpecifier &CS, 5504 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 5505 5506 if (argIndex >= NumDataArgs) { 5507 PartialDiagnostic PDiag = FS.usesPositionalArg() 5508 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 5509 << (argIndex+1) << NumDataArgs) 5510 : S.PDiag(diag::warn_printf_insufficient_data_args); 5511 EmitFormatDiagnostic( 5512 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 5513 getSpecifierRange(startSpecifier, specifierLen)); 5514 5515 // Since more arguments than conversion tokens are given, by extension 5516 // all arguments are covered, so mark this as so. 5517 UncoveredArg.setAllCovered(); 5518 return false; 5519 } 5520 return true; 5521 } 5522 5523 template<typename Range> 5524 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 5525 SourceLocation Loc, 5526 bool IsStringLocation, 5527 Range StringRange, 5528 ArrayRef<FixItHint> FixIt) { 5529 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 5530 Loc, IsStringLocation, StringRange, FixIt); 5531 } 5532 5533 /// \brief If the format string is not within the funcion call, emit a note 5534 /// so that the function call and string are in diagnostic messages. 5535 /// 5536 /// \param InFunctionCall if true, the format string is within the function 5537 /// call and only one diagnostic message will be produced. Otherwise, an 5538 /// extra note will be emitted pointing to location of the format string. 5539 /// 5540 /// \param ArgumentExpr the expression that is passed as the format string 5541 /// argument in the function call. Used for getting locations when two 5542 /// diagnostics are emitted. 5543 /// 5544 /// \param PDiag the callee should already have provided any strings for the 5545 /// diagnostic message. This function only adds locations and fixits 5546 /// to diagnostics. 5547 /// 5548 /// \param Loc primary location for diagnostic. If two diagnostics are 5549 /// required, one will be at Loc and a new SourceLocation will be created for 5550 /// the other one. 5551 /// 5552 /// \param IsStringLocation if true, Loc points to the format string should be 5553 /// used for the note. Otherwise, Loc points to the argument list and will 5554 /// be used with PDiag. 5555 /// 5556 /// \param StringRange some or all of the string to highlight. This is 5557 /// templated so it can accept either a CharSourceRange or a SourceRange. 5558 /// 5559 /// \param FixIt optional fix it hint for the format string. 5560 template <typename Range> 5561 void CheckFormatHandler::EmitFormatDiagnostic( 5562 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 5563 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 5564 Range StringRange, ArrayRef<FixItHint> FixIt) { 5565 if (InFunctionCall) { 5566 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 5567 D << StringRange; 5568 D << FixIt; 5569 } else { 5570 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 5571 << ArgumentExpr->getSourceRange(); 5572 5573 const Sema::SemaDiagnosticBuilder &Note = 5574 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 5575 diag::note_format_string_defined); 5576 5577 Note << StringRange; 5578 Note << FixIt; 5579 } 5580 } 5581 5582 //===--- CHECK: Printf format string checking ------------------------------===// 5583 5584 namespace { 5585 class CheckPrintfHandler : public CheckFormatHandler { 5586 public: 5587 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 5588 const Expr *origFormatExpr, 5589 const Sema::FormatStringType type, unsigned firstDataArg, 5590 unsigned numDataArgs, bool isObjC, const char *beg, 5591 bool hasVAListArg, ArrayRef<const Expr *> Args, 5592 unsigned formatIdx, bool inFunctionCall, 5593 Sema::VariadicCallType CallType, 5594 llvm::SmallBitVector &CheckedVarArgs, 5595 UncoveredArgHandler &UncoveredArg) 5596 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 5597 numDataArgs, beg, hasVAListArg, Args, formatIdx, 5598 inFunctionCall, CallType, CheckedVarArgs, 5599 UncoveredArg) {} 5600 5601 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 5602 5603 /// Returns true if '%@' specifiers are allowed in the format string. 5604 bool allowsObjCArg() const { 5605 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 5606 FSType == Sema::FST_OSTrace; 5607 } 5608 5609 bool HandleInvalidPrintfConversionSpecifier( 5610 const analyze_printf::PrintfSpecifier &FS, 5611 const char *startSpecifier, 5612 unsigned specifierLen) override; 5613 5614 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 5615 const char *startSpecifier, 5616 unsigned specifierLen) override; 5617 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5618 const char *StartSpecifier, 5619 unsigned SpecifierLen, 5620 const Expr *E); 5621 5622 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 5623 const char *startSpecifier, unsigned specifierLen); 5624 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 5625 const analyze_printf::OptionalAmount &Amt, 5626 unsigned type, 5627 const char *startSpecifier, unsigned specifierLen); 5628 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5629 const analyze_printf::OptionalFlag &flag, 5630 const char *startSpecifier, unsigned specifierLen); 5631 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 5632 const analyze_printf::OptionalFlag &ignoredFlag, 5633 const analyze_printf::OptionalFlag &flag, 5634 const char *startSpecifier, unsigned specifierLen); 5635 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 5636 const Expr *E); 5637 5638 void HandleEmptyObjCModifierFlag(const char *startFlag, 5639 unsigned flagLen) override; 5640 5641 void HandleInvalidObjCModifierFlag(const char *startFlag, 5642 unsigned flagLen) override; 5643 5644 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 5645 const char *flagsEnd, 5646 const char *conversionPosition) 5647 override; 5648 }; 5649 } // end anonymous namespace 5650 5651 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 5652 const analyze_printf::PrintfSpecifier &FS, 5653 const char *startSpecifier, 5654 unsigned specifierLen) { 5655 const analyze_printf::PrintfConversionSpecifier &CS = 5656 FS.getConversionSpecifier(); 5657 5658 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5659 getLocationOfByte(CS.getStart()), 5660 startSpecifier, specifierLen, 5661 CS.getStart(), CS.getLength()); 5662 } 5663 5664 bool CheckPrintfHandler::HandleAmount( 5665 const analyze_format_string::OptionalAmount &Amt, 5666 unsigned k, const char *startSpecifier, 5667 unsigned specifierLen) { 5668 if (Amt.hasDataArgument()) { 5669 if (!HasVAListArg) { 5670 unsigned argIndex = Amt.getArgIndex(); 5671 if (argIndex >= NumDataArgs) { 5672 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 5673 << k, 5674 getLocationOfByte(Amt.getStart()), 5675 /*IsStringLocation*/true, 5676 getSpecifierRange(startSpecifier, specifierLen)); 5677 // Don't do any more checking. We will just emit 5678 // spurious errors. 5679 return false; 5680 } 5681 5682 // Type check the data argument. It should be an 'int'. 5683 // Although not in conformance with C99, we also allow the argument to be 5684 // an 'unsigned int' as that is a reasonably safe case. GCC also 5685 // doesn't emit a warning for that case. 5686 CoveredArgs.set(argIndex); 5687 const Expr *Arg = getDataArg(argIndex); 5688 if (!Arg) 5689 return false; 5690 5691 QualType T = Arg->getType(); 5692 5693 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 5694 assert(AT.isValid()); 5695 5696 if (!AT.matchesType(S.Context, T)) { 5697 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 5698 << k << AT.getRepresentativeTypeName(S.Context) 5699 << T << Arg->getSourceRange(), 5700 getLocationOfByte(Amt.getStart()), 5701 /*IsStringLocation*/true, 5702 getSpecifierRange(startSpecifier, specifierLen)); 5703 // Don't do any more checking. We will just emit 5704 // spurious errors. 5705 return false; 5706 } 5707 } 5708 } 5709 return true; 5710 } 5711 5712 void CheckPrintfHandler::HandleInvalidAmount( 5713 const analyze_printf::PrintfSpecifier &FS, 5714 const analyze_printf::OptionalAmount &Amt, 5715 unsigned type, 5716 const char *startSpecifier, 5717 unsigned specifierLen) { 5718 const analyze_printf::PrintfConversionSpecifier &CS = 5719 FS.getConversionSpecifier(); 5720 5721 FixItHint fixit = 5722 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 5723 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 5724 Amt.getConstantLength())) 5725 : FixItHint(); 5726 5727 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 5728 << type << CS.toString(), 5729 getLocationOfByte(Amt.getStart()), 5730 /*IsStringLocation*/true, 5731 getSpecifierRange(startSpecifier, specifierLen), 5732 fixit); 5733 } 5734 5735 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5736 const analyze_printf::OptionalFlag &flag, 5737 const char *startSpecifier, 5738 unsigned specifierLen) { 5739 // Warn about pointless flag with a fixit removal. 5740 const analyze_printf::PrintfConversionSpecifier &CS = 5741 FS.getConversionSpecifier(); 5742 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 5743 << flag.toString() << CS.toString(), 5744 getLocationOfByte(flag.getPosition()), 5745 /*IsStringLocation*/true, 5746 getSpecifierRange(startSpecifier, specifierLen), 5747 FixItHint::CreateRemoval( 5748 getSpecifierRange(flag.getPosition(), 1))); 5749 } 5750 5751 void CheckPrintfHandler::HandleIgnoredFlag( 5752 const analyze_printf::PrintfSpecifier &FS, 5753 const analyze_printf::OptionalFlag &ignoredFlag, 5754 const analyze_printf::OptionalFlag &flag, 5755 const char *startSpecifier, 5756 unsigned specifierLen) { 5757 // Warn about ignored flag with a fixit removal. 5758 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 5759 << ignoredFlag.toString() << flag.toString(), 5760 getLocationOfByte(ignoredFlag.getPosition()), 5761 /*IsStringLocation*/true, 5762 getSpecifierRange(startSpecifier, specifierLen), 5763 FixItHint::CreateRemoval( 5764 getSpecifierRange(ignoredFlag.getPosition(), 1))); 5765 } 5766 5767 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5768 // bool IsStringLocation, Range StringRange, 5769 // ArrayRef<FixItHint> Fixit = None); 5770 5771 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 5772 unsigned flagLen) { 5773 // Warn about an empty flag. 5774 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 5775 getLocationOfByte(startFlag), 5776 /*IsStringLocation*/true, 5777 getSpecifierRange(startFlag, flagLen)); 5778 } 5779 5780 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 5781 unsigned flagLen) { 5782 // Warn about an invalid flag. 5783 auto Range = getSpecifierRange(startFlag, flagLen); 5784 StringRef flag(startFlag, flagLen); 5785 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 5786 getLocationOfByte(startFlag), 5787 /*IsStringLocation*/true, 5788 Range, FixItHint::CreateRemoval(Range)); 5789 } 5790 5791 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 5792 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 5793 // Warn about using '[...]' without a '@' conversion. 5794 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 5795 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 5796 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 5797 getLocationOfByte(conversionPosition), 5798 /*IsStringLocation*/true, 5799 Range, FixItHint::CreateRemoval(Range)); 5800 } 5801 5802 // Determines if the specified is a C++ class or struct containing 5803 // a member with the specified name and kind (e.g. a CXXMethodDecl named 5804 // "c_str()"). 5805 template<typename MemberKind> 5806 static llvm::SmallPtrSet<MemberKind*, 1> 5807 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 5808 const RecordType *RT = Ty->getAs<RecordType>(); 5809 llvm::SmallPtrSet<MemberKind*, 1> Results; 5810 5811 if (!RT) 5812 return Results; 5813 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 5814 if (!RD || !RD->getDefinition()) 5815 return Results; 5816 5817 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 5818 Sema::LookupMemberName); 5819 R.suppressDiagnostics(); 5820 5821 // We just need to include all members of the right kind turned up by the 5822 // filter, at this point. 5823 if (S.LookupQualifiedName(R, RT->getDecl())) 5824 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 5825 NamedDecl *decl = (*I)->getUnderlyingDecl(); 5826 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 5827 Results.insert(FK); 5828 } 5829 return Results; 5830 } 5831 5832 /// Check if we could call '.c_str()' on an object. 5833 /// 5834 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 5835 /// allow the call, or if it would be ambiguous). 5836 bool Sema::hasCStrMethod(const Expr *E) { 5837 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5838 MethodSet Results = 5839 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 5840 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5841 MI != ME; ++MI) 5842 if ((*MI)->getMinRequiredArguments() == 0) 5843 return true; 5844 return false; 5845 } 5846 5847 // Check if a (w)string was passed when a (w)char* was needed, and offer a 5848 // better diagnostic if so. AT is assumed to be valid. 5849 // Returns true when a c_str() conversion method is found. 5850 bool CheckPrintfHandler::checkForCStrMembers( 5851 const analyze_printf::ArgType &AT, const Expr *E) { 5852 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5853 5854 MethodSet Results = 5855 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 5856 5857 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5858 MI != ME; ++MI) { 5859 const CXXMethodDecl *Method = *MI; 5860 if (Method->getMinRequiredArguments() == 0 && 5861 AT.matchesType(S.Context, Method->getReturnType())) { 5862 // FIXME: Suggest parens if the expression needs them. 5863 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 5864 S.Diag(E->getLocStart(), diag::note_printf_c_str) 5865 << "c_str()" 5866 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 5867 return true; 5868 } 5869 } 5870 5871 return false; 5872 } 5873 5874 bool 5875 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 5876 &FS, 5877 const char *startSpecifier, 5878 unsigned specifierLen) { 5879 using namespace analyze_format_string; 5880 using namespace analyze_printf; 5881 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 5882 5883 if (FS.consumesDataArgument()) { 5884 if (atFirstArg) { 5885 atFirstArg = false; 5886 usesPositionalArgs = FS.usesPositionalArg(); 5887 } 5888 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5889 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5890 startSpecifier, specifierLen); 5891 return false; 5892 } 5893 } 5894 5895 // First check if the field width, precision, and conversion specifier 5896 // have matching data arguments. 5897 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 5898 startSpecifier, specifierLen)) { 5899 return false; 5900 } 5901 5902 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 5903 startSpecifier, specifierLen)) { 5904 return false; 5905 } 5906 5907 if (!CS.consumesDataArgument()) { 5908 // FIXME: Technically specifying a precision or field width here 5909 // makes no sense. Worth issuing a warning at some point. 5910 return true; 5911 } 5912 5913 // Consume the argument. 5914 unsigned argIndex = FS.getArgIndex(); 5915 if (argIndex < NumDataArgs) { 5916 // The check to see if the argIndex is valid will come later. 5917 // We set the bit here because we may exit early from this 5918 // function if we encounter some other error. 5919 CoveredArgs.set(argIndex); 5920 } 5921 5922 // FreeBSD kernel extensions. 5923 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 5924 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 5925 // We need at least two arguments. 5926 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 5927 return false; 5928 5929 // Claim the second argument. 5930 CoveredArgs.set(argIndex + 1); 5931 5932 // Type check the first argument (int for %b, pointer for %D) 5933 const Expr *Ex = getDataArg(argIndex); 5934 const analyze_printf::ArgType &AT = 5935 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 5936 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 5937 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 5938 EmitFormatDiagnostic( 5939 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5940 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 5941 << false << Ex->getSourceRange(), 5942 Ex->getLocStart(), /*IsStringLocation*/false, 5943 getSpecifierRange(startSpecifier, specifierLen)); 5944 5945 // Type check the second argument (char * for both %b and %D) 5946 Ex = getDataArg(argIndex + 1); 5947 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 5948 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 5949 EmitFormatDiagnostic( 5950 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5951 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 5952 << false << Ex->getSourceRange(), 5953 Ex->getLocStart(), /*IsStringLocation*/false, 5954 getSpecifierRange(startSpecifier, specifierLen)); 5955 5956 return true; 5957 } 5958 5959 // Check for using an Objective-C specific conversion specifier 5960 // in a non-ObjC literal. 5961 if (!allowsObjCArg() && CS.isObjCArg()) { 5962 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5963 specifierLen); 5964 } 5965 5966 // %P can only be used with os_log. 5967 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 5968 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5969 specifierLen); 5970 } 5971 5972 // %n is not allowed with os_log. 5973 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 5974 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 5975 getLocationOfByte(CS.getStart()), 5976 /*IsStringLocation*/ false, 5977 getSpecifierRange(startSpecifier, specifierLen)); 5978 5979 return true; 5980 } 5981 5982 // Only scalars are allowed for os_trace. 5983 if (FSType == Sema::FST_OSTrace && 5984 (CS.getKind() == ConversionSpecifier::PArg || 5985 CS.getKind() == ConversionSpecifier::sArg || 5986 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 5987 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5988 specifierLen); 5989 } 5990 5991 // Check for use of public/private annotation outside of os_log(). 5992 if (FSType != Sema::FST_OSLog) { 5993 if (FS.isPublic().isSet()) { 5994 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 5995 << "public", 5996 getLocationOfByte(FS.isPublic().getPosition()), 5997 /*IsStringLocation*/ false, 5998 getSpecifierRange(startSpecifier, specifierLen)); 5999 } 6000 if (FS.isPrivate().isSet()) { 6001 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6002 << "private", 6003 getLocationOfByte(FS.isPrivate().getPosition()), 6004 /*IsStringLocation*/ false, 6005 getSpecifierRange(startSpecifier, specifierLen)); 6006 } 6007 } 6008 6009 // Check for invalid use of field width 6010 if (!FS.hasValidFieldWidth()) { 6011 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 6012 startSpecifier, specifierLen); 6013 } 6014 6015 // Check for invalid use of precision 6016 if (!FS.hasValidPrecision()) { 6017 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 6018 startSpecifier, specifierLen); 6019 } 6020 6021 // Precision is mandatory for %P specifier. 6022 if (CS.getKind() == ConversionSpecifier::PArg && 6023 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 6024 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 6025 getLocationOfByte(startSpecifier), 6026 /*IsStringLocation*/ false, 6027 getSpecifierRange(startSpecifier, specifierLen)); 6028 } 6029 6030 // Check each flag does not conflict with any other component. 6031 if (!FS.hasValidThousandsGroupingPrefix()) 6032 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 6033 if (!FS.hasValidLeadingZeros()) 6034 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 6035 if (!FS.hasValidPlusPrefix()) 6036 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 6037 if (!FS.hasValidSpacePrefix()) 6038 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 6039 if (!FS.hasValidAlternativeForm()) 6040 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 6041 if (!FS.hasValidLeftJustified()) 6042 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 6043 6044 // Check that flags are not ignored by another flag 6045 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 6046 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 6047 startSpecifier, specifierLen); 6048 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 6049 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 6050 startSpecifier, specifierLen); 6051 6052 // Check the length modifier is valid with the given conversion specifier. 6053 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6054 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6055 diag::warn_format_nonsensical_length); 6056 else if (!FS.hasStandardLengthModifier()) 6057 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6058 else if (!FS.hasStandardLengthConversionCombination()) 6059 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6060 diag::warn_format_non_standard_conversion_spec); 6061 6062 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6063 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6064 6065 // The remaining checks depend on the data arguments. 6066 if (HasVAListArg) 6067 return true; 6068 6069 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6070 return false; 6071 6072 const Expr *Arg = getDataArg(argIndex); 6073 if (!Arg) 6074 return true; 6075 6076 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 6077 } 6078 6079 static bool requiresParensToAddCast(const Expr *E) { 6080 // FIXME: We should have a general way to reason about operator 6081 // precedence and whether parens are actually needed here. 6082 // Take care of a few common cases where they aren't. 6083 const Expr *Inside = E->IgnoreImpCasts(); 6084 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 6085 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 6086 6087 switch (Inside->getStmtClass()) { 6088 case Stmt::ArraySubscriptExprClass: 6089 case Stmt::CallExprClass: 6090 case Stmt::CharacterLiteralClass: 6091 case Stmt::CXXBoolLiteralExprClass: 6092 case Stmt::DeclRefExprClass: 6093 case Stmt::FloatingLiteralClass: 6094 case Stmt::IntegerLiteralClass: 6095 case Stmt::MemberExprClass: 6096 case Stmt::ObjCArrayLiteralClass: 6097 case Stmt::ObjCBoolLiteralExprClass: 6098 case Stmt::ObjCBoxedExprClass: 6099 case Stmt::ObjCDictionaryLiteralClass: 6100 case Stmt::ObjCEncodeExprClass: 6101 case Stmt::ObjCIvarRefExprClass: 6102 case Stmt::ObjCMessageExprClass: 6103 case Stmt::ObjCPropertyRefExprClass: 6104 case Stmt::ObjCStringLiteralClass: 6105 case Stmt::ObjCSubscriptRefExprClass: 6106 case Stmt::ParenExprClass: 6107 case Stmt::StringLiteralClass: 6108 case Stmt::UnaryOperatorClass: 6109 return false; 6110 default: 6111 return true; 6112 } 6113 } 6114 6115 static std::pair<QualType, StringRef> 6116 shouldNotPrintDirectly(const ASTContext &Context, 6117 QualType IntendedTy, 6118 const Expr *E) { 6119 // Use a 'while' to peel off layers of typedefs. 6120 QualType TyTy = IntendedTy; 6121 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 6122 StringRef Name = UserTy->getDecl()->getName(); 6123 QualType CastTy = llvm::StringSwitch<QualType>(Name) 6124 .Case("CFIndex", Context.LongTy) 6125 .Case("NSInteger", Context.LongTy) 6126 .Case("NSUInteger", Context.UnsignedLongTy) 6127 .Case("SInt32", Context.IntTy) 6128 .Case("UInt32", Context.UnsignedIntTy) 6129 .Default(QualType()); 6130 6131 if (!CastTy.isNull()) 6132 return std::make_pair(CastTy, Name); 6133 6134 TyTy = UserTy->desugar(); 6135 } 6136 6137 // Strip parens if necessary. 6138 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 6139 return shouldNotPrintDirectly(Context, 6140 PE->getSubExpr()->getType(), 6141 PE->getSubExpr()); 6142 6143 // If this is a conditional expression, then its result type is constructed 6144 // via usual arithmetic conversions and thus there might be no necessary 6145 // typedef sugar there. Recurse to operands to check for NSInteger & 6146 // Co. usage condition. 6147 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6148 QualType TrueTy, FalseTy; 6149 StringRef TrueName, FalseName; 6150 6151 std::tie(TrueTy, TrueName) = 6152 shouldNotPrintDirectly(Context, 6153 CO->getTrueExpr()->getType(), 6154 CO->getTrueExpr()); 6155 std::tie(FalseTy, FalseName) = 6156 shouldNotPrintDirectly(Context, 6157 CO->getFalseExpr()->getType(), 6158 CO->getFalseExpr()); 6159 6160 if (TrueTy == FalseTy) 6161 return std::make_pair(TrueTy, TrueName); 6162 else if (TrueTy.isNull()) 6163 return std::make_pair(FalseTy, FalseName); 6164 else if (FalseTy.isNull()) 6165 return std::make_pair(TrueTy, TrueName); 6166 } 6167 6168 return std::make_pair(QualType(), StringRef()); 6169 } 6170 6171 bool 6172 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6173 const char *StartSpecifier, 6174 unsigned SpecifierLen, 6175 const Expr *E) { 6176 using namespace analyze_format_string; 6177 using namespace analyze_printf; 6178 // Now type check the data expression that matches the 6179 // format specifier. 6180 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 6181 if (!AT.isValid()) 6182 return true; 6183 6184 QualType ExprTy = E->getType(); 6185 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 6186 ExprTy = TET->getUnderlyingExpr()->getType(); 6187 } 6188 6189 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 6190 6191 if (match == analyze_printf::ArgType::Match) { 6192 return true; 6193 } 6194 6195 // Look through argument promotions for our error message's reported type. 6196 // This includes the integral and floating promotions, but excludes array 6197 // and function pointer decay; seeing that an argument intended to be a 6198 // string has type 'char [6]' is probably more confusing than 'char *'. 6199 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6200 if (ICE->getCastKind() == CK_IntegralCast || 6201 ICE->getCastKind() == CK_FloatingCast) { 6202 E = ICE->getSubExpr(); 6203 ExprTy = E->getType(); 6204 6205 // Check if we didn't match because of an implicit cast from a 'char' 6206 // or 'short' to an 'int'. This is done because printf is a varargs 6207 // function. 6208 if (ICE->getType() == S.Context.IntTy || 6209 ICE->getType() == S.Context.UnsignedIntTy) { 6210 // All further checking is done on the subexpression. 6211 if (AT.matchesType(S.Context, ExprTy)) 6212 return true; 6213 } 6214 } 6215 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 6216 // Special case for 'a', which has type 'int' in C. 6217 // Note, however, that we do /not/ want to treat multibyte constants like 6218 // 'MooV' as characters! This form is deprecated but still exists. 6219 if (ExprTy == S.Context.IntTy) 6220 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 6221 ExprTy = S.Context.CharTy; 6222 } 6223 6224 // Look through enums to their underlying type. 6225 bool IsEnum = false; 6226 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 6227 ExprTy = EnumTy->getDecl()->getIntegerType(); 6228 IsEnum = true; 6229 } 6230 6231 // %C in an Objective-C context prints a unichar, not a wchar_t. 6232 // If the argument is an integer of some kind, believe the %C and suggest 6233 // a cast instead of changing the conversion specifier. 6234 QualType IntendedTy = ExprTy; 6235 if (isObjCContext() && 6236 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 6237 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 6238 !ExprTy->isCharType()) { 6239 // 'unichar' is defined as a typedef of unsigned short, but we should 6240 // prefer using the typedef if it is visible. 6241 IntendedTy = S.Context.UnsignedShortTy; 6242 6243 // While we are here, check if the value is an IntegerLiteral that happens 6244 // to be within the valid range. 6245 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 6246 const llvm::APInt &V = IL->getValue(); 6247 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 6248 return true; 6249 } 6250 6251 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 6252 Sema::LookupOrdinaryName); 6253 if (S.LookupName(Result, S.getCurScope())) { 6254 NamedDecl *ND = Result.getFoundDecl(); 6255 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 6256 if (TD->getUnderlyingType() == IntendedTy) 6257 IntendedTy = S.Context.getTypedefType(TD); 6258 } 6259 } 6260 } 6261 6262 // Special-case some of Darwin's platform-independence types by suggesting 6263 // casts to primitive types that are known to be large enough. 6264 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 6265 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 6266 QualType CastTy; 6267 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 6268 if (!CastTy.isNull()) { 6269 IntendedTy = CastTy; 6270 ShouldNotPrintDirectly = true; 6271 } 6272 } 6273 6274 // We may be able to offer a FixItHint if it is a supported type. 6275 PrintfSpecifier fixedFS = FS; 6276 bool success = 6277 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 6278 6279 if (success) { 6280 // Get the fix string from the fixed format specifier 6281 SmallString<16> buf; 6282 llvm::raw_svector_ostream os(buf); 6283 fixedFS.toString(os); 6284 6285 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 6286 6287 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 6288 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6289 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6290 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6291 } 6292 // In this case, the specifier is wrong and should be changed to match 6293 // the argument. 6294 EmitFormatDiagnostic(S.PDiag(diag) 6295 << AT.getRepresentativeTypeName(S.Context) 6296 << IntendedTy << IsEnum << E->getSourceRange(), 6297 E->getLocStart(), 6298 /*IsStringLocation*/ false, SpecRange, 6299 FixItHint::CreateReplacement(SpecRange, os.str())); 6300 } else { 6301 // The canonical type for formatting this value is different from the 6302 // actual type of the expression. (This occurs, for example, with Darwin's 6303 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 6304 // should be printed as 'long' for 64-bit compatibility.) 6305 // Rather than emitting a normal format/argument mismatch, we want to 6306 // add a cast to the recommended type (and correct the format string 6307 // if necessary). 6308 SmallString<16> CastBuf; 6309 llvm::raw_svector_ostream CastFix(CastBuf); 6310 CastFix << "("; 6311 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 6312 CastFix << ")"; 6313 6314 SmallVector<FixItHint,4> Hints; 6315 if (!AT.matchesType(S.Context, IntendedTy)) 6316 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 6317 6318 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 6319 // If there's already a cast present, just replace it. 6320 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 6321 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 6322 6323 } else if (!requiresParensToAddCast(E)) { 6324 // If the expression has high enough precedence, 6325 // just write the C-style cast. 6326 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6327 CastFix.str())); 6328 } else { 6329 // Otherwise, add parens around the expression as well as the cast. 6330 CastFix << "("; 6331 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6332 CastFix.str())); 6333 6334 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6335 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6336 } 6337 6338 if (ShouldNotPrintDirectly) { 6339 // The expression has a type that should not be printed directly. 6340 // We extract the name from the typedef because we don't want to show 6341 // the underlying type in the diagnostic. 6342 StringRef Name; 6343 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6344 Name = TypedefTy->getDecl()->getName(); 6345 else 6346 Name = CastTyName; 6347 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6348 << Name << IntendedTy << IsEnum 6349 << E->getSourceRange(), 6350 E->getLocStart(), /*IsStringLocation=*/false, 6351 SpecRange, Hints); 6352 } else { 6353 // In this case, the expression could be printed using a different 6354 // specifier, but we've decided that the specifier is probably correct 6355 // and we should cast instead. Just use the normal warning message. 6356 EmitFormatDiagnostic( 6357 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6358 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6359 << E->getSourceRange(), 6360 E->getLocStart(), /*IsStringLocation*/false, 6361 SpecRange, Hints); 6362 } 6363 } 6364 } else { 6365 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6366 SpecifierLen); 6367 // Since the warning for passing non-POD types to variadic functions 6368 // was deferred until now, we emit a warning for non-POD 6369 // arguments here. 6370 switch (S.isValidVarArgType(ExprTy)) { 6371 case Sema::VAK_Valid: 6372 case Sema::VAK_ValidInCXX11: { 6373 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6374 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6375 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6376 } 6377 6378 EmitFormatDiagnostic( 6379 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6380 << IsEnum << CSR << E->getSourceRange(), 6381 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6382 break; 6383 } 6384 case Sema::VAK_Undefined: 6385 case Sema::VAK_MSVCUndefined: 6386 EmitFormatDiagnostic( 6387 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6388 << S.getLangOpts().CPlusPlus11 6389 << ExprTy 6390 << CallType 6391 << AT.getRepresentativeTypeName(S.Context) 6392 << CSR 6393 << E->getSourceRange(), 6394 E->getLocStart(), /*IsStringLocation*/false, CSR); 6395 checkForCStrMembers(AT, E); 6396 break; 6397 6398 case Sema::VAK_Invalid: 6399 if (ExprTy->isObjCObjectType()) 6400 EmitFormatDiagnostic( 6401 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 6402 << S.getLangOpts().CPlusPlus11 6403 << ExprTy 6404 << CallType 6405 << AT.getRepresentativeTypeName(S.Context) 6406 << CSR 6407 << E->getSourceRange(), 6408 E->getLocStart(), /*IsStringLocation*/false, CSR); 6409 else 6410 // FIXME: If this is an initializer list, suggest removing the braces 6411 // or inserting a cast to the target type. 6412 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 6413 << isa<InitListExpr>(E) << ExprTy << CallType 6414 << AT.getRepresentativeTypeName(S.Context) 6415 << E->getSourceRange(); 6416 break; 6417 } 6418 6419 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 6420 "format string specifier index out of range"); 6421 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 6422 } 6423 6424 return true; 6425 } 6426 6427 //===--- CHECK: Scanf format string checking ------------------------------===// 6428 6429 namespace { 6430 class CheckScanfHandler : public CheckFormatHandler { 6431 public: 6432 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 6433 const Expr *origFormatExpr, Sema::FormatStringType type, 6434 unsigned firstDataArg, unsigned numDataArgs, 6435 const char *beg, bool hasVAListArg, 6436 ArrayRef<const Expr *> Args, unsigned formatIdx, 6437 bool inFunctionCall, Sema::VariadicCallType CallType, 6438 llvm::SmallBitVector &CheckedVarArgs, 6439 UncoveredArgHandler &UncoveredArg) 6440 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6441 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6442 inFunctionCall, CallType, CheckedVarArgs, 6443 UncoveredArg) {} 6444 6445 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 6446 const char *startSpecifier, 6447 unsigned specifierLen) override; 6448 6449 bool HandleInvalidScanfConversionSpecifier( 6450 const analyze_scanf::ScanfSpecifier &FS, 6451 const char *startSpecifier, 6452 unsigned specifierLen) override; 6453 6454 void HandleIncompleteScanList(const char *start, const char *end) override; 6455 }; 6456 } // end anonymous namespace 6457 6458 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 6459 const char *end) { 6460 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 6461 getLocationOfByte(end), /*IsStringLocation*/true, 6462 getSpecifierRange(start, end - start)); 6463 } 6464 6465 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 6466 const analyze_scanf::ScanfSpecifier &FS, 6467 const char *startSpecifier, 6468 unsigned specifierLen) { 6469 6470 const analyze_scanf::ScanfConversionSpecifier &CS = 6471 FS.getConversionSpecifier(); 6472 6473 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6474 getLocationOfByte(CS.getStart()), 6475 startSpecifier, specifierLen, 6476 CS.getStart(), CS.getLength()); 6477 } 6478 6479 bool CheckScanfHandler::HandleScanfSpecifier( 6480 const analyze_scanf::ScanfSpecifier &FS, 6481 const char *startSpecifier, 6482 unsigned specifierLen) { 6483 using namespace analyze_scanf; 6484 using namespace analyze_format_string; 6485 6486 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 6487 6488 // Handle case where '%' and '*' don't consume an argument. These shouldn't 6489 // be used to decide if we are using positional arguments consistently. 6490 if (FS.consumesDataArgument()) { 6491 if (atFirstArg) { 6492 atFirstArg = false; 6493 usesPositionalArgs = FS.usesPositionalArg(); 6494 } 6495 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6496 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6497 startSpecifier, specifierLen); 6498 return false; 6499 } 6500 } 6501 6502 // Check if the field with is non-zero. 6503 const OptionalAmount &Amt = FS.getFieldWidth(); 6504 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 6505 if (Amt.getConstantAmount() == 0) { 6506 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 6507 Amt.getConstantLength()); 6508 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 6509 getLocationOfByte(Amt.getStart()), 6510 /*IsStringLocation*/true, R, 6511 FixItHint::CreateRemoval(R)); 6512 } 6513 } 6514 6515 if (!FS.consumesDataArgument()) { 6516 // FIXME: Technically specifying a precision or field width here 6517 // makes no sense. Worth issuing a warning at some point. 6518 return true; 6519 } 6520 6521 // Consume the argument. 6522 unsigned argIndex = FS.getArgIndex(); 6523 if (argIndex < NumDataArgs) { 6524 // The check to see if the argIndex is valid will come later. 6525 // We set the bit here because we may exit early from this 6526 // function if we encounter some other error. 6527 CoveredArgs.set(argIndex); 6528 } 6529 6530 // Check the length modifier is valid with the given conversion specifier. 6531 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6532 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6533 diag::warn_format_nonsensical_length); 6534 else if (!FS.hasStandardLengthModifier()) 6535 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6536 else if (!FS.hasStandardLengthConversionCombination()) 6537 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6538 diag::warn_format_non_standard_conversion_spec); 6539 6540 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6541 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6542 6543 // The remaining checks depend on the data arguments. 6544 if (HasVAListArg) 6545 return true; 6546 6547 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6548 return false; 6549 6550 // Check that the argument type matches the format specifier. 6551 const Expr *Ex = getDataArg(argIndex); 6552 if (!Ex) 6553 return true; 6554 6555 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 6556 6557 if (!AT.isValid()) { 6558 return true; 6559 } 6560 6561 analyze_format_string::ArgType::MatchKind match = 6562 AT.matchesType(S.Context, Ex->getType()); 6563 if (match == analyze_format_string::ArgType::Match) { 6564 return true; 6565 } 6566 6567 ScanfSpecifier fixedFS = FS; 6568 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 6569 S.getLangOpts(), S.Context); 6570 6571 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6572 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6573 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6574 } 6575 6576 if (success) { 6577 // Get the fix string from the fixed format specifier. 6578 SmallString<128> buf; 6579 llvm::raw_svector_ostream os(buf); 6580 fixedFS.toString(os); 6581 6582 EmitFormatDiagnostic( 6583 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 6584 << Ex->getType() << false << Ex->getSourceRange(), 6585 Ex->getLocStart(), 6586 /*IsStringLocation*/ false, 6587 getSpecifierRange(startSpecifier, specifierLen), 6588 FixItHint::CreateReplacement( 6589 getSpecifierRange(startSpecifier, specifierLen), os.str())); 6590 } else { 6591 EmitFormatDiagnostic(S.PDiag(diag) 6592 << AT.getRepresentativeTypeName(S.Context) 6593 << Ex->getType() << false << Ex->getSourceRange(), 6594 Ex->getLocStart(), 6595 /*IsStringLocation*/ false, 6596 getSpecifierRange(startSpecifier, specifierLen)); 6597 } 6598 6599 return true; 6600 } 6601 6602 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6603 const Expr *OrigFormatExpr, 6604 ArrayRef<const Expr *> Args, 6605 bool HasVAListArg, unsigned format_idx, 6606 unsigned firstDataArg, 6607 Sema::FormatStringType Type, 6608 bool inFunctionCall, 6609 Sema::VariadicCallType CallType, 6610 llvm::SmallBitVector &CheckedVarArgs, 6611 UncoveredArgHandler &UncoveredArg) { 6612 // CHECK: is the format string a wide literal? 6613 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 6614 CheckFormatHandler::EmitFormatDiagnostic( 6615 S, inFunctionCall, Args[format_idx], 6616 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 6617 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6618 return; 6619 } 6620 6621 // Str - The format string. NOTE: this is NOT null-terminated! 6622 StringRef StrRef = FExpr->getString(); 6623 const char *Str = StrRef.data(); 6624 // Account for cases where the string literal is truncated in a declaration. 6625 const ConstantArrayType *T = 6626 S.Context.getAsConstantArrayType(FExpr->getType()); 6627 assert(T && "String literal not of constant array type!"); 6628 size_t TypeSize = T->getSize().getZExtValue(); 6629 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6630 const unsigned numDataArgs = Args.size() - firstDataArg; 6631 6632 // Emit a warning if the string literal is truncated and does not contain an 6633 // embedded null character. 6634 if (TypeSize <= StrRef.size() && 6635 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 6636 CheckFormatHandler::EmitFormatDiagnostic( 6637 S, inFunctionCall, Args[format_idx], 6638 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 6639 FExpr->getLocStart(), 6640 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 6641 return; 6642 } 6643 6644 // CHECK: empty format string? 6645 if (StrLen == 0 && numDataArgs > 0) { 6646 CheckFormatHandler::EmitFormatDiagnostic( 6647 S, inFunctionCall, Args[format_idx], 6648 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 6649 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6650 return; 6651 } 6652 6653 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 6654 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 6655 Type == Sema::FST_OSTrace) { 6656 CheckPrintfHandler H( 6657 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 6658 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 6659 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 6660 CheckedVarArgs, UncoveredArg); 6661 6662 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 6663 S.getLangOpts(), 6664 S.Context.getTargetInfo(), 6665 Type == Sema::FST_FreeBSDKPrintf)) 6666 H.DoneProcessing(); 6667 } else if (Type == Sema::FST_Scanf) { 6668 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 6669 numDataArgs, Str, HasVAListArg, Args, format_idx, 6670 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 6671 6672 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 6673 S.getLangOpts(), 6674 S.Context.getTargetInfo())) 6675 H.DoneProcessing(); 6676 } // TODO: handle other formats 6677 } 6678 6679 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 6680 // Str - The format string. NOTE: this is NOT null-terminated! 6681 StringRef StrRef = FExpr->getString(); 6682 const char *Str = StrRef.data(); 6683 // Account for cases where the string literal is truncated in a declaration. 6684 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 6685 assert(T && "String literal not of constant array type!"); 6686 size_t TypeSize = T->getSize().getZExtValue(); 6687 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6688 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 6689 getLangOpts(), 6690 Context.getTargetInfo()); 6691 } 6692 6693 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 6694 6695 // Returns the related absolute value function that is larger, of 0 if one 6696 // does not exist. 6697 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 6698 switch (AbsFunction) { 6699 default: 6700 return 0; 6701 6702 case Builtin::BI__builtin_abs: 6703 return Builtin::BI__builtin_labs; 6704 case Builtin::BI__builtin_labs: 6705 return Builtin::BI__builtin_llabs; 6706 case Builtin::BI__builtin_llabs: 6707 return 0; 6708 6709 case Builtin::BI__builtin_fabsf: 6710 return Builtin::BI__builtin_fabs; 6711 case Builtin::BI__builtin_fabs: 6712 return Builtin::BI__builtin_fabsl; 6713 case Builtin::BI__builtin_fabsl: 6714 return 0; 6715 6716 case Builtin::BI__builtin_cabsf: 6717 return Builtin::BI__builtin_cabs; 6718 case Builtin::BI__builtin_cabs: 6719 return Builtin::BI__builtin_cabsl; 6720 case Builtin::BI__builtin_cabsl: 6721 return 0; 6722 6723 case Builtin::BIabs: 6724 return Builtin::BIlabs; 6725 case Builtin::BIlabs: 6726 return Builtin::BIllabs; 6727 case Builtin::BIllabs: 6728 return 0; 6729 6730 case Builtin::BIfabsf: 6731 return Builtin::BIfabs; 6732 case Builtin::BIfabs: 6733 return Builtin::BIfabsl; 6734 case Builtin::BIfabsl: 6735 return 0; 6736 6737 case Builtin::BIcabsf: 6738 return Builtin::BIcabs; 6739 case Builtin::BIcabs: 6740 return Builtin::BIcabsl; 6741 case Builtin::BIcabsl: 6742 return 0; 6743 } 6744 } 6745 6746 // Returns the argument type of the absolute value function. 6747 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 6748 unsigned AbsType) { 6749 if (AbsType == 0) 6750 return QualType(); 6751 6752 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 6753 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 6754 if (Error != ASTContext::GE_None) 6755 return QualType(); 6756 6757 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 6758 if (!FT) 6759 return QualType(); 6760 6761 if (FT->getNumParams() != 1) 6762 return QualType(); 6763 6764 return FT->getParamType(0); 6765 } 6766 6767 // Returns the best absolute value function, or zero, based on type and 6768 // current absolute value function. 6769 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 6770 unsigned AbsFunctionKind) { 6771 unsigned BestKind = 0; 6772 uint64_t ArgSize = Context.getTypeSize(ArgType); 6773 for (unsigned Kind = AbsFunctionKind; Kind != 0; 6774 Kind = getLargerAbsoluteValueFunction(Kind)) { 6775 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 6776 if (Context.getTypeSize(ParamType) >= ArgSize) { 6777 if (BestKind == 0) 6778 BestKind = Kind; 6779 else if (Context.hasSameType(ParamType, ArgType)) { 6780 BestKind = Kind; 6781 break; 6782 } 6783 } 6784 } 6785 return BestKind; 6786 } 6787 6788 enum AbsoluteValueKind { 6789 AVK_Integer, 6790 AVK_Floating, 6791 AVK_Complex 6792 }; 6793 6794 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 6795 if (T->isIntegralOrEnumerationType()) 6796 return AVK_Integer; 6797 if (T->isRealFloatingType()) 6798 return AVK_Floating; 6799 if (T->isAnyComplexType()) 6800 return AVK_Complex; 6801 6802 llvm_unreachable("Type not integer, floating, or complex"); 6803 } 6804 6805 // Changes the absolute value function to a different type. Preserves whether 6806 // the function is a builtin. 6807 static unsigned changeAbsFunction(unsigned AbsKind, 6808 AbsoluteValueKind ValueKind) { 6809 switch (ValueKind) { 6810 case AVK_Integer: 6811 switch (AbsKind) { 6812 default: 6813 return 0; 6814 case Builtin::BI__builtin_fabsf: 6815 case Builtin::BI__builtin_fabs: 6816 case Builtin::BI__builtin_fabsl: 6817 case Builtin::BI__builtin_cabsf: 6818 case Builtin::BI__builtin_cabs: 6819 case Builtin::BI__builtin_cabsl: 6820 return Builtin::BI__builtin_abs; 6821 case Builtin::BIfabsf: 6822 case Builtin::BIfabs: 6823 case Builtin::BIfabsl: 6824 case Builtin::BIcabsf: 6825 case Builtin::BIcabs: 6826 case Builtin::BIcabsl: 6827 return Builtin::BIabs; 6828 } 6829 case AVK_Floating: 6830 switch (AbsKind) { 6831 default: 6832 return 0; 6833 case Builtin::BI__builtin_abs: 6834 case Builtin::BI__builtin_labs: 6835 case Builtin::BI__builtin_llabs: 6836 case Builtin::BI__builtin_cabsf: 6837 case Builtin::BI__builtin_cabs: 6838 case Builtin::BI__builtin_cabsl: 6839 return Builtin::BI__builtin_fabsf; 6840 case Builtin::BIabs: 6841 case Builtin::BIlabs: 6842 case Builtin::BIllabs: 6843 case Builtin::BIcabsf: 6844 case Builtin::BIcabs: 6845 case Builtin::BIcabsl: 6846 return Builtin::BIfabsf; 6847 } 6848 case AVK_Complex: 6849 switch (AbsKind) { 6850 default: 6851 return 0; 6852 case Builtin::BI__builtin_abs: 6853 case Builtin::BI__builtin_labs: 6854 case Builtin::BI__builtin_llabs: 6855 case Builtin::BI__builtin_fabsf: 6856 case Builtin::BI__builtin_fabs: 6857 case Builtin::BI__builtin_fabsl: 6858 return Builtin::BI__builtin_cabsf; 6859 case Builtin::BIabs: 6860 case Builtin::BIlabs: 6861 case Builtin::BIllabs: 6862 case Builtin::BIfabsf: 6863 case Builtin::BIfabs: 6864 case Builtin::BIfabsl: 6865 return Builtin::BIcabsf; 6866 } 6867 } 6868 llvm_unreachable("Unable to convert function"); 6869 } 6870 6871 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 6872 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 6873 if (!FnInfo) 6874 return 0; 6875 6876 switch (FDecl->getBuiltinID()) { 6877 default: 6878 return 0; 6879 case Builtin::BI__builtin_abs: 6880 case Builtin::BI__builtin_fabs: 6881 case Builtin::BI__builtin_fabsf: 6882 case Builtin::BI__builtin_fabsl: 6883 case Builtin::BI__builtin_labs: 6884 case Builtin::BI__builtin_llabs: 6885 case Builtin::BI__builtin_cabs: 6886 case Builtin::BI__builtin_cabsf: 6887 case Builtin::BI__builtin_cabsl: 6888 case Builtin::BIabs: 6889 case Builtin::BIlabs: 6890 case Builtin::BIllabs: 6891 case Builtin::BIfabs: 6892 case Builtin::BIfabsf: 6893 case Builtin::BIfabsl: 6894 case Builtin::BIcabs: 6895 case Builtin::BIcabsf: 6896 case Builtin::BIcabsl: 6897 return FDecl->getBuiltinID(); 6898 } 6899 llvm_unreachable("Unknown Builtin type"); 6900 } 6901 6902 // If the replacement is valid, emit a note with replacement function. 6903 // Additionally, suggest including the proper header if not already included. 6904 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 6905 unsigned AbsKind, QualType ArgType) { 6906 bool EmitHeaderHint = true; 6907 const char *HeaderName = nullptr; 6908 const char *FunctionName = nullptr; 6909 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 6910 FunctionName = "std::abs"; 6911 if (ArgType->isIntegralOrEnumerationType()) { 6912 HeaderName = "cstdlib"; 6913 } else if (ArgType->isRealFloatingType()) { 6914 HeaderName = "cmath"; 6915 } else { 6916 llvm_unreachable("Invalid Type"); 6917 } 6918 6919 // Lookup all std::abs 6920 if (NamespaceDecl *Std = S.getStdNamespace()) { 6921 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 6922 R.suppressDiagnostics(); 6923 S.LookupQualifiedName(R, Std); 6924 6925 for (const auto *I : R) { 6926 const FunctionDecl *FDecl = nullptr; 6927 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 6928 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 6929 } else { 6930 FDecl = dyn_cast<FunctionDecl>(I); 6931 } 6932 if (!FDecl) 6933 continue; 6934 6935 // Found std::abs(), check that they are the right ones. 6936 if (FDecl->getNumParams() != 1) 6937 continue; 6938 6939 // Check that the parameter type can handle the argument. 6940 QualType ParamType = FDecl->getParamDecl(0)->getType(); 6941 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 6942 S.Context.getTypeSize(ArgType) <= 6943 S.Context.getTypeSize(ParamType)) { 6944 // Found a function, don't need the header hint. 6945 EmitHeaderHint = false; 6946 break; 6947 } 6948 } 6949 } 6950 } else { 6951 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 6952 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 6953 6954 if (HeaderName) { 6955 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 6956 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 6957 R.suppressDiagnostics(); 6958 S.LookupName(R, S.getCurScope()); 6959 6960 if (R.isSingleResult()) { 6961 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 6962 if (FD && FD->getBuiltinID() == AbsKind) { 6963 EmitHeaderHint = false; 6964 } else { 6965 return; 6966 } 6967 } else if (!R.empty()) { 6968 return; 6969 } 6970 } 6971 } 6972 6973 S.Diag(Loc, diag::note_replace_abs_function) 6974 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 6975 6976 if (!HeaderName) 6977 return; 6978 6979 if (!EmitHeaderHint) 6980 return; 6981 6982 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 6983 << FunctionName; 6984 } 6985 6986 template <std::size_t StrLen> 6987 static bool IsStdFunction(const FunctionDecl *FDecl, 6988 const char (&Str)[StrLen]) { 6989 if (!FDecl) 6990 return false; 6991 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 6992 return false; 6993 if (!FDecl->isInStdNamespace()) 6994 return false; 6995 6996 return true; 6997 } 6998 6999 // Warn when using the wrong abs() function. 7000 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 7001 const FunctionDecl *FDecl) { 7002 if (Call->getNumArgs() != 1) 7003 return; 7004 7005 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 7006 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 7007 if (AbsKind == 0 && !IsStdAbs) 7008 return; 7009 7010 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7011 QualType ParamType = Call->getArg(0)->getType(); 7012 7013 // Unsigned types cannot be negative. Suggest removing the absolute value 7014 // function call. 7015 if (ArgType->isUnsignedIntegerType()) { 7016 const char *FunctionName = 7017 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 7018 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 7019 Diag(Call->getExprLoc(), diag::note_remove_abs) 7020 << FunctionName 7021 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 7022 return; 7023 } 7024 7025 // Taking the absolute value of a pointer is very suspicious, they probably 7026 // wanted to index into an array, dereference a pointer, call a function, etc. 7027 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 7028 unsigned DiagType = 0; 7029 if (ArgType->isFunctionType()) 7030 DiagType = 1; 7031 else if (ArgType->isArrayType()) 7032 DiagType = 2; 7033 7034 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 7035 return; 7036 } 7037 7038 // std::abs has overloads which prevent most of the absolute value problems 7039 // from occurring. 7040 if (IsStdAbs) 7041 return; 7042 7043 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 7044 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 7045 7046 // The argument and parameter are the same kind. Check if they are the right 7047 // size. 7048 if (ArgValueKind == ParamValueKind) { 7049 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 7050 return; 7051 7052 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 7053 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 7054 << FDecl << ArgType << ParamType; 7055 7056 if (NewAbsKind == 0) 7057 return; 7058 7059 emitReplacement(*this, Call->getExprLoc(), 7060 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7061 return; 7062 } 7063 7064 // ArgValueKind != ParamValueKind 7065 // The wrong type of absolute value function was used. Attempt to find the 7066 // proper one. 7067 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 7068 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 7069 if (NewAbsKind == 0) 7070 return; 7071 7072 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 7073 << FDecl << ParamValueKind << ArgValueKind; 7074 7075 emitReplacement(*this, Call->getExprLoc(), 7076 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7077 } 7078 7079 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 7080 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 7081 const FunctionDecl *FDecl) { 7082 if (!Call || !FDecl) return; 7083 7084 // Ignore template specializations and macros. 7085 if (inTemplateInstantiation()) return; 7086 if (Call->getExprLoc().isMacroID()) return; 7087 7088 // Only care about the one template argument, two function parameter std::max 7089 if (Call->getNumArgs() != 2) return; 7090 if (!IsStdFunction(FDecl, "max")) return; 7091 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 7092 if (!ArgList) return; 7093 if (ArgList->size() != 1) return; 7094 7095 // Check that template type argument is unsigned integer. 7096 const auto& TA = ArgList->get(0); 7097 if (TA.getKind() != TemplateArgument::Type) return; 7098 QualType ArgType = TA.getAsType(); 7099 if (!ArgType->isUnsignedIntegerType()) return; 7100 7101 // See if either argument is a literal zero. 7102 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 7103 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 7104 if (!MTE) return false; 7105 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 7106 if (!Num) return false; 7107 if (Num->getValue() != 0) return false; 7108 return true; 7109 }; 7110 7111 const Expr *FirstArg = Call->getArg(0); 7112 const Expr *SecondArg = Call->getArg(1); 7113 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 7114 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 7115 7116 // Only warn when exactly one argument is zero. 7117 if (IsFirstArgZero == IsSecondArgZero) return; 7118 7119 SourceRange FirstRange = FirstArg->getSourceRange(); 7120 SourceRange SecondRange = SecondArg->getSourceRange(); 7121 7122 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 7123 7124 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 7125 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 7126 7127 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 7128 SourceRange RemovalRange; 7129 if (IsFirstArgZero) { 7130 RemovalRange = SourceRange(FirstRange.getBegin(), 7131 SecondRange.getBegin().getLocWithOffset(-1)); 7132 } else { 7133 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 7134 SecondRange.getEnd()); 7135 } 7136 7137 Diag(Call->getExprLoc(), diag::note_remove_max_call) 7138 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 7139 << FixItHint::CreateRemoval(RemovalRange); 7140 } 7141 7142 //===--- CHECK: Standard memory functions ---------------------------------===// 7143 7144 /// \brief Takes the expression passed to the size_t parameter of functions 7145 /// such as memcmp, strncat, etc and warns if it's a comparison. 7146 /// 7147 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 7148 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 7149 IdentifierInfo *FnName, 7150 SourceLocation FnLoc, 7151 SourceLocation RParenLoc) { 7152 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 7153 if (!Size) 7154 return false; 7155 7156 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 7157 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 7158 return false; 7159 7160 SourceRange SizeRange = Size->getSourceRange(); 7161 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 7162 << SizeRange << FnName; 7163 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 7164 << FnName << FixItHint::CreateInsertion( 7165 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 7166 << FixItHint::CreateRemoval(RParenLoc); 7167 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 7168 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 7169 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 7170 ")"); 7171 7172 return true; 7173 } 7174 7175 /// \brief Determine whether the given type is or contains a dynamic class type 7176 /// (e.g., whether it has a vtable). 7177 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 7178 bool &IsContained) { 7179 // Look through array types while ignoring qualifiers. 7180 const Type *Ty = T->getBaseElementTypeUnsafe(); 7181 IsContained = false; 7182 7183 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 7184 RD = RD ? RD->getDefinition() : nullptr; 7185 if (!RD || RD->isInvalidDecl()) 7186 return nullptr; 7187 7188 if (RD->isDynamicClass()) 7189 return RD; 7190 7191 // Check all the fields. If any bases were dynamic, the class is dynamic. 7192 // It's impossible for a class to transitively contain itself by value, so 7193 // infinite recursion is impossible. 7194 for (auto *FD : RD->fields()) { 7195 bool SubContained; 7196 if (const CXXRecordDecl *ContainedRD = 7197 getContainedDynamicClass(FD->getType(), SubContained)) { 7198 IsContained = true; 7199 return ContainedRD; 7200 } 7201 } 7202 7203 return nullptr; 7204 } 7205 7206 /// \brief If E is a sizeof expression, returns its argument expression, 7207 /// otherwise returns NULL. 7208 static const Expr *getSizeOfExprArg(const Expr *E) { 7209 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7210 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7211 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 7212 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 7213 7214 return nullptr; 7215 } 7216 7217 /// \brief If E is a sizeof expression, returns its argument type. 7218 static QualType getSizeOfArgType(const Expr *E) { 7219 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7220 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7221 if (SizeOf->getKind() == clang::UETT_SizeOf) 7222 return SizeOf->getTypeOfArgument(); 7223 7224 return QualType(); 7225 } 7226 7227 /// \brief Check for dangerous or invalid arguments to memset(). 7228 /// 7229 /// This issues warnings on known problematic, dangerous or unspecified 7230 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 7231 /// function calls. 7232 /// 7233 /// \param Call The call expression to diagnose. 7234 void Sema::CheckMemaccessArguments(const CallExpr *Call, 7235 unsigned BId, 7236 IdentifierInfo *FnName) { 7237 assert(BId != 0); 7238 7239 // It is possible to have a non-standard definition of memset. Validate 7240 // we have enough arguments, and if not, abort further checking. 7241 unsigned ExpectedNumArgs = 7242 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 7243 if (Call->getNumArgs() < ExpectedNumArgs) 7244 return; 7245 7246 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 7247 BId == Builtin::BIstrndup ? 1 : 2); 7248 unsigned LenArg = 7249 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 7250 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 7251 7252 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 7253 Call->getLocStart(), Call->getRParenLoc())) 7254 return; 7255 7256 // We have special checking when the length is a sizeof expression. 7257 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 7258 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 7259 llvm::FoldingSetNodeID SizeOfArgID; 7260 7261 // Although widely used, 'bzero' is not a standard function. Be more strict 7262 // with the argument types before allowing diagnostics and only allow the 7263 // form bzero(ptr, sizeof(...)). 7264 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7265 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 7266 return; 7267 7268 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 7269 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 7270 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 7271 7272 QualType DestTy = Dest->getType(); 7273 QualType PointeeTy; 7274 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 7275 PointeeTy = DestPtrTy->getPointeeType(); 7276 7277 // Never warn about void type pointers. This can be used to suppress 7278 // false positives. 7279 if (PointeeTy->isVoidType()) 7280 continue; 7281 7282 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 7283 // actually comparing the expressions for equality. Because computing the 7284 // expression IDs can be expensive, we only do this if the diagnostic is 7285 // enabled. 7286 if (SizeOfArg && 7287 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 7288 SizeOfArg->getExprLoc())) { 7289 // We only compute IDs for expressions if the warning is enabled, and 7290 // cache the sizeof arg's ID. 7291 if (SizeOfArgID == llvm::FoldingSetNodeID()) 7292 SizeOfArg->Profile(SizeOfArgID, Context, true); 7293 llvm::FoldingSetNodeID DestID; 7294 Dest->Profile(DestID, Context, true); 7295 if (DestID == SizeOfArgID) { 7296 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 7297 // over sizeof(src) as well. 7298 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 7299 StringRef ReadableName = FnName->getName(); 7300 7301 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 7302 if (UnaryOp->getOpcode() == UO_AddrOf) 7303 ActionIdx = 1; // If its an address-of operator, just remove it. 7304 if (!PointeeTy->isIncompleteType() && 7305 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 7306 ActionIdx = 2; // If the pointee's size is sizeof(char), 7307 // suggest an explicit length. 7308 7309 // If the function is defined as a builtin macro, do not show macro 7310 // expansion. 7311 SourceLocation SL = SizeOfArg->getExprLoc(); 7312 SourceRange DSR = Dest->getSourceRange(); 7313 SourceRange SSR = SizeOfArg->getSourceRange(); 7314 SourceManager &SM = getSourceManager(); 7315 7316 if (SM.isMacroArgExpansion(SL)) { 7317 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 7318 SL = SM.getSpellingLoc(SL); 7319 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 7320 SM.getSpellingLoc(DSR.getEnd())); 7321 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 7322 SM.getSpellingLoc(SSR.getEnd())); 7323 } 7324 7325 DiagRuntimeBehavior(SL, SizeOfArg, 7326 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 7327 << ReadableName 7328 << PointeeTy 7329 << DestTy 7330 << DSR 7331 << SSR); 7332 DiagRuntimeBehavior(SL, SizeOfArg, 7333 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 7334 << ActionIdx 7335 << SSR); 7336 7337 break; 7338 } 7339 } 7340 7341 // Also check for cases where the sizeof argument is the exact same 7342 // type as the memory argument, and where it points to a user-defined 7343 // record type. 7344 if (SizeOfArgTy != QualType()) { 7345 if (PointeeTy->isRecordType() && 7346 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 7347 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 7348 PDiag(diag::warn_sizeof_pointer_type_memaccess) 7349 << FnName << SizeOfArgTy << ArgIdx 7350 << PointeeTy << Dest->getSourceRange() 7351 << LenExpr->getSourceRange()); 7352 break; 7353 } 7354 } 7355 } else if (DestTy->isArrayType()) { 7356 PointeeTy = DestTy; 7357 } 7358 7359 if (PointeeTy == QualType()) 7360 continue; 7361 7362 // Always complain about dynamic classes. 7363 bool IsContained; 7364 if (const CXXRecordDecl *ContainedRD = 7365 getContainedDynamicClass(PointeeTy, IsContained)) { 7366 7367 unsigned OperationType = 0; 7368 // "overwritten" if we're warning about the destination for any call 7369 // but memcmp; otherwise a verb appropriate to the call. 7370 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 7371 if (BId == Builtin::BImemcpy) 7372 OperationType = 1; 7373 else if(BId == Builtin::BImemmove) 7374 OperationType = 2; 7375 else if (BId == Builtin::BImemcmp) 7376 OperationType = 3; 7377 } 7378 7379 DiagRuntimeBehavior( 7380 Dest->getExprLoc(), Dest, 7381 PDiag(diag::warn_dyn_class_memaccess) 7382 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 7383 << FnName << IsContained << ContainedRD << OperationType 7384 << Call->getCallee()->getSourceRange()); 7385 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 7386 BId != Builtin::BImemset) 7387 DiagRuntimeBehavior( 7388 Dest->getExprLoc(), Dest, 7389 PDiag(diag::warn_arc_object_memaccess) 7390 << ArgIdx << FnName << PointeeTy 7391 << Call->getCallee()->getSourceRange()); 7392 else 7393 continue; 7394 7395 DiagRuntimeBehavior( 7396 Dest->getExprLoc(), Dest, 7397 PDiag(diag::note_bad_memaccess_silence) 7398 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 7399 break; 7400 } 7401 } 7402 7403 // A little helper routine: ignore addition and subtraction of integer literals. 7404 // This intentionally does not ignore all integer constant expressions because 7405 // we don't want to remove sizeof(). 7406 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 7407 Ex = Ex->IgnoreParenCasts(); 7408 7409 for (;;) { 7410 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 7411 if (!BO || !BO->isAdditiveOp()) 7412 break; 7413 7414 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 7415 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 7416 7417 if (isa<IntegerLiteral>(RHS)) 7418 Ex = LHS; 7419 else if (isa<IntegerLiteral>(LHS)) 7420 Ex = RHS; 7421 else 7422 break; 7423 } 7424 7425 return Ex; 7426 } 7427 7428 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 7429 ASTContext &Context) { 7430 // Only handle constant-sized or VLAs, but not flexible members. 7431 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 7432 // Only issue the FIXIT for arrays of size > 1. 7433 if (CAT->getSize().getSExtValue() <= 1) 7434 return false; 7435 } else if (!Ty->isVariableArrayType()) { 7436 return false; 7437 } 7438 return true; 7439 } 7440 7441 // Warn if the user has made the 'size' argument to strlcpy or strlcat 7442 // be the size of the source, instead of the destination. 7443 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 7444 IdentifierInfo *FnName) { 7445 7446 // Don't crash if the user has the wrong number of arguments 7447 unsigned NumArgs = Call->getNumArgs(); 7448 if ((NumArgs != 3) && (NumArgs != 4)) 7449 return; 7450 7451 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 7452 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 7453 const Expr *CompareWithSrc = nullptr; 7454 7455 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 7456 Call->getLocStart(), Call->getRParenLoc())) 7457 return; 7458 7459 // Look for 'strlcpy(dst, x, sizeof(x))' 7460 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 7461 CompareWithSrc = Ex; 7462 else { 7463 // Look for 'strlcpy(dst, x, strlen(x))' 7464 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 7465 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 7466 SizeCall->getNumArgs() == 1) 7467 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 7468 } 7469 } 7470 7471 if (!CompareWithSrc) 7472 return; 7473 7474 // Determine if the argument to sizeof/strlen is equal to the source 7475 // argument. In principle there's all kinds of things you could do 7476 // here, for instance creating an == expression and evaluating it with 7477 // EvaluateAsBooleanCondition, but this uses a more direct technique: 7478 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 7479 if (!SrcArgDRE) 7480 return; 7481 7482 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 7483 if (!CompareWithSrcDRE || 7484 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 7485 return; 7486 7487 const Expr *OriginalSizeArg = Call->getArg(2); 7488 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 7489 << OriginalSizeArg->getSourceRange() << FnName; 7490 7491 // Output a FIXIT hint if the destination is an array (rather than a 7492 // pointer to an array). This could be enhanced to handle some 7493 // pointers if we know the actual size, like if DstArg is 'array+2' 7494 // we could say 'sizeof(array)-2'. 7495 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 7496 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 7497 return; 7498 7499 SmallString<128> sizeString; 7500 llvm::raw_svector_ostream OS(sizeString); 7501 OS << "sizeof("; 7502 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7503 OS << ")"; 7504 7505 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 7506 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 7507 OS.str()); 7508 } 7509 7510 /// Check if two expressions refer to the same declaration. 7511 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 7512 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 7513 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 7514 return D1->getDecl() == D2->getDecl(); 7515 return false; 7516 } 7517 7518 static const Expr *getStrlenExprArg(const Expr *E) { 7519 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7520 const FunctionDecl *FD = CE->getDirectCallee(); 7521 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 7522 return nullptr; 7523 return CE->getArg(0)->IgnoreParenCasts(); 7524 } 7525 return nullptr; 7526 } 7527 7528 // Warn on anti-patterns as the 'size' argument to strncat. 7529 // The correct size argument should look like following: 7530 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 7531 void Sema::CheckStrncatArguments(const CallExpr *CE, 7532 IdentifierInfo *FnName) { 7533 // Don't crash if the user has the wrong number of arguments. 7534 if (CE->getNumArgs() < 3) 7535 return; 7536 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 7537 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 7538 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 7539 7540 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 7541 CE->getRParenLoc())) 7542 return; 7543 7544 // Identify common expressions, which are wrongly used as the size argument 7545 // to strncat and may lead to buffer overflows. 7546 unsigned PatternType = 0; 7547 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 7548 // - sizeof(dst) 7549 if (referToTheSameDecl(SizeOfArg, DstArg)) 7550 PatternType = 1; 7551 // - sizeof(src) 7552 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 7553 PatternType = 2; 7554 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 7555 if (BE->getOpcode() == BO_Sub) { 7556 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 7557 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 7558 // - sizeof(dst) - strlen(dst) 7559 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 7560 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 7561 PatternType = 1; 7562 // - sizeof(src) - (anything) 7563 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 7564 PatternType = 2; 7565 } 7566 } 7567 7568 if (PatternType == 0) 7569 return; 7570 7571 // Generate the diagnostic. 7572 SourceLocation SL = LenArg->getLocStart(); 7573 SourceRange SR = LenArg->getSourceRange(); 7574 SourceManager &SM = getSourceManager(); 7575 7576 // If the function is defined as a builtin macro, do not show macro expansion. 7577 if (SM.isMacroArgExpansion(SL)) { 7578 SL = SM.getSpellingLoc(SL); 7579 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 7580 SM.getSpellingLoc(SR.getEnd())); 7581 } 7582 7583 // Check if the destination is an array (rather than a pointer to an array). 7584 QualType DstTy = DstArg->getType(); 7585 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 7586 Context); 7587 if (!isKnownSizeArray) { 7588 if (PatternType == 1) 7589 Diag(SL, diag::warn_strncat_wrong_size) << SR; 7590 else 7591 Diag(SL, diag::warn_strncat_src_size) << SR; 7592 return; 7593 } 7594 7595 if (PatternType == 1) 7596 Diag(SL, diag::warn_strncat_large_size) << SR; 7597 else 7598 Diag(SL, diag::warn_strncat_src_size) << SR; 7599 7600 SmallString<128> sizeString; 7601 llvm::raw_svector_ostream OS(sizeString); 7602 OS << "sizeof("; 7603 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7604 OS << ") - "; 7605 OS << "strlen("; 7606 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7607 OS << ") - 1"; 7608 7609 Diag(SL, diag::note_strncat_wrong_size) 7610 << FixItHint::CreateReplacement(SR, OS.str()); 7611 } 7612 7613 //===--- CHECK: Return Address of Stack Variable --------------------------===// 7614 7615 static const Expr *EvalVal(const Expr *E, 7616 SmallVectorImpl<const DeclRefExpr *> &refVars, 7617 const Decl *ParentDecl); 7618 static const Expr *EvalAddr(const Expr *E, 7619 SmallVectorImpl<const DeclRefExpr *> &refVars, 7620 const Decl *ParentDecl); 7621 7622 /// CheckReturnStackAddr - Check if a return statement returns the address 7623 /// of a stack variable. 7624 static void 7625 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 7626 SourceLocation ReturnLoc) { 7627 7628 const Expr *stackE = nullptr; 7629 SmallVector<const DeclRefExpr *, 8> refVars; 7630 7631 // Perform checking for returned stack addresses, local blocks, 7632 // label addresses or references to temporaries. 7633 if (lhsType->isPointerType() || 7634 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 7635 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 7636 } else if (lhsType->isReferenceType()) { 7637 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 7638 } 7639 7640 if (!stackE) 7641 return; // Nothing suspicious was found. 7642 7643 // Parameters are initialized in the calling scope, so taking the address 7644 // of a parameter reference doesn't need a warning. 7645 for (auto *DRE : refVars) 7646 if (isa<ParmVarDecl>(DRE->getDecl())) 7647 return; 7648 7649 SourceLocation diagLoc; 7650 SourceRange diagRange; 7651 if (refVars.empty()) { 7652 diagLoc = stackE->getLocStart(); 7653 diagRange = stackE->getSourceRange(); 7654 } else { 7655 // We followed through a reference variable. 'stackE' contains the 7656 // problematic expression but we will warn at the return statement pointing 7657 // at the reference variable. We will later display the "trail" of 7658 // reference variables using notes. 7659 diagLoc = refVars[0]->getLocStart(); 7660 diagRange = refVars[0]->getSourceRange(); 7661 } 7662 7663 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 7664 // address of local var 7665 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 7666 << DR->getDecl()->getDeclName() << diagRange; 7667 } else if (isa<BlockExpr>(stackE)) { // local block. 7668 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 7669 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 7670 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 7671 } else { // local temporary. 7672 // If there is an LValue->RValue conversion, then the value of the 7673 // reference type is used, not the reference. 7674 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 7675 if (ICE->getCastKind() == CK_LValueToRValue) { 7676 return; 7677 } 7678 } 7679 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 7680 << lhsType->isReferenceType() << diagRange; 7681 } 7682 7683 // Display the "trail" of reference variables that we followed until we 7684 // found the problematic expression using notes. 7685 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 7686 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 7687 // If this var binds to another reference var, show the range of the next 7688 // var, otherwise the var binds to the problematic expression, in which case 7689 // show the range of the expression. 7690 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 7691 : stackE->getSourceRange(); 7692 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 7693 << VD->getDeclName() << range; 7694 } 7695 } 7696 7697 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 7698 /// check if the expression in a return statement evaluates to an address 7699 /// to a location on the stack, a local block, an address of a label, or a 7700 /// reference to local temporary. The recursion is used to traverse the 7701 /// AST of the return expression, with recursion backtracking when we 7702 /// encounter a subexpression that (1) clearly does not lead to one of the 7703 /// above problematic expressions (2) is something we cannot determine leads to 7704 /// a problematic expression based on such local checking. 7705 /// 7706 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 7707 /// the expression that they point to. Such variables are added to the 7708 /// 'refVars' vector so that we know what the reference variable "trail" was. 7709 /// 7710 /// EvalAddr processes expressions that are pointers that are used as 7711 /// references (and not L-values). EvalVal handles all other values. 7712 /// At the base case of the recursion is a check for the above problematic 7713 /// expressions. 7714 /// 7715 /// This implementation handles: 7716 /// 7717 /// * pointer-to-pointer casts 7718 /// * implicit conversions from array references to pointers 7719 /// * taking the address of fields 7720 /// * arbitrary interplay between "&" and "*" operators 7721 /// * pointer arithmetic from an address of a stack variable 7722 /// * taking the address of an array element where the array is on the stack 7723 static const Expr *EvalAddr(const Expr *E, 7724 SmallVectorImpl<const DeclRefExpr *> &refVars, 7725 const Decl *ParentDecl) { 7726 if (E->isTypeDependent()) 7727 return nullptr; 7728 7729 // We should only be called for evaluating pointer expressions. 7730 assert((E->getType()->isAnyPointerType() || 7731 E->getType()->isBlockPointerType() || 7732 E->getType()->isObjCQualifiedIdType()) && 7733 "EvalAddr only works on pointers"); 7734 7735 E = E->IgnoreParens(); 7736 7737 // Our "symbolic interpreter" is just a dispatch off the currently 7738 // viewed AST node. We then recursively traverse the AST by calling 7739 // EvalAddr and EvalVal appropriately. 7740 switch (E->getStmtClass()) { 7741 case Stmt::DeclRefExprClass: { 7742 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7743 7744 // If we leave the immediate function, the lifetime isn't about to end. 7745 if (DR->refersToEnclosingVariableOrCapture()) 7746 return nullptr; 7747 7748 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 7749 // If this is a reference variable, follow through to the expression that 7750 // it points to. 7751 if (V->hasLocalStorage() && 7752 V->getType()->isReferenceType() && V->hasInit()) { 7753 // Add the reference variable to the "trail". 7754 refVars.push_back(DR); 7755 return EvalAddr(V->getInit(), refVars, ParentDecl); 7756 } 7757 7758 return nullptr; 7759 } 7760 7761 case Stmt::UnaryOperatorClass: { 7762 // The only unary operator that make sense to handle here 7763 // is AddrOf. All others don't make sense as pointers. 7764 const UnaryOperator *U = cast<UnaryOperator>(E); 7765 7766 if (U->getOpcode() == UO_AddrOf) 7767 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 7768 return nullptr; 7769 } 7770 7771 case Stmt::BinaryOperatorClass: { 7772 // Handle pointer arithmetic. All other binary operators are not valid 7773 // in this context. 7774 const BinaryOperator *B = cast<BinaryOperator>(E); 7775 BinaryOperatorKind op = B->getOpcode(); 7776 7777 if (op != BO_Add && op != BO_Sub) 7778 return nullptr; 7779 7780 const Expr *Base = B->getLHS(); 7781 7782 // Determine which argument is the real pointer base. It could be 7783 // the RHS argument instead of the LHS. 7784 if (!Base->getType()->isPointerType()) 7785 Base = B->getRHS(); 7786 7787 assert(Base->getType()->isPointerType()); 7788 return EvalAddr(Base, refVars, ParentDecl); 7789 } 7790 7791 // For conditional operators we need to see if either the LHS or RHS are 7792 // valid DeclRefExpr*s. If one of them is valid, we return it. 7793 case Stmt::ConditionalOperatorClass: { 7794 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7795 7796 // Handle the GNU extension for missing LHS. 7797 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 7798 if (const Expr *LHSExpr = C->getLHS()) { 7799 // In C++, we can have a throw-expression, which has 'void' type. 7800 if (!LHSExpr->getType()->isVoidType()) 7801 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 7802 return LHS; 7803 } 7804 7805 // In C++, we can have a throw-expression, which has 'void' type. 7806 if (C->getRHS()->getType()->isVoidType()) 7807 return nullptr; 7808 7809 return EvalAddr(C->getRHS(), refVars, ParentDecl); 7810 } 7811 7812 case Stmt::BlockExprClass: 7813 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 7814 return E; // local block. 7815 return nullptr; 7816 7817 case Stmt::AddrLabelExprClass: 7818 return E; // address of label. 7819 7820 case Stmt::ExprWithCleanupsClass: 7821 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7822 ParentDecl); 7823 7824 // For casts, we need to handle conversions from arrays to 7825 // pointer values, and pointer-to-pointer conversions. 7826 case Stmt::ImplicitCastExprClass: 7827 case Stmt::CStyleCastExprClass: 7828 case Stmt::CXXFunctionalCastExprClass: 7829 case Stmt::ObjCBridgedCastExprClass: 7830 case Stmt::CXXStaticCastExprClass: 7831 case Stmt::CXXDynamicCastExprClass: 7832 case Stmt::CXXConstCastExprClass: 7833 case Stmt::CXXReinterpretCastExprClass: { 7834 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 7835 switch (cast<CastExpr>(E)->getCastKind()) { 7836 case CK_LValueToRValue: 7837 case CK_NoOp: 7838 case CK_BaseToDerived: 7839 case CK_DerivedToBase: 7840 case CK_UncheckedDerivedToBase: 7841 case CK_Dynamic: 7842 case CK_CPointerToObjCPointerCast: 7843 case CK_BlockPointerToObjCPointerCast: 7844 case CK_AnyPointerToBlockPointerCast: 7845 return EvalAddr(SubExpr, refVars, ParentDecl); 7846 7847 case CK_ArrayToPointerDecay: 7848 return EvalVal(SubExpr, refVars, ParentDecl); 7849 7850 case CK_BitCast: 7851 if (SubExpr->getType()->isAnyPointerType() || 7852 SubExpr->getType()->isBlockPointerType() || 7853 SubExpr->getType()->isObjCQualifiedIdType()) 7854 return EvalAddr(SubExpr, refVars, ParentDecl); 7855 else 7856 return nullptr; 7857 7858 default: 7859 return nullptr; 7860 } 7861 } 7862 7863 case Stmt::MaterializeTemporaryExprClass: 7864 if (const Expr *Result = 7865 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7866 refVars, ParentDecl)) 7867 return Result; 7868 return E; 7869 7870 // Everything else: we simply don't reason about them. 7871 default: 7872 return nullptr; 7873 } 7874 } 7875 7876 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 7877 /// See the comments for EvalAddr for more details. 7878 static const Expr *EvalVal(const Expr *E, 7879 SmallVectorImpl<const DeclRefExpr *> &refVars, 7880 const Decl *ParentDecl) { 7881 do { 7882 // We should only be called for evaluating non-pointer expressions, or 7883 // expressions with a pointer type that are not used as references but 7884 // instead 7885 // are l-values (e.g., DeclRefExpr with a pointer type). 7886 7887 // Our "symbolic interpreter" is just a dispatch off the currently 7888 // viewed AST node. We then recursively traverse the AST by calling 7889 // EvalAddr and EvalVal appropriately. 7890 7891 E = E->IgnoreParens(); 7892 switch (E->getStmtClass()) { 7893 case Stmt::ImplicitCastExprClass: { 7894 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 7895 if (IE->getValueKind() == VK_LValue) { 7896 E = IE->getSubExpr(); 7897 continue; 7898 } 7899 return nullptr; 7900 } 7901 7902 case Stmt::ExprWithCleanupsClass: 7903 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7904 ParentDecl); 7905 7906 case Stmt::DeclRefExprClass: { 7907 // When we hit a DeclRefExpr we are looking at code that refers to a 7908 // variable's name. If it's not a reference variable we check if it has 7909 // local storage within the function, and if so, return the expression. 7910 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7911 7912 // If we leave the immediate function, the lifetime isn't about to end. 7913 if (DR->refersToEnclosingVariableOrCapture()) 7914 return nullptr; 7915 7916 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 7917 // Check if it refers to itself, e.g. "int& i = i;". 7918 if (V == ParentDecl) 7919 return DR; 7920 7921 if (V->hasLocalStorage()) { 7922 if (!V->getType()->isReferenceType()) 7923 return DR; 7924 7925 // Reference variable, follow through to the expression that 7926 // it points to. 7927 if (V->hasInit()) { 7928 // Add the reference variable to the "trail". 7929 refVars.push_back(DR); 7930 return EvalVal(V->getInit(), refVars, V); 7931 } 7932 } 7933 } 7934 7935 return nullptr; 7936 } 7937 7938 case Stmt::UnaryOperatorClass: { 7939 // The only unary operator that make sense to handle here 7940 // is Deref. All others don't resolve to a "name." This includes 7941 // handling all sorts of rvalues passed to a unary operator. 7942 const UnaryOperator *U = cast<UnaryOperator>(E); 7943 7944 if (U->getOpcode() == UO_Deref) 7945 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 7946 7947 return nullptr; 7948 } 7949 7950 case Stmt::ArraySubscriptExprClass: { 7951 // Array subscripts are potential references to data on the stack. We 7952 // retrieve the DeclRefExpr* for the array variable if it indeed 7953 // has local storage. 7954 const auto *ASE = cast<ArraySubscriptExpr>(E); 7955 if (ASE->isTypeDependent()) 7956 return nullptr; 7957 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 7958 } 7959 7960 case Stmt::OMPArraySectionExprClass: { 7961 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 7962 ParentDecl); 7963 } 7964 7965 case Stmt::ConditionalOperatorClass: { 7966 // For conditional operators we need to see if either the LHS or RHS are 7967 // non-NULL Expr's. If one is non-NULL, we return it. 7968 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7969 7970 // Handle the GNU extension for missing LHS. 7971 if (const Expr *LHSExpr = C->getLHS()) { 7972 // In C++, we can have a throw-expression, which has 'void' type. 7973 if (!LHSExpr->getType()->isVoidType()) 7974 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 7975 return LHS; 7976 } 7977 7978 // In C++, we can have a throw-expression, which has 'void' type. 7979 if (C->getRHS()->getType()->isVoidType()) 7980 return nullptr; 7981 7982 return EvalVal(C->getRHS(), refVars, ParentDecl); 7983 } 7984 7985 // Accesses to members are potential references to data on the stack. 7986 case Stmt::MemberExprClass: { 7987 const MemberExpr *M = cast<MemberExpr>(E); 7988 7989 // Check for indirect access. We only want direct field accesses. 7990 if (M->isArrow()) 7991 return nullptr; 7992 7993 // Check whether the member type is itself a reference, in which case 7994 // we're not going to refer to the member, but to what the member refers 7995 // to. 7996 if (M->getMemberDecl()->getType()->isReferenceType()) 7997 return nullptr; 7998 7999 return EvalVal(M->getBase(), refVars, ParentDecl); 8000 } 8001 8002 case Stmt::MaterializeTemporaryExprClass: 8003 if (const Expr *Result = 8004 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8005 refVars, ParentDecl)) 8006 return Result; 8007 return E; 8008 8009 default: 8010 // Check that we don't return or take the address of a reference to a 8011 // temporary. This is only useful in C++. 8012 if (!E->isTypeDependent() && E->isRValue()) 8013 return E; 8014 8015 // Everything else: we simply don't reason about them. 8016 return nullptr; 8017 } 8018 } while (true); 8019 } 8020 8021 void 8022 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 8023 SourceLocation ReturnLoc, 8024 bool isObjCMethod, 8025 const AttrVec *Attrs, 8026 const FunctionDecl *FD) { 8027 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 8028 8029 // Check if the return value is null but should not be. 8030 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 8031 (!isObjCMethod && isNonNullType(Context, lhsType))) && 8032 CheckNonNullExpr(*this, RetValExp)) 8033 Diag(ReturnLoc, diag::warn_null_ret) 8034 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 8035 8036 // C++11 [basic.stc.dynamic.allocation]p4: 8037 // If an allocation function declared with a non-throwing 8038 // exception-specification fails to allocate storage, it shall return 8039 // a null pointer. Any other allocation function that fails to allocate 8040 // storage shall indicate failure only by throwing an exception [...] 8041 if (FD) { 8042 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 8043 if (Op == OO_New || Op == OO_Array_New) { 8044 const FunctionProtoType *Proto 8045 = FD->getType()->castAs<FunctionProtoType>(); 8046 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 8047 CheckNonNullExpr(*this, RetValExp)) 8048 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 8049 << FD << getLangOpts().CPlusPlus11; 8050 } 8051 } 8052 } 8053 8054 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 8055 8056 /// Check for comparisons of floating point operands using != and ==. 8057 /// Issue a warning if these are no self-comparisons, as they are not likely 8058 /// to do what the programmer intended. 8059 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 8060 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 8061 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 8062 8063 // Special case: check for x == x (which is OK). 8064 // Do not emit warnings for such cases. 8065 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 8066 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 8067 if (DRL->getDecl() == DRR->getDecl()) 8068 return; 8069 8070 // Special case: check for comparisons against literals that can be exactly 8071 // represented by APFloat. In such cases, do not emit a warning. This 8072 // is a heuristic: often comparison against such literals are used to 8073 // detect if a value in a variable has not changed. This clearly can 8074 // lead to false negatives. 8075 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 8076 if (FLL->isExact()) 8077 return; 8078 } else 8079 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 8080 if (FLR->isExact()) 8081 return; 8082 8083 // Check for comparisons with builtin types. 8084 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 8085 if (CL->getBuiltinCallee()) 8086 return; 8087 8088 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 8089 if (CR->getBuiltinCallee()) 8090 return; 8091 8092 // Emit the diagnostic. 8093 Diag(Loc, diag::warn_floatingpoint_eq) 8094 << LHS->getSourceRange() << RHS->getSourceRange(); 8095 } 8096 8097 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 8098 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 8099 8100 namespace { 8101 8102 /// Structure recording the 'active' range of an integer-valued 8103 /// expression. 8104 struct IntRange { 8105 /// The number of bits active in the int. 8106 unsigned Width; 8107 8108 /// True if the int is known not to have negative values. 8109 bool NonNegative; 8110 8111 IntRange(unsigned Width, bool NonNegative) 8112 : Width(Width), NonNegative(NonNegative) 8113 {} 8114 8115 /// Returns the range of the bool type. 8116 static IntRange forBoolType() { 8117 return IntRange(1, true); 8118 } 8119 8120 /// Returns the range of an opaque value of the given integral type. 8121 static IntRange forValueOfType(ASTContext &C, QualType T) { 8122 return forValueOfCanonicalType(C, 8123 T->getCanonicalTypeInternal().getTypePtr()); 8124 } 8125 8126 /// Returns the range of an opaque value of a canonical integral type. 8127 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 8128 assert(T->isCanonicalUnqualified()); 8129 8130 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8131 T = VT->getElementType().getTypePtr(); 8132 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8133 T = CT->getElementType().getTypePtr(); 8134 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8135 T = AT->getValueType().getTypePtr(); 8136 8137 // For enum types, use the known bit width of the enumerators. 8138 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 8139 EnumDecl *Enum = ET->getDecl(); 8140 if (!Enum->isCompleteDefinition()) 8141 return IntRange(C.getIntWidth(QualType(T, 0)), false); 8142 8143 unsigned NumPositive = Enum->getNumPositiveBits(); 8144 unsigned NumNegative = Enum->getNumNegativeBits(); 8145 8146 if (NumNegative == 0) 8147 return IntRange(NumPositive, true/*NonNegative*/); 8148 else 8149 return IntRange(std::max(NumPositive + 1, NumNegative), 8150 false/*NonNegative*/); 8151 } 8152 8153 const BuiltinType *BT = cast<BuiltinType>(T); 8154 assert(BT->isInteger()); 8155 8156 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8157 } 8158 8159 /// Returns the "target" range of a canonical integral type, i.e. 8160 /// the range of values expressible in the type. 8161 /// 8162 /// This matches forValueOfCanonicalType except that enums have the 8163 /// full range of their type, not the range of their enumerators. 8164 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 8165 assert(T->isCanonicalUnqualified()); 8166 8167 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8168 T = VT->getElementType().getTypePtr(); 8169 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8170 T = CT->getElementType().getTypePtr(); 8171 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8172 T = AT->getValueType().getTypePtr(); 8173 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8174 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 8175 8176 const BuiltinType *BT = cast<BuiltinType>(T); 8177 assert(BT->isInteger()); 8178 8179 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8180 } 8181 8182 /// Returns the supremum of two ranges: i.e. their conservative merge. 8183 static IntRange join(IntRange L, IntRange R) { 8184 return IntRange(std::max(L.Width, R.Width), 8185 L.NonNegative && R.NonNegative); 8186 } 8187 8188 /// Returns the infinum of two ranges: i.e. their aggressive merge. 8189 static IntRange meet(IntRange L, IntRange R) { 8190 return IntRange(std::min(L.Width, R.Width), 8191 L.NonNegative || R.NonNegative); 8192 } 8193 }; 8194 8195 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 8196 if (value.isSigned() && value.isNegative()) 8197 return IntRange(value.getMinSignedBits(), false); 8198 8199 if (value.getBitWidth() > MaxWidth) 8200 value = value.trunc(MaxWidth); 8201 8202 // isNonNegative() just checks the sign bit without considering 8203 // signedness. 8204 return IntRange(value.getActiveBits(), true); 8205 } 8206 8207 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 8208 unsigned MaxWidth) { 8209 if (result.isInt()) 8210 return GetValueRange(C, result.getInt(), MaxWidth); 8211 8212 if (result.isVector()) { 8213 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 8214 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 8215 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 8216 R = IntRange::join(R, El); 8217 } 8218 return R; 8219 } 8220 8221 if (result.isComplexInt()) { 8222 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 8223 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 8224 return IntRange::join(R, I); 8225 } 8226 8227 // This can happen with lossless casts to intptr_t of "based" lvalues. 8228 // Assume it might use arbitrary bits. 8229 // FIXME: The only reason we need to pass the type in here is to get 8230 // the sign right on this one case. It would be nice if APValue 8231 // preserved this. 8232 assert(result.isLValue() || result.isAddrLabelDiff()); 8233 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 8234 } 8235 8236 QualType GetExprType(const Expr *E) { 8237 QualType Ty = E->getType(); 8238 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 8239 Ty = AtomicRHS->getValueType(); 8240 return Ty; 8241 } 8242 8243 /// Pseudo-evaluate the given integer expression, estimating the 8244 /// range of values it might take. 8245 /// 8246 /// \param MaxWidth - the width to which the value will be truncated 8247 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 8248 E = E->IgnoreParens(); 8249 8250 // Try a full evaluation first. 8251 Expr::EvalResult result; 8252 if (E->EvaluateAsRValue(result, C)) 8253 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 8254 8255 // I think we only want to look through implicit casts here; if the 8256 // user has an explicit widening cast, we should treat the value as 8257 // being of the new, wider type. 8258 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 8259 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 8260 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 8261 8262 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 8263 8264 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 8265 CE->getCastKind() == CK_BooleanToSignedIntegral; 8266 8267 // Assume that non-integer casts can span the full range of the type. 8268 if (!isIntegerCast) 8269 return OutputTypeRange; 8270 8271 IntRange SubRange 8272 = GetExprRange(C, CE->getSubExpr(), 8273 std::min(MaxWidth, OutputTypeRange.Width)); 8274 8275 // Bail out if the subexpr's range is as wide as the cast type. 8276 if (SubRange.Width >= OutputTypeRange.Width) 8277 return OutputTypeRange; 8278 8279 // Otherwise, we take the smaller width, and we're non-negative if 8280 // either the output type or the subexpr is. 8281 return IntRange(SubRange.Width, 8282 SubRange.NonNegative || OutputTypeRange.NonNegative); 8283 } 8284 8285 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 8286 // If we can fold the condition, just take that operand. 8287 bool CondResult; 8288 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 8289 return GetExprRange(C, CondResult ? CO->getTrueExpr() 8290 : CO->getFalseExpr(), 8291 MaxWidth); 8292 8293 // Otherwise, conservatively merge. 8294 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 8295 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 8296 return IntRange::join(L, R); 8297 } 8298 8299 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 8300 switch (BO->getOpcode()) { 8301 8302 // Boolean-valued operations are single-bit and positive. 8303 case BO_LAnd: 8304 case BO_LOr: 8305 case BO_LT: 8306 case BO_GT: 8307 case BO_LE: 8308 case BO_GE: 8309 case BO_EQ: 8310 case BO_NE: 8311 return IntRange::forBoolType(); 8312 8313 // The type of the assignments is the type of the LHS, so the RHS 8314 // is not necessarily the same type. 8315 case BO_MulAssign: 8316 case BO_DivAssign: 8317 case BO_RemAssign: 8318 case BO_AddAssign: 8319 case BO_SubAssign: 8320 case BO_XorAssign: 8321 case BO_OrAssign: 8322 // TODO: bitfields? 8323 return IntRange::forValueOfType(C, GetExprType(E)); 8324 8325 // Simple assignments just pass through the RHS, which will have 8326 // been coerced to the LHS type. 8327 case BO_Assign: 8328 // TODO: bitfields? 8329 return GetExprRange(C, BO->getRHS(), MaxWidth); 8330 8331 // Operations with opaque sources are black-listed. 8332 case BO_PtrMemD: 8333 case BO_PtrMemI: 8334 return IntRange::forValueOfType(C, GetExprType(E)); 8335 8336 // Bitwise-and uses the *infinum* of the two source ranges. 8337 case BO_And: 8338 case BO_AndAssign: 8339 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 8340 GetExprRange(C, BO->getRHS(), MaxWidth)); 8341 8342 // Left shift gets black-listed based on a judgement call. 8343 case BO_Shl: 8344 // ...except that we want to treat '1 << (blah)' as logically 8345 // positive. It's an important idiom. 8346 if (IntegerLiteral *I 8347 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 8348 if (I->getValue() == 1) { 8349 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 8350 return IntRange(R.Width, /*NonNegative*/ true); 8351 } 8352 } 8353 // fallthrough 8354 8355 case BO_ShlAssign: 8356 return IntRange::forValueOfType(C, GetExprType(E)); 8357 8358 // Right shift by a constant can narrow its left argument. 8359 case BO_Shr: 8360 case BO_ShrAssign: { 8361 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8362 8363 // If the shift amount is a positive constant, drop the width by 8364 // that much. 8365 llvm::APSInt shift; 8366 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 8367 shift.isNonNegative()) { 8368 unsigned zext = shift.getZExtValue(); 8369 if (zext >= L.Width) 8370 L.Width = (L.NonNegative ? 0 : 1); 8371 else 8372 L.Width -= zext; 8373 } 8374 8375 return L; 8376 } 8377 8378 // Comma acts as its right operand. 8379 case BO_Comma: 8380 return GetExprRange(C, BO->getRHS(), MaxWidth); 8381 8382 // Black-list pointer subtractions. 8383 case BO_Sub: 8384 if (BO->getLHS()->getType()->isPointerType()) 8385 return IntRange::forValueOfType(C, GetExprType(E)); 8386 break; 8387 8388 // The width of a division result is mostly determined by the size 8389 // of the LHS. 8390 case BO_Div: { 8391 // Don't 'pre-truncate' the operands. 8392 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8393 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8394 8395 // If the divisor is constant, use that. 8396 llvm::APSInt divisor; 8397 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 8398 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 8399 if (log2 >= L.Width) 8400 L.Width = (L.NonNegative ? 0 : 1); 8401 else 8402 L.Width = std::min(L.Width - log2, MaxWidth); 8403 return L; 8404 } 8405 8406 // Otherwise, just use the LHS's width. 8407 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8408 return IntRange(L.Width, L.NonNegative && R.NonNegative); 8409 } 8410 8411 // The result of a remainder can't be larger than the result of 8412 // either side. 8413 case BO_Rem: { 8414 // Don't 'pre-truncate' the operands. 8415 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8416 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8417 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8418 8419 IntRange meet = IntRange::meet(L, R); 8420 meet.Width = std::min(meet.Width, MaxWidth); 8421 return meet; 8422 } 8423 8424 // The default behavior is okay for these. 8425 case BO_Mul: 8426 case BO_Add: 8427 case BO_Xor: 8428 case BO_Or: 8429 break; 8430 } 8431 8432 // The default case is to treat the operation as if it were closed 8433 // on the narrowest type that encompasses both operands. 8434 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8435 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 8436 return IntRange::join(L, R); 8437 } 8438 8439 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 8440 switch (UO->getOpcode()) { 8441 // Boolean-valued operations are white-listed. 8442 case UO_LNot: 8443 return IntRange::forBoolType(); 8444 8445 // Operations with opaque sources are black-listed. 8446 case UO_Deref: 8447 case UO_AddrOf: // should be impossible 8448 return IntRange::forValueOfType(C, GetExprType(E)); 8449 8450 default: 8451 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 8452 } 8453 } 8454 8455 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 8456 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 8457 8458 if (const auto *BitField = E->getSourceBitField()) 8459 return IntRange(BitField->getBitWidthValue(C), 8460 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 8461 8462 return IntRange::forValueOfType(C, GetExprType(E)); 8463 } 8464 8465 IntRange GetExprRange(ASTContext &C, const Expr *E) { 8466 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 8467 } 8468 8469 /// Checks whether the given value, which currently has the given 8470 /// source semantics, has the same value when coerced through the 8471 /// target semantics. 8472 bool IsSameFloatAfterCast(const llvm::APFloat &value, 8473 const llvm::fltSemantics &Src, 8474 const llvm::fltSemantics &Tgt) { 8475 llvm::APFloat truncated = value; 8476 8477 bool ignored; 8478 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 8479 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 8480 8481 return truncated.bitwiseIsEqual(value); 8482 } 8483 8484 /// Checks whether the given value, which currently has the given 8485 /// source semantics, has the same value when coerced through the 8486 /// target semantics. 8487 /// 8488 /// The value might be a vector of floats (or a complex number). 8489 bool IsSameFloatAfterCast(const APValue &value, 8490 const llvm::fltSemantics &Src, 8491 const llvm::fltSemantics &Tgt) { 8492 if (value.isFloat()) 8493 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 8494 8495 if (value.isVector()) { 8496 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 8497 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 8498 return false; 8499 return true; 8500 } 8501 8502 assert(value.isComplexFloat()); 8503 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 8504 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 8505 } 8506 8507 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 8508 8509 bool IsZero(Sema &S, Expr *E) { 8510 // Suppress cases where we are comparing against an enum constant. 8511 if (const DeclRefExpr *DR = 8512 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 8513 if (isa<EnumConstantDecl>(DR->getDecl())) 8514 return false; 8515 8516 // Suppress cases where the '0' value is expanded from a macro. 8517 if (E->getLocStart().isMacroID()) 8518 return false; 8519 8520 llvm::APSInt Value; 8521 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 8522 } 8523 8524 bool HasEnumType(Expr *E) { 8525 // Strip off implicit integral promotions. 8526 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8527 if (ICE->getCastKind() != CK_IntegralCast && 8528 ICE->getCastKind() != CK_NoOp) 8529 break; 8530 E = ICE->getSubExpr(); 8531 } 8532 8533 return E->getType()->isEnumeralType(); 8534 } 8535 8536 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 8537 // Disable warning in template instantiations. 8538 if (S.inTemplateInstantiation()) 8539 return; 8540 8541 BinaryOperatorKind op = E->getOpcode(); 8542 if (E->isValueDependent()) 8543 return; 8544 8545 if (op == BO_LT && IsZero(S, E->getRHS())) { 8546 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8547 << "< 0" << "false" << HasEnumType(E->getLHS()) 8548 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8549 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 8550 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8551 << ">= 0" << "true" << HasEnumType(E->getLHS()) 8552 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8553 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 8554 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8555 << "0 >" << "false" << HasEnumType(E->getRHS()) 8556 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8557 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 8558 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8559 << "0 <=" << "true" << HasEnumType(E->getRHS()) 8560 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8561 } 8562 } 8563 8564 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant, 8565 Expr *Other, const llvm::APSInt &Value, 8566 bool RhsConstant) { 8567 // Disable warning in template instantiations. 8568 if (S.inTemplateInstantiation()) 8569 return; 8570 8571 // TODO: Investigate using GetExprRange() to get tighter bounds 8572 // on the bit ranges. 8573 QualType OtherT = Other->getType(); 8574 if (const auto *AT = OtherT->getAs<AtomicType>()) 8575 OtherT = AT->getValueType(); 8576 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 8577 unsigned OtherWidth = OtherRange.Width; 8578 8579 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 8580 8581 // 0 values are handled later by CheckTrivialUnsignedComparison(). 8582 if ((Value == 0) && (!OtherIsBooleanType)) 8583 return; 8584 8585 BinaryOperatorKind op = E->getOpcode(); 8586 bool IsTrue = true; 8587 8588 // Used for diagnostic printout. 8589 enum { 8590 LiteralConstant = 0, 8591 CXXBoolLiteralTrue, 8592 CXXBoolLiteralFalse 8593 } LiteralOrBoolConstant = LiteralConstant; 8594 8595 if (!OtherIsBooleanType) { 8596 QualType ConstantT = Constant->getType(); 8597 QualType CommonT = E->getLHS()->getType(); 8598 8599 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 8600 return; 8601 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 8602 "comparison with non-integer type"); 8603 8604 bool ConstantSigned = ConstantT->isSignedIntegerType(); 8605 bool CommonSigned = CommonT->isSignedIntegerType(); 8606 8607 bool EqualityOnly = false; 8608 8609 if (CommonSigned) { 8610 // The common type is signed, therefore no signed to unsigned conversion. 8611 if (!OtherRange.NonNegative) { 8612 // Check that the constant is representable in type OtherT. 8613 if (ConstantSigned) { 8614 if (OtherWidth >= Value.getMinSignedBits()) 8615 return; 8616 } else { // !ConstantSigned 8617 if (OtherWidth >= Value.getActiveBits() + 1) 8618 return; 8619 } 8620 } else { // !OtherSigned 8621 // Check that the constant is representable in type OtherT. 8622 // Negative values are out of range. 8623 if (ConstantSigned) { 8624 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 8625 return; 8626 } else { // !ConstantSigned 8627 if (OtherWidth >= Value.getActiveBits()) 8628 return; 8629 } 8630 } 8631 } else { // !CommonSigned 8632 if (OtherRange.NonNegative) { 8633 if (OtherWidth >= Value.getActiveBits()) 8634 return; 8635 } else { // OtherSigned 8636 assert(!ConstantSigned && 8637 "Two signed types converted to unsigned types."); 8638 // Check to see if the constant is representable in OtherT. 8639 if (OtherWidth > Value.getActiveBits()) 8640 return; 8641 // Check to see if the constant is equivalent to a negative value 8642 // cast to CommonT. 8643 if (S.Context.getIntWidth(ConstantT) == 8644 S.Context.getIntWidth(CommonT) && 8645 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 8646 return; 8647 // The constant value rests between values that OtherT can represent 8648 // after conversion. Relational comparison still works, but equality 8649 // comparisons will be tautological. 8650 EqualityOnly = true; 8651 } 8652 } 8653 8654 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 8655 8656 if (op == BO_EQ || op == BO_NE) { 8657 IsTrue = op == BO_NE; 8658 } else if (EqualityOnly) { 8659 return; 8660 } else if (RhsConstant) { 8661 if (op == BO_GT || op == BO_GE) 8662 IsTrue = !PositiveConstant; 8663 else // op == BO_LT || op == BO_LE 8664 IsTrue = PositiveConstant; 8665 } else { 8666 if (op == BO_LT || op == BO_LE) 8667 IsTrue = !PositiveConstant; 8668 else // op == BO_GT || op == BO_GE 8669 IsTrue = PositiveConstant; 8670 } 8671 } else { 8672 // Other isKnownToHaveBooleanValue 8673 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 8674 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 8675 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 8676 8677 static const struct LinkedConditions { 8678 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 8679 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 8680 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 8681 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 8682 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 8683 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 8684 8685 } TruthTable = { 8686 // Constant on LHS. | Constant on RHS. | 8687 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 8688 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 8689 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 8690 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 8691 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 8692 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 8693 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 8694 }; 8695 8696 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 8697 8698 enum ConstantValue ConstVal = Zero; 8699 if (Value.isUnsigned() || Value.isNonNegative()) { 8700 if (Value == 0) { 8701 LiteralOrBoolConstant = 8702 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 8703 ConstVal = Zero; 8704 } else if (Value == 1) { 8705 LiteralOrBoolConstant = 8706 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 8707 ConstVal = One; 8708 } else { 8709 LiteralOrBoolConstant = LiteralConstant; 8710 ConstVal = GT_One; 8711 } 8712 } else { 8713 ConstVal = LT_Zero; 8714 } 8715 8716 CompareBoolWithConstantResult CmpRes; 8717 8718 switch (op) { 8719 case BO_LT: 8720 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 8721 break; 8722 case BO_GT: 8723 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 8724 break; 8725 case BO_LE: 8726 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 8727 break; 8728 case BO_GE: 8729 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 8730 break; 8731 case BO_EQ: 8732 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 8733 break; 8734 case BO_NE: 8735 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 8736 break; 8737 default: 8738 CmpRes = Unkwn; 8739 break; 8740 } 8741 8742 if (CmpRes == AFals) { 8743 IsTrue = false; 8744 } else if (CmpRes == ATrue) { 8745 IsTrue = true; 8746 } else { 8747 return; 8748 } 8749 } 8750 8751 // If this is a comparison to an enum constant, include that 8752 // constant in the diagnostic. 8753 const EnumConstantDecl *ED = nullptr; 8754 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 8755 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 8756 8757 SmallString<64> PrettySourceValue; 8758 llvm::raw_svector_ostream OS(PrettySourceValue); 8759 if (ED) 8760 OS << '\'' << *ED << "' (" << Value << ")"; 8761 else 8762 OS << Value; 8763 8764 S.DiagRuntimeBehavior( 8765 E->getOperatorLoc(), E, 8766 S.PDiag(diag::warn_out_of_range_compare) 8767 << OS.str() << LiteralOrBoolConstant 8768 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 8769 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 8770 } 8771 8772 /// Analyze the operands of the given comparison. Implements the 8773 /// fallback case from AnalyzeComparison. 8774 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 8775 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8776 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8777 } 8778 8779 /// \brief Implements -Wsign-compare. 8780 /// 8781 /// \param E the binary operator to check for warnings 8782 void AnalyzeComparison(Sema &S, BinaryOperator *E) { 8783 // The type the comparison is being performed in. 8784 QualType T = E->getLHS()->getType(); 8785 8786 // Only analyze comparison operators where both sides have been converted to 8787 // the same type. 8788 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 8789 return AnalyzeImpConvsInComparison(S, E); 8790 8791 // Don't analyze value-dependent comparisons directly. 8792 if (E->isValueDependent()) 8793 return AnalyzeImpConvsInComparison(S, E); 8794 8795 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 8796 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 8797 8798 bool IsComparisonConstant = false; 8799 8800 // Check whether an integer constant comparison results in a value 8801 // of 'true' or 'false'. 8802 if (T->isIntegralType(S.Context)) { 8803 llvm::APSInt RHSValue; 8804 bool IsRHSIntegralLiteral = 8805 RHS->isIntegerConstantExpr(RHSValue, S.Context); 8806 llvm::APSInt LHSValue; 8807 bool IsLHSIntegralLiteral = 8808 LHS->isIntegerConstantExpr(LHSValue, S.Context); 8809 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 8810 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 8811 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 8812 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 8813 else 8814 IsComparisonConstant = 8815 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 8816 } else if (!T->hasUnsignedIntegerRepresentation()) 8817 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 8818 8819 // We don't do anything special if this isn't an unsigned integral 8820 // comparison: we're only interested in integral comparisons, and 8821 // signed comparisons only happen in cases we don't care to warn about. 8822 // 8823 // We also don't care about value-dependent expressions or expressions 8824 // whose result is a constant. 8825 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 8826 return AnalyzeImpConvsInComparison(S, E); 8827 8828 // Check to see if one of the (unmodified) operands is of different 8829 // signedness. 8830 Expr *signedOperand, *unsignedOperand; 8831 if (LHS->getType()->hasSignedIntegerRepresentation()) { 8832 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 8833 "unsigned comparison between two signed integer expressions?"); 8834 signedOperand = LHS; 8835 unsignedOperand = RHS; 8836 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 8837 signedOperand = RHS; 8838 unsignedOperand = LHS; 8839 } else { 8840 CheckTrivialUnsignedComparison(S, E); 8841 return AnalyzeImpConvsInComparison(S, E); 8842 } 8843 8844 // Otherwise, calculate the effective range of the signed operand. 8845 IntRange signedRange = GetExprRange(S.Context, signedOperand); 8846 8847 // Go ahead and analyze implicit conversions in the operands. Note 8848 // that we skip the implicit conversions on both sides. 8849 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 8850 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 8851 8852 // If the signed range is non-negative, -Wsign-compare won't fire, 8853 // but we should still check for comparisons which are always true 8854 // or false. 8855 if (signedRange.NonNegative) 8856 return CheckTrivialUnsignedComparison(S, E); 8857 8858 // For (in)equality comparisons, if the unsigned operand is a 8859 // constant which cannot collide with a overflowed signed operand, 8860 // then reinterpreting the signed operand as unsigned will not 8861 // change the result of the comparison. 8862 if (E->isEqualityOp()) { 8863 unsigned comparisonWidth = S.Context.getIntWidth(T); 8864 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 8865 8866 // We should never be unable to prove that the unsigned operand is 8867 // non-negative. 8868 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 8869 8870 if (unsignedRange.Width < comparisonWidth) 8871 return; 8872 } 8873 8874 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 8875 S.PDiag(diag::warn_mixed_sign_comparison) 8876 << LHS->getType() << RHS->getType() 8877 << LHS->getSourceRange() << RHS->getSourceRange()); 8878 } 8879 8880 /// Analyzes an attempt to assign the given value to a bitfield. 8881 /// 8882 /// Returns true if there was something fishy about the attempt. 8883 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 8884 SourceLocation InitLoc) { 8885 assert(Bitfield->isBitField()); 8886 if (Bitfield->isInvalidDecl()) 8887 return false; 8888 8889 // White-list bool bitfields. 8890 QualType BitfieldType = Bitfield->getType(); 8891 if (BitfieldType->isBooleanType()) 8892 return false; 8893 8894 if (BitfieldType->isEnumeralType()) { 8895 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 8896 // If the underlying enum type was not explicitly specified as an unsigned 8897 // type and the enum contain only positive values, MSVC++ will cause an 8898 // inconsistency by storing this as a signed type. 8899 if (S.getLangOpts().CPlusPlus11 && 8900 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 8901 BitfieldEnumDecl->getNumPositiveBits() > 0 && 8902 BitfieldEnumDecl->getNumNegativeBits() == 0) { 8903 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 8904 << BitfieldEnumDecl->getNameAsString(); 8905 } 8906 } 8907 8908 if (Bitfield->getType()->isBooleanType()) 8909 return false; 8910 8911 // Ignore value- or type-dependent expressions. 8912 if (Bitfield->getBitWidth()->isValueDependent() || 8913 Bitfield->getBitWidth()->isTypeDependent() || 8914 Init->isValueDependent() || 8915 Init->isTypeDependent()) 8916 return false; 8917 8918 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 8919 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 8920 8921 llvm::APSInt Value; 8922 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 8923 Expr::SE_AllowSideEffects)) { 8924 // The RHS is not constant. If the RHS has an enum type, make sure the 8925 // bitfield is wide enough to hold all the values of the enum without 8926 // truncation. 8927 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 8928 EnumDecl *ED = EnumTy->getDecl(); 8929 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 8930 8931 // Enum types are implicitly signed on Windows, so check if there are any 8932 // negative enumerators to see if the enum was intended to be signed or 8933 // not. 8934 bool SignedEnum = ED->getNumNegativeBits() > 0; 8935 8936 // Check for surprising sign changes when assigning enum values to a 8937 // bitfield of different signedness. If the bitfield is signed and we 8938 // have exactly the right number of bits to store this unsigned enum, 8939 // suggest changing the enum to an unsigned type. This typically happens 8940 // on Windows where unfixed enums always use an underlying type of 'int'. 8941 unsigned DiagID = 0; 8942 if (SignedEnum && !SignedBitfield) { 8943 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 8944 } else if (SignedBitfield && !SignedEnum && 8945 ED->getNumPositiveBits() == FieldWidth) { 8946 DiagID = diag::warn_signed_bitfield_enum_conversion; 8947 } 8948 8949 if (DiagID) { 8950 S.Diag(InitLoc, DiagID) << Bitfield << ED; 8951 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 8952 SourceRange TypeRange = 8953 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 8954 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 8955 << SignedEnum << TypeRange; 8956 } 8957 8958 // Compute the required bitwidth. If the enum has negative values, we need 8959 // one more bit than the normal number of positive bits to represent the 8960 // sign bit. 8961 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 8962 ED->getNumNegativeBits()) 8963 : ED->getNumPositiveBits(); 8964 8965 // Check the bitwidth. 8966 if (BitsNeeded > FieldWidth) { 8967 Expr *WidthExpr = Bitfield->getBitWidth(); 8968 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 8969 << Bitfield << ED; 8970 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 8971 << BitsNeeded << ED << WidthExpr->getSourceRange(); 8972 } 8973 } 8974 8975 return false; 8976 } 8977 8978 unsigned OriginalWidth = Value.getBitWidth(); 8979 8980 if (!Value.isSigned() || Value.isNegative()) 8981 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 8982 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 8983 OriginalWidth = Value.getMinSignedBits(); 8984 8985 if (OriginalWidth <= FieldWidth) 8986 return false; 8987 8988 // Compute the value which the bitfield will contain. 8989 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 8990 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 8991 8992 // Check whether the stored value is equal to the original value. 8993 TruncatedValue = TruncatedValue.extend(OriginalWidth); 8994 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 8995 return false; 8996 8997 // Special-case bitfields of width 1: booleans are naturally 0/1, and 8998 // therefore don't strictly fit into a signed bitfield of width 1. 8999 if (FieldWidth == 1 && Value == 1) 9000 return false; 9001 9002 std::string PrettyValue = Value.toString(10); 9003 std::string PrettyTrunc = TruncatedValue.toString(10); 9004 9005 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 9006 << PrettyValue << PrettyTrunc << OriginalInit->getType() 9007 << Init->getSourceRange(); 9008 9009 return true; 9010 } 9011 9012 /// Analyze the given simple or compound assignment for warning-worthy 9013 /// operations. 9014 void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 9015 // Just recurse on the LHS. 9016 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9017 9018 // We want to recurse on the RHS as normal unless we're assigning to 9019 // a bitfield. 9020 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 9021 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 9022 E->getOperatorLoc())) { 9023 // Recurse, ignoring any implicit conversions on the RHS. 9024 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 9025 E->getOperatorLoc()); 9026 } 9027 } 9028 9029 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9030 } 9031 9032 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9033 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 9034 SourceLocation CContext, unsigned diag, 9035 bool pruneControlFlow = false) { 9036 if (pruneControlFlow) { 9037 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9038 S.PDiag(diag) 9039 << SourceType << T << E->getSourceRange() 9040 << SourceRange(CContext)); 9041 return; 9042 } 9043 S.Diag(E->getExprLoc(), diag) 9044 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 9045 } 9046 9047 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9048 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 9049 unsigned diag, bool pruneControlFlow = false) { 9050 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 9051 } 9052 9053 9054 /// Diagnose an implicit cast from a floating point value to an integer value. 9055 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 9056 9057 SourceLocation CContext) { 9058 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 9059 const bool PruneWarnings = S.inTemplateInstantiation(); 9060 9061 Expr *InnerE = E->IgnoreParenImpCasts(); 9062 // We also want to warn on, e.g., "int i = -1.234" 9063 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 9064 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 9065 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 9066 9067 const bool IsLiteral = 9068 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 9069 9070 llvm::APFloat Value(0.0); 9071 bool IsConstant = 9072 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 9073 if (!IsConstant) { 9074 return DiagnoseImpCast(S, E, T, CContext, 9075 diag::warn_impcast_float_integer, PruneWarnings); 9076 } 9077 9078 bool isExact = false; 9079 9080 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 9081 T->hasUnsignedIntegerRepresentation()); 9082 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 9083 &isExact) == llvm::APFloat::opOK && 9084 isExact) { 9085 if (IsLiteral) return; 9086 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 9087 PruneWarnings); 9088 } 9089 9090 unsigned DiagID = 0; 9091 if (IsLiteral) { 9092 // Warn on floating point literal to integer. 9093 DiagID = diag::warn_impcast_literal_float_to_integer; 9094 } else if (IntegerValue == 0) { 9095 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 9096 return DiagnoseImpCast(S, E, T, CContext, 9097 diag::warn_impcast_float_integer, PruneWarnings); 9098 } 9099 // Warn on non-zero to zero conversion. 9100 DiagID = diag::warn_impcast_float_to_integer_zero; 9101 } else { 9102 if (IntegerValue.isUnsigned()) { 9103 if (!IntegerValue.isMaxValue()) { 9104 return DiagnoseImpCast(S, E, T, CContext, 9105 diag::warn_impcast_float_integer, PruneWarnings); 9106 } 9107 } else { // IntegerValue.isSigned() 9108 if (!IntegerValue.isMaxSignedValue() && 9109 !IntegerValue.isMinSignedValue()) { 9110 return DiagnoseImpCast(S, E, T, CContext, 9111 diag::warn_impcast_float_integer, PruneWarnings); 9112 } 9113 } 9114 // Warn on evaluatable floating point expression to integer conversion. 9115 DiagID = diag::warn_impcast_float_to_integer; 9116 } 9117 9118 // FIXME: Force the precision of the source value down so we don't print 9119 // digits which are usually useless (we don't really care here if we 9120 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 9121 // would automatically print the shortest representation, but it's a bit 9122 // tricky to implement. 9123 SmallString<16> PrettySourceValue; 9124 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 9125 precision = (precision * 59 + 195) / 196; 9126 Value.toString(PrettySourceValue, precision); 9127 9128 SmallString<16> PrettyTargetValue; 9129 if (IsBool) 9130 PrettyTargetValue = Value.isZero() ? "false" : "true"; 9131 else 9132 IntegerValue.toString(PrettyTargetValue); 9133 9134 if (PruneWarnings) { 9135 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9136 S.PDiag(DiagID) 9137 << E->getType() << T.getUnqualifiedType() 9138 << PrettySourceValue << PrettyTargetValue 9139 << E->getSourceRange() << SourceRange(CContext)); 9140 } else { 9141 S.Diag(E->getExprLoc(), DiagID) 9142 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 9143 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 9144 } 9145 } 9146 9147 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 9148 if (!Range.Width) return "0"; 9149 9150 llvm::APSInt ValueInRange = Value; 9151 ValueInRange.setIsSigned(!Range.NonNegative); 9152 ValueInRange = ValueInRange.trunc(Range.Width); 9153 return ValueInRange.toString(10); 9154 } 9155 9156 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 9157 if (!isa<ImplicitCastExpr>(Ex)) 9158 return false; 9159 9160 Expr *InnerE = Ex->IgnoreParenImpCasts(); 9161 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 9162 const Type *Source = 9163 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 9164 if (Target->isDependentType()) 9165 return false; 9166 9167 const BuiltinType *FloatCandidateBT = 9168 dyn_cast<BuiltinType>(ToBool ? Source : Target); 9169 const Type *BoolCandidateType = ToBool ? Target : Source; 9170 9171 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 9172 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 9173 } 9174 9175 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 9176 SourceLocation CC) { 9177 unsigned NumArgs = TheCall->getNumArgs(); 9178 for (unsigned i = 0; i < NumArgs; ++i) { 9179 Expr *CurrA = TheCall->getArg(i); 9180 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 9181 continue; 9182 9183 bool IsSwapped = ((i > 0) && 9184 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 9185 IsSwapped |= ((i < (NumArgs - 1)) && 9186 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 9187 if (IsSwapped) { 9188 // Warn on this floating-point to bool conversion. 9189 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 9190 CurrA->getType(), CC, 9191 diag::warn_impcast_floating_point_to_bool); 9192 } 9193 } 9194 } 9195 9196 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) { 9197 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 9198 E->getExprLoc())) 9199 return; 9200 9201 // Don't warn on functions which have return type nullptr_t. 9202 if (isa<CallExpr>(E)) 9203 return; 9204 9205 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 9206 const Expr::NullPointerConstantKind NullKind = 9207 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 9208 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 9209 return; 9210 9211 // Return if target type is a safe conversion. 9212 if (T->isAnyPointerType() || T->isBlockPointerType() || 9213 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 9214 return; 9215 9216 SourceLocation Loc = E->getSourceRange().getBegin(); 9217 9218 // Venture through the macro stacks to get to the source of macro arguments. 9219 // The new location is a better location than the complete location that was 9220 // passed in. 9221 while (S.SourceMgr.isMacroArgExpansion(Loc)) 9222 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); 9223 9224 while (S.SourceMgr.isMacroArgExpansion(CC)) 9225 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); 9226 9227 // __null is usually wrapped in a macro. Go up a macro if that is the case. 9228 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 9229 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 9230 Loc, S.SourceMgr, S.getLangOpts()); 9231 if (MacroName == "NULL") 9232 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 9233 } 9234 9235 // Only warn if the null and context location are in the same macro expansion. 9236 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 9237 return; 9238 9239 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 9240 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) 9241 << FixItHint::CreateReplacement(Loc, 9242 S.getFixItZeroLiteralForType(T, Loc)); 9243 } 9244 9245 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9246 ObjCArrayLiteral *ArrayLiteral); 9247 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9248 ObjCDictionaryLiteral *DictionaryLiteral); 9249 9250 /// Check a single element within a collection literal against the 9251 /// target element type. 9252 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, 9253 Expr *Element, unsigned ElementKind) { 9254 // Skip a bitcast to 'id' or qualified 'id'. 9255 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 9256 if (ICE->getCastKind() == CK_BitCast && 9257 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 9258 Element = ICE->getSubExpr(); 9259 } 9260 9261 QualType ElementType = Element->getType(); 9262 ExprResult ElementResult(Element); 9263 if (ElementType->getAs<ObjCObjectPointerType>() && 9264 S.CheckSingleAssignmentConstraints(TargetElementType, 9265 ElementResult, 9266 false, false) 9267 != Sema::Compatible) { 9268 S.Diag(Element->getLocStart(), 9269 diag::warn_objc_collection_literal_element) 9270 << ElementType << ElementKind << TargetElementType 9271 << Element->getSourceRange(); 9272 } 9273 9274 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 9275 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 9276 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 9277 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 9278 } 9279 9280 /// Check an Objective-C array literal being converted to the given 9281 /// target type. 9282 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9283 ObjCArrayLiteral *ArrayLiteral) { 9284 if (!S.NSArrayDecl) 9285 return; 9286 9287 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9288 if (!TargetObjCPtr) 9289 return; 9290 9291 if (TargetObjCPtr->isUnspecialized() || 9292 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9293 != S.NSArrayDecl->getCanonicalDecl()) 9294 return; 9295 9296 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9297 if (TypeArgs.size() != 1) 9298 return; 9299 9300 QualType TargetElementType = TypeArgs[0]; 9301 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 9302 checkObjCCollectionLiteralElement(S, TargetElementType, 9303 ArrayLiteral->getElement(I), 9304 0); 9305 } 9306 } 9307 9308 /// Check an Objective-C dictionary literal being converted to the given 9309 /// target type. 9310 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9311 ObjCDictionaryLiteral *DictionaryLiteral) { 9312 if (!S.NSDictionaryDecl) 9313 return; 9314 9315 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9316 if (!TargetObjCPtr) 9317 return; 9318 9319 if (TargetObjCPtr->isUnspecialized() || 9320 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9321 != S.NSDictionaryDecl->getCanonicalDecl()) 9322 return; 9323 9324 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9325 if (TypeArgs.size() != 2) 9326 return; 9327 9328 QualType TargetKeyType = TypeArgs[0]; 9329 QualType TargetObjectType = TypeArgs[1]; 9330 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 9331 auto Element = DictionaryLiteral->getKeyValueElement(I); 9332 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 9333 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 9334 } 9335 } 9336 9337 // Helper function to filter out cases for constant width constant conversion. 9338 // Don't warn on char array initialization or for non-decimal values. 9339 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 9340 SourceLocation CC) { 9341 // If initializing from a constant, and the constant starts with '0', 9342 // then it is a binary, octal, or hexadecimal. Allow these constants 9343 // to fill all the bits, even if there is a sign change. 9344 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 9345 const char FirstLiteralCharacter = 9346 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 9347 if (FirstLiteralCharacter == '0') 9348 return false; 9349 } 9350 9351 // If the CC location points to a '{', and the type is char, then assume 9352 // assume it is an array initialization. 9353 if (CC.isValid() && T->isCharType()) { 9354 const char FirstContextCharacter = 9355 S.getSourceManager().getCharacterData(CC)[0]; 9356 if (FirstContextCharacter == '{') 9357 return false; 9358 } 9359 9360 return true; 9361 } 9362 9363 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 9364 SourceLocation CC, bool *ICContext = nullptr) { 9365 if (E->isTypeDependent() || E->isValueDependent()) return; 9366 9367 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 9368 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 9369 if (Source == Target) return; 9370 if (Target->isDependentType()) return; 9371 9372 // If the conversion context location is invalid don't complain. We also 9373 // don't want to emit a warning if the issue occurs from the expansion of 9374 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 9375 // delay this check as long as possible. Once we detect we are in that 9376 // scenario, we just return. 9377 if (CC.isInvalid()) 9378 return; 9379 9380 // Diagnose implicit casts to bool. 9381 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 9382 if (isa<StringLiteral>(E)) 9383 // Warn on string literal to bool. Checks for string literals in logical 9384 // and expressions, for instance, assert(0 && "error here"), are 9385 // prevented by a check in AnalyzeImplicitConversions(). 9386 return DiagnoseImpCast(S, E, T, CC, 9387 diag::warn_impcast_string_literal_to_bool); 9388 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 9389 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 9390 // This covers the literal expressions that evaluate to Objective-C 9391 // objects. 9392 return DiagnoseImpCast(S, E, T, CC, 9393 diag::warn_impcast_objective_c_literal_to_bool); 9394 } 9395 if (Source->isPointerType() || Source->canDecayToPointerType()) { 9396 // Warn on pointer to bool conversion that is always true. 9397 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 9398 SourceRange(CC)); 9399 } 9400 } 9401 9402 // Check implicit casts from Objective-C collection literals to specialized 9403 // collection types, e.g., NSArray<NSString *> *. 9404 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 9405 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 9406 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 9407 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 9408 9409 // Strip vector types. 9410 if (isa<VectorType>(Source)) { 9411 if (!isa<VectorType>(Target)) { 9412 if (S.SourceMgr.isInSystemMacro(CC)) 9413 return; 9414 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 9415 } 9416 9417 // If the vector cast is cast between two vectors of the same size, it is 9418 // a bitcast, not a conversion. 9419 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 9420 return; 9421 9422 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 9423 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 9424 } 9425 if (auto VecTy = dyn_cast<VectorType>(Target)) 9426 Target = VecTy->getElementType().getTypePtr(); 9427 9428 // Strip complex types. 9429 if (isa<ComplexType>(Source)) { 9430 if (!isa<ComplexType>(Target)) { 9431 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 9432 return; 9433 9434 return DiagnoseImpCast(S, E, T, CC, 9435 S.getLangOpts().CPlusPlus 9436 ? diag::err_impcast_complex_scalar 9437 : 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