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 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 1845 /// This checks that the target supports __builtin_cpu_is and 1846 /// that the string argument is constant and valid. 1847 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 1848 Expr *Arg = TheCall->getArg(0); 1849 1850 // Check if the argument is a string literal. 1851 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1852 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1853 << Arg->getSourceRange(); 1854 1855 // Check the contents of the string. 1856 StringRef Feature = 1857 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1858 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 1859 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is) 1860 << Arg->getSourceRange(); 1861 return false; 1862 } 1863 1864 // Check if the rounding mode is legal. 1865 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 1866 // Indicates if this instruction has rounding control or just SAE. 1867 bool HasRC = false; 1868 1869 unsigned ArgNum = 0; 1870 switch (BuiltinID) { 1871 default: 1872 return false; 1873 case X86::BI__builtin_ia32_vcvttsd2si32: 1874 case X86::BI__builtin_ia32_vcvttsd2si64: 1875 case X86::BI__builtin_ia32_vcvttsd2usi32: 1876 case X86::BI__builtin_ia32_vcvttsd2usi64: 1877 case X86::BI__builtin_ia32_vcvttss2si32: 1878 case X86::BI__builtin_ia32_vcvttss2si64: 1879 case X86::BI__builtin_ia32_vcvttss2usi32: 1880 case X86::BI__builtin_ia32_vcvttss2usi64: 1881 ArgNum = 1; 1882 break; 1883 case X86::BI__builtin_ia32_cvtps2pd512_mask: 1884 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 1885 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 1886 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 1887 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 1888 case X86::BI__builtin_ia32_cvttps2dq512_mask: 1889 case X86::BI__builtin_ia32_cvttps2qq512_mask: 1890 case X86::BI__builtin_ia32_cvttps2udq512_mask: 1891 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 1892 case X86::BI__builtin_ia32_exp2pd_mask: 1893 case X86::BI__builtin_ia32_exp2ps_mask: 1894 case X86::BI__builtin_ia32_getexppd512_mask: 1895 case X86::BI__builtin_ia32_getexpps512_mask: 1896 case X86::BI__builtin_ia32_rcp28pd_mask: 1897 case X86::BI__builtin_ia32_rcp28ps_mask: 1898 case X86::BI__builtin_ia32_rsqrt28pd_mask: 1899 case X86::BI__builtin_ia32_rsqrt28ps_mask: 1900 case X86::BI__builtin_ia32_vcomisd: 1901 case X86::BI__builtin_ia32_vcomiss: 1902 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 1903 ArgNum = 3; 1904 break; 1905 case X86::BI__builtin_ia32_cmppd512_mask: 1906 case X86::BI__builtin_ia32_cmpps512_mask: 1907 case X86::BI__builtin_ia32_cmpsd_mask: 1908 case X86::BI__builtin_ia32_cmpss_mask: 1909 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 1910 case X86::BI__builtin_ia32_getexpsd128_round_mask: 1911 case X86::BI__builtin_ia32_getexpss128_round_mask: 1912 case X86::BI__builtin_ia32_maxpd512_mask: 1913 case X86::BI__builtin_ia32_maxps512_mask: 1914 case X86::BI__builtin_ia32_maxsd_round_mask: 1915 case X86::BI__builtin_ia32_maxss_round_mask: 1916 case X86::BI__builtin_ia32_minpd512_mask: 1917 case X86::BI__builtin_ia32_minps512_mask: 1918 case X86::BI__builtin_ia32_minsd_round_mask: 1919 case X86::BI__builtin_ia32_minss_round_mask: 1920 case X86::BI__builtin_ia32_rcp28sd_round_mask: 1921 case X86::BI__builtin_ia32_rcp28ss_round_mask: 1922 case X86::BI__builtin_ia32_reducepd512_mask: 1923 case X86::BI__builtin_ia32_reduceps512_mask: 1924 case X86::BI__builtin_ia32_rndscalepd_mask: 1925 case X86::BI__builtin_ia32_rndscaleps_mask: 1926 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 1927 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 1928 ArgNum = 4; 1929 break; 1930 case X86::BI__builtin_ia32_fixupimmpd512_mask: 1931 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 1932 case X86::BI__builtin_ia32_fixupimmps512_mask: 1933 case X86::BI__builtin_ia32_fixupimmps512_maskz: 1934 case X86::BI__builtin_ia32_fixupimmsd_mask: 1935 case X86::BI__builtin_ia32_fixupimmsd_maskz: 1936 case X86::BI__builtin_ia32_fixupimmss_mask: 1937 case X86::BI__builtin_ia32_fixupimmss_maskz: 1938 case X86::BI__builtin_ia32_rangepd512_mask: 1939 case X86::BI__builtin_ia32_rangeps512_mask: 1940 case X86::BI__builtin_ia32_rangesd128_round_mask: 1941 case X86::BI__builtin_ia32_rangess128_round_mask: 1942 case X86::BI__builtin_ia32_reducesd_mask: 1943 case X86::BI__builtin_ia32_reducess_mask: 1944 case X86::BI__builtin_ia32_rndscalesd_round_mask: 1945 case X86::BI__builtin_ia32_rndscaless_round_mask: 1946 ArgNum = 5; 1947 break; 1948 case X86::BI__builtin_ia32_vcvtsd2si64: 1949 case X86::BI__builtin_ia32_vcvtsd2si32: 1950 case X86::BI__builtin_ia32_vcvtsd2usi32: 1951 case X86::BI__builtin_ia32_vcvtsd2usi64: 1952 case X86::BI__builtin_ia32_vcvtss2si32: 1953 case X86::BI__builtin_ia32_vcvtss2si64: 1954 case X86::BI__builtin_ia32_vcvtss2usi32: 1955 case X86::BI__builtin_ia32_vcvtss2usi64: 1956 ArgNum = 1; 1957 HasRC = true; 1958 break; 1959 case X86::BI__builtin_ia32_cvtsi2sd64: 1960 case X86::BI__builtin_ia32_cvtsi2ss32: 1961 case X86::BI__builtin_ia32_cvtsi2ss64: 1962 case X86::BI__builtin_ia32_cvtusi2sd64: 1963 case X86::BI__builtin_ia32_cvtusi2ss32: 1964 case X86::BI__builtin_ia32_cvtusi2ss64: 1965 ArgNum = 2; 1966 HasRC = true; 1967 break; 1968 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 1969 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 1970 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 1971 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 1972 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 1973 case X86::BI__builtin_ia32_cvtps2qq512_mask: 1974 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 1975 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 1976 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 1977 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 1978 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 1979 case X86::BI__builtin_ia32_sqrtpd512_mask: 1980 case X86::BI__builtin_ia32_sqrtps512_mask: 1981 ArgNum = 3; 1982 HasRC = true; 1983 break; 1984 case X86::BI__builtin_ia32_addpd512_mask: 1985 case X86::BI__builtin_ia32_addps512_mask: 1986 case X86::BI__builtin_ia32_divpd512_mask: 1987 case X86::BI__builtin_ia32_divps512_mask: 1988 case X86::BI__builtin_ia32_mulpd512_mask: 1989 case X86::BI__builtin_ia32_mulps512_mask: 1990 case X86::BI__builtin_ia32_subpd512_mask: 1991 case X86::BI__builtin_ia32_subps512_mask: 1992 case X86::BI__builtin_ia32_addss_round_mask: 1993 case X86::BI__builtin_ia32_addsd_round_mask: 1994 case X86::BI__builtin_ia32_divss_round_mask: 1995 case X86::BI__builtin_ia32_divsd_round_mask: 1996 case X86::BI__builtin_ia32_mulss_round_mask: 1997 case X86::BI__builtin_ia32_mulsd_round_mask: 1998 case X86::BI__builtin_ia32_subss_round_mask: 1999 case X86::BI__builtin_ia32_subsd_round_mask: 2000 case X86::BI__builtin_ia32_scalefpd512_mask: 2001 case X86::BI__builtin_ia32_scalefps512_mask: 2002 case X86::BI__builtin_ia32_scalefsd_round_mask: 2003 case X86::BI__builtin_ia32_scalefss_round_mask: 2004 case X86::BI__builtin_ia32_getmantpd512_mask: 2005 case X86::BI__builtin_ia32_getmantps512_mask: 2006 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 2007 case X86::BI__builtin_ia32_sqrtsd_round_mask: 2008 case X86::BI__builtin_ia32_sqrtss_round_mask: 2009 case X86::BI__builtin_ia32_vfmaddpd512_mask: 2010 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 2011 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 2012 case X86::BI__builtin_ia32_vfmaddps512_mask: 2013 case X86::BI__builtin_ia32_vfmaddps512_mask3: 2014 case X86::BI__builtin_ia32_vfmaddps512_maskz: 2015 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 2016 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 2017 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 2018 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 2019 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 2020 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 2021 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 2022 case X86::BI__builtin_ia32_vfmsubps512_mask3: 2023 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 2024 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 2025 case X86::BI__builtin_ia32_vfnmaddpd512_mask: 2026 case X86::BI__builtin_ia32_vfnmaddps512_mask: 2027 case X86::BI__builtin_ia32_vfnmsubpd512_mask: 2028 case X86::BI__builtin_ia32_vfnmsubpd512_mask3: 2029 case X86::BI__builtin_ia32_vfnmsubps512_mask: 2030 case X86::BI__builtin_ia32_vfnmsubps512_mask3: 2031 case X86::BI__builtin_ia32_vfmaddsd3_mask: 2032 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 2033 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 2034 case X86::BI__builtin_ia32_vfmaddss3_mask: 2035 case X86::BI__builtin_ia32_vfmaddss3_maskz: 2036 case X86::BI__builtin_ia32_vfmaddss3_mask3: 2037 ArgNum = 4; 2038 HasRC = true; 2039 break; 2040 case X86::BI__builtin_ia32_getmantsd_round_mask: 2041 case X86::BI__builtin_ia32_getmantss_round_mask: 2042 ArgNum = 5; 2043 HasRC = true; 2044 break; 2045 } 2046 2047 llvm::APSInt Result; 2048 2049 // We can't check the value of a dependent argument. 2050 Expr *Arg = TheCall->getArg(ArgNum); 2051 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2052 return false; 2053 2054 // Check constant-ness first. 2055 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2056 return true; 2057 2058 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 2059 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 2060 // combined with ROUND_NO_EXC. 2061 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 2062 Result == 8/*ROUND_NO_EXC*/ || 2063 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 2064 return false; 2065 2066 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 2067 << Arg->getSourceRange(); 2068 } 2069 2070 // Check if the gather/scatter scale is legal. 2071 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 2072 CallExpr *TheCall) { 2073 unsigned ArgNum = 0; 2074 switch (BuiltinID) { 2075 default: 2076 return false; 2077 case X86::BI__builtin_ia32_gatherpfdpd: 2078 case X86::BI__builtin_ia32_gatherpfdps: 2079 case X86::BI__builtin_ia32_gatherpfqpd: 2080 case X86::BI__builtin_ia32_gatherpfqps: 2081 case X86::BI__builtin_ia32_scatterpfdpd: 2082 case X86::BI__builtin_ia32_scatterpfdps: 2083 case X86::BI__builtin_ia32_scatterpfqpd: 2084 case X86::BI__builtin_ia32_scatterpfqps: 2085 ArgNum = 3; 2086 break; 2087 case X86::BI__builtin_ia32_gatherd_pd: 2088 case X86::BI__builtin_ia32_gatherd_pd256: 2089 case X86::BI__builtin_ia32_gatherq_pd: 2090 case X86::BI__builtin_ia32_gatherq_pd256: 2091 case X86::BI__builtin_ia32_gatherd_ps: 2092 case X86::BI__builtin_ia32_gatherd_ps256: 2093 case X86::BI__builtin_ia32_gatherq_ps: 2094 case X86::BI__builtin_ia32_gatherq_ps256: 2095 case X86::BI__builtin_ia32_gatherd_q: 2096 case X86::BI__builtin_ia32_gatherd_q256: 2097 case X86::BI__builtin_ia32_gatherq_q: 2098 case X86::BI__builtin_ia32_gatherq_q256: 2099 case X86::BI__builtin_ia32_gatherd_d: 2100 case X86::BI__builtin_ia32_gatherd_d256: 2101 case X86::BI__builtin_ia32_gatherq_d: 2102 case X86::BI__builtin_ia32_gatherq_d256: 2103 case X86::BI__builtin_ia32_gather3div2df: 2104 case X86::BI__builtin_ia32_gather3div2di: 2105 case X86::BI__builtin_ia32_gather3div4df: 2106 case X86::BI__builtin_ia32_gather3div4di: 2107 case X86::BI__builtin_ia32_gather3div4sf: 2108 case X86::BI__builtin_ia32_gather3div4si: 2109 case X86::BI__builtin_ia32_gather3div8sf: 2110 case X86::BI__builtin_ia32_gather3div8si: 2111 case X86::BI__builtin_ia32_gather3siv2df: 2112 case X86::BI__builtin_ia32_gather3siv2di: 2113 case X86::BI__builtin_ia32_gather3siv4df: 2114 case X86::BI__builtin_ia32_gather3siv4di: 2115 case X86::BI__builtin_ia32_gather3siv4sf: 2116 case X86::BI__builtin_ia32_gather3siv4si: 2117 case X86::BI__builtin_ia32_gather3siv8sf: 2118 case X86::BI__builtin_ia32_gather3siv8si: 2119 case X86::BI__builtin_ia32_gathersiv8df: 2120 case X86::BI__builtin_ia32_gathersiv16sf: 2121 case X86::BI__builtin_ia32_gatherdiv8df: 2122 case X86::BI__builtin_ia32_gatherdiv16sf: 2123 case X86::BI__builtin_ia32_gathersiv8di: 2124 case X86::BI__builtin_ia32_gathersiv16si: 2125 case X86::BI__builtin_ia32_gatherdiv8di: 2126 case X86::BI__builtin_ia32_gatherdiv16si: 2127 case X86::BI__builtin_ia32_scatterdiv2df: 2128 case X86::BI__builtin_ia32_scatterdiv2di: 2129 case X86::BI__builtin_ia32_scatterdiv4df: 2130 case X86::BI__builtin_ia32_scatterdiv4di: 2131 case X86::BI__builtin_ia32_scatterdiv4sf: 2132 case X86::BI__builtin_ia32_scatterdiv4si: 2133 case X86::BI__builtin_ia32_scatterdiv8sf: 2134 case X86::BI__builtin_ia32_scatterdiv8si: 2135 case X86::BI__builtin_ia32_scattersiv2df: 2136 case X86::BI__builtin_ia32_scattersiv2di: 2137 case X86::BI__builtin_ia32_scattersiv4df: 2138 case X86::BI__builtin_ia32_scattersiv4di: 2139 case X86::BI__builtin_ia32_scattersiv4sf: 2140 case X86::BI__builtin_ia32_scattersiv4si: 2141 case X86::BI__builtin_ia32_scattersiv8sf: 2142 case X86::BI__builtin_ia32_scattersiv8si: 2143 case X86::BI__builtin_ia32_scattersiv8df: 2144 case X86::BI__builtin_ia32_scattersiv16sf: 2145 case X86::BI__builtin_ia32_scatterdiv8df: 2146 case X86::BI__builtin_ia32_scatterdiv16sf: 2147 case X86::BI__builtin_ia32_scattersiv8di: 2148 case X86::BI__builtin_ia32_scattersiv16si: 2149 case X86::BI__builtin_ia32_scatterdiv8di: 2150 case X86::BI__builtin_ia32_scatterdiv16si: 2151 ArgNum = 4; 2152 break; 2153 } 2154 2155 llvm::APSInt Result; 2156 2157 // We can't check the value of a dependent argument. 2158 Expr *Arg = TheCall->getArg(ArgNum); 2159 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2160 return false; 2161 2162 // Check constant-ness first. 2163 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2164 return true; 2165 2166 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 2167 return false; 2168 2169 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale) 2170 << Arg->getSourceRange(); 2171 } 2172 2173 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2174 if (BuiltinID == X86::BI__builtin_cpu_supports) 2175 return SemaBuiltinCpuSupports(*this, TheCall); 2176 2177 if (BuiltinID == X86::BI__builtin_cpu_is) 2178 return SemaBuiltinCpuIs(*this, TheCall); 2179 2180 // If the intrinsic has rounding or SAE make sure its valid. 2181 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 2182 return true; 2183 2184 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 2185 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 2186 return true; 2187 2188 // For intrinsics which take an immediate value as part of the instruction, 2189 // range check them here. 2190 int i = 0, l = 0, u = 0; 2191 switch (BuiltinID) { 2192 default: 2193 return false; 2194 case X86::BI_mm_prefetch: 2195 i = 1; l = 0; u = 3; 2196 break; 2197 case X86::BI__builtin_ia32_sha1rnds4: 2198 case X86::BI__builtin_ia32_shuf_f32x4_256_mask: 2199 case X86::BI__builtin_ia32_shuf_f64x2_256_mask: 2200 case X86::BI__builtin_ia32_shuf_i32x4_256_mask: 2201 case X86::BI__builtin_ia32_shuf_i64x2_256_mask: 2202 i = 2; l = 0; u = 3; 2203 break; 2204 case X86::BI__builtin_ia32_vpermil2pd: 2205 case X86::BI__builtin_ia32_vpermil2pd256: 2206 case X86::BI__builtin_ia32_vpermil2ps: 2207 case X86::BI__builtin_ia32_vpermil2ps256: 2208 i = 3; l = 0; u = 3; 2209 break; 2210 case X86::BI__builtin_ia32_cmpb128_mask: 2211 case X86::BI__builtin_ia32_cmpw128_mask: 2212 case X86::BI__builtin_ia32_cmpd128_mask: 2213 case X86::BI__builtin_ia32_cmpq128_mask: 2214 case X86::BI__builtin_ia32_cmpb256_mask: 2215 case X86::BI__builtin_ia32_cmpw256_mask: 2216 case X86::BI__builtin_ia32_cmpd256_mask: 2217 case X86::BI__builtin_ia32_cmpq256_mask: 2218 case X86::BI__builtin_ia32_cmpb512_mask: 2219 case X86::BI__builtin_ia32_cmpw512_mask: 2220 case X86::BI__builtin_ia32_cmpd512_mask: 2221 case X86::BI__builtin_ia32_cmpq512_mask: 2222 case X86::BI__builtin_ia32_ucmpb128_mask: 2223 case X86::BI__builtin_ia32_ucmpw128_mask: 2224 case X86::BI__builtin_ia32_ucmpd128_mask: 2225 case X86::BI__builtin_ia32_ucmpq128_mask: 2226 case X86::BI__builtin_ia32_ucmpb256_mask: 2227 case X86::BI__builtin_ia32_ucmpw256_mask: 2228 case X86::BI__builtin_ia32_ucmpd256_mask: 2229 case X86::BI__builtin_ia32_ucmpq256_mask: 2230 case X86::BI__builtin_ia32_ucmpb512_mask: 2231 case X86::BI__builtin_ia32_ucmpw512_mask: 2232 case X86::BI__builtin_ia32_ucmpd512_mask: 2233 case X86::BI__builtin_ia32_ucmpq512_mask: 2234 case X86::BI__builtin_ia32_vpcomub: 2235 case X86::BI__builtin_ia32_vpcomuw: 2236 case X86::BI__builtin_ia32_vpcomud: 2237 case X86::BI__builtin_ia32_vpcomuq: 2238 case X86::BI__builtin_ia32_vpcomb: 2239 case X86::BI__builtin_ia32_vpcomw: 2240 case X86::BI__builtin_ia32_vpcomd: 2241 case X86::BI__builtin_ia32_vpcomq: 2242 i = 2; l = 0; u = 7; 2243 break; 2244 case X86::BI__builtin_ia32_roundps: 2245 case X86::BI__builtin_ia32_roundpd: 2246 case X86::BI__builtin_ia32_roundps256: 2247 case X86::BI__builtin_ia32_roundpd256: 2248 i = 1; l = 0; u = 15; 2249 break; 2250 case X86::BI__builtin_ia32_roundss: 2251 case X86::BI__builtin_ia32_roundsd: 2252 case X86::BI__builtin_ia32_rangepd128_mask: 2253 case X86::BI__builtin_ia32_rangepd256_mask: 2254 case X86::BI__builtin_ia32_rangepd512_mask: 2255 case X86::BI__builtin_ia32_rangeps128_mask: 2256 case X86::BI__builtin_ia32_rangeps256_mask: 2257 case X86::BI__builtin_ia32_rangeps512_mask: 2258 case X86::BI__builtin_ia32_getmantsd_round_mask: 2259 case X86::BI__builtin_ia32_getmantss_round_mask: 2260 i = 2; l = 0; u = 15; 2261 break; 2262 case X86::BI__builtin_ia32_cmpps: 2263 case X86::BI__builtin_ia32_cmpss: 2264 case X86::BI__builtin_ia32_cmppd: 2265 case X86::BI__builtin_ia32_cmpsd: 2266 case X86::BI__builtin_ia32_cmpps256: 2267 case X86::BI__builtin_ia32_cmppd256: 2268 case X86::BI__builtin_ia32_cmpps128_mask: 2269 case X86::BI__builtin_ia32_cmppd128_mask: 2270 case X86::BI__builtin_ia32_cmpps256_mask: 2271 case X86::BI__builtin_ia32_cmppd256_mask: 2272 case X86::BI__builtin_ia32_cmpps512_mask: 2273 case X86::BI__builtin_ia32_cmppd512_mask: 2274 case X86::BI__builtin_ia32_cmpsd_mask: 2275 case X86::BI__builtin_ia32_cmpss_mask: 2276 i = 2; l = 0; u = 31; 2277 break; 2278 case X86::BI__builtin_ia32_xabort: 2279 i = 0; l = -128; u = 255; 2280 break; 2281 case X86::BI__builtin_ia32_pshufw: 2282 case X86::BI__builtin_ia32_aeskeygenassist128: 2283 i = 1; l = -128; u = 255; 2284 break; 2285 case X86::BI__builtin_ia32_vcvtps2ph: 2286 case X86::BI__builtin_ia32_vcvtps2ph256: 2287 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2288 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2289 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2290 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2291 case X86::BI__builtin_ia32_rndscaleps_mask: 2292 case X86::BI__builtin_ia32_rndscalepd_mask: 2293 case X86::BI__builtin_ia32_reducepd128_mask: 2294 case X86::BI__builtin_ia32_reducepd256_mask: 2295 case X86::BI__builtin_ia32_reducepd512_mask: 2296 case X86::BI__builtin_ia32_reduceps128_mask: 2297 case X86::BI__builtin_ia32_reduceps256_mask: 2298 case X86::BI__builtin_ia32_reduceps512_mask: 2299 case X86::BI__builtin_ia32_prold512_mask: 2300 case X86::BI__builtin_ia32_prolq512_mask: 2301 case X86::BI__builtin_ia32_prold128_mask: 2302 case X86::BI__builtin_ia32_prold256_mask: 2303 case X86::BI__builtin_ia32_prolq128_mask: 2304 case X86::BI__builtin_ia32_prolq256_mask: 2305 case X86::BI__builtin_ia32_prord128_mask: 2306 case X86::BI__builtin_ia32_prord256_mask: 2307 case X86::BI__builtin_ia32_prorq128_mask: 2308 case X86::BI__builtin_ia32_prorq256_mask: 2309 case X86::BI__builtin_ia32_fpclasspd128_mask: 2310 case X86::BI__builtin_ia32_fpclasspd256_mask: 2311 case X86::BI__builtin_ia32_fpclassps128_mask: 2312 case X86::BI__builtin_ia32_fpclassps256_mask: 2313 case X86::BI__builtin_ia32_fpclassps512_mask: 2314 case X86::BI__builtin_ia32_fpclasspd512_mask: 2315 case X86::BI__builtin_ia32_fpclasssd_mask: 2316 case X86::BI__builtin_ia32_fpclassss_mask: 2317 i = 1; l = 0; u = 255; 2318 break; 2319 case X86::BI__builtin_ia32_palignr: 2320 case X86::BI__builtin_ia32_insertps128: 2321 case X86::BI__builtin_ia32_dpps: 2322 case X86::BI__builtin_ia32_dppd: 2323 case X86::BI__builtin_ia32_dpps256: 2324 case X86::BI__builtin_ia32_mpsadbw128: 2325 case X86::BI__builtin_ia32_mpsadbw256: 2326 case X86::BI__builtin_ia32_pcmpistrm128: 2327 case X86::BI__builtin_ia32_pcmpistri128: 2328 case X86::BI__builtin_ia32_pcmpistria128: 2329 case X86::BI__builtin_ia32_pcmpistric128: 2330 case X86::BI__builtin_ia32_pcmpistrio128: 2331 case X86::BI__builtin_ia32_pcmpistris128: 2332 case X86::BI__builtin_ia32_pcmpistriz128: 2333 case X86::BI__builtin_ia32_pclmulqdq128: 2334 case X86::BI__builtin_ia32_vperm2f128_pd256: 2335 case X86::BI__builtin_ia32_vperm2f128_ps256: 2336 case X86::BI__builtin_ia32_vperm2f128_si256: 2337 case X86::BI__builtin_ia32_permti256: 2338 i = 2; l = -128; u = 255; 2339 break; 2340 case X86::BI__builtin_ia32_palignr128: 2341 case X86::BI__builtin_ia32_palignr256: 2342 case X86::BI__builtin_ia32_palignr512_mask: 2343 case X86::BI__builtin_ia32_vcomisd: 2344 case X86::BI__builtin_ia32_vcomiss: 2345 case X86::BI__builtin_ia32_shuf_f32x4_mask: 2346 case X86::BI__builtin_ia32_shuf_f64x2_mask: 2347 case X86::BI__builtin_ia32_shuf_i32x4_mask: 2348 case X86::BI__builtin_ia32_shuf_i64x2_mask: 2349 case X86::BI__builtin_ia32_dbpsadbw128_mask: 2350 case X86::BI__builtin_ia32_dbpsadbw256_mask: 2351 case X86::BI__builtin_ia32_dbpsadbw512_mask: 2352 i = 2; l = 0; u = 255; 2353 break; 2354 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2355 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2356 case X86::BI__builtin_ia32_fixupimmps512_mask: 2357 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2358 case X86::BI__builtin_ia32_fixupimmsd_mask: 2359 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2360 case X86::BI__builtin_ia32_fixupimmss_mask: 2361 case X86::BI__builtin_ia32_fixupimmss_maskz: 2362 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2363 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2364 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2365 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2366 case X86::BI__builtin_ia32_fixupimmps128_mask: 2367 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2368 case X86::BI__builtin_ia32_fixupimmps256_mask: 2369 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2370 case X86::BI__builtin_ia32_pternlogd512_mask: 2371 case X86::BI__builtin_ia32_pternlogd512_maskz: 2372 case X86::BI__builtin_ia32_pternlogq512_mask: 2373 case X86::BI__builtin_ia32_pternlogq512_maskz: 2374 case X86::BI__builtin_ia32_pternlogd128_mask: 2375 case X86::BI__builtin_ia32_pternlogd128_maskz: 2376 case X86::BI__builtin_ia32_pternlogd256_mask: 2377 case X86::BI__builtin_ia32_pternlogd256_maskz: 2378 case X86::BI__builtin_ia32_pternlogq128_mask: 2379 case X86::BI__builtin_ia32_pternlogq128_maskz: 2380 case X86::BI__builtin_ia32_pternlogq256_mask: 2381 case X86::BI__builtin_ia32_pternlogq256_maskz: 2382 i = 3; l = 0; u = 255; 2383 break; 2384 case X86::BI__builtin_ia32_gatherpfdpd: 2385 case X86::BI__builtin_ia32_gatherpfdps: 2386 case X86::BI__builtin_ia32_gatherpfqpd: 2387 case X86::BI__builtin_ia32_gatherpfqps: 2388 case X86::BI__builtin_ia32_scatterpfdpd: 2389 case X86::BI__builtin_ia32_scatterpfdps: 2390 case X86::BI__builtin_ia32_scatterpfqpd: 2391 case X86::BI__builtin_ia32_scatterpfqps: 2392 i = 4; l = 2; u = 3; 2393 break; 2394 case X86::BI__builtin_ia32_pcmpestrm128: 2395 case X86::BI__builtin_ia32_pcmpestri128: 2396 case X86::BI__builtin_ia32_pcmpestria128: 2397 case X86::BI__builtin_ia32_pcmpestric128: 2398 case X86::BI__builtin_ia32_pcmpestrio128: 2399 case X86::BI__builtin_ia32_pcmpestris128: 2400 case X86::BI__builtin_ia32_pcmpestriz128: 2401 i = 4; l = -128; u = 255; 2402 break; 2403 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2404 case X86::BI__builtin_ia32_rndscaless_round_mask: 2405 i = 4; l = 0; u = 255; 2406 break; 2407 } 2408 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2409 } 2410 2411 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2412 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2413 /// Returns true when the format fits the function and the FormatStringInfo has 2414 /// been populated. 2415 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2416 FormatStringInfo *FSI) { 2417 FSI->HasVAListArg = Format->getFirstArg() == 0; 2418 FSI->FormatIdx = Format->getFormatIdx() - 1; 2419 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2420 2421 // The way the format attribute works in GCC, the implicit this argument 2422 // of member functions is counted. However, it doesn't appear in our own 2423 // lists, so decrement format_idx in that case. 2424 if (IsCXXMember) { 2425 if(FSI->FormatIdx == 0) 2426 return false; 2427 --FSI->FormatIdx; 2428 if (FSI->FirstDataArg != 0) 2429 --FSI->FirstDataArg; 2430 } 2431 return true; 2432 } 2433 2434 /// Checks if a the given expression evaluates to null. 2435 /// 2436 /// \brief Returns true if the value evaluates to null. 2437 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2438 // If the expression has non-null type, it doesn't evaluate to null. 2439 if (auto nullability 2440 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2441 if (*nullability == NullabilityKind::NonNull) 2442 return false; 2443 } 2444 2445 // As a special case, transparent unions initialized with zero are 2446 // considered null for the purposes of the nonnull attribute. 2447 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2448 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2449 if (const CompoundLiteralExpr *CLE = 2450 dyn_cast<CompoundLiteralExpr>(Expr)) 2451 if (const InitListExpr *ILE = 2452 dyn_cast<InitListExpr>(CLE->getInitializer())) 2453 Expr = ILE->getInit(0); 2454 } 2455 2456 bool Result; 2457 return (!Expr->isValueDependent() && 2458 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2459 !Result); 2460 } 2461 2462 static void CheckNonNullArgument(Sema &S, 2463 const Expr *ArgExpr, 2464 SourceLocation CallSiteLoc) { 2465 if (CheckNonNullExpr(S, ArgExpr)) 2466 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2467 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2468 } 2469 2470 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2471 FormatStringInfo FSI; 2472 if ((GetFormatStringType(Format) == FST_NSString) && 2473 getFormatStringInfo(Format, false, &FSI)) { 2474 Idx = FSI.FormatIdx; 2475 return true; 2476 } 2477 return false; 2478 } 2479 /// \brief Diagnose use of %s directive in an NSString which is being passed 2480 /// as formatting string to formatting method. 2481 static void 2482 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 2483 const NamedDecl *FDecl, 2484 Expr **Args, 2485 unsigned NumArgs) { 2486 unsigned Idx = 0; 2487 bool Format = false; 2488 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 2489 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 2490 Idx = 2; 2491 Format = true; 2492 } 2493 else 2494 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2495 if (S.GetFormatNSStringIdx(I, Idx)) { 2496 Format = true; 2497 break; 2498 } 2499 } 2500 if (!Format || NumArgs <= Idx) 2501 return; 2502 const Expr *FormatExpr = Args[Idx]; 2503 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2504 FormatExpr = CSCE->getSubExpr(); 2505 const StringLiteral *FormatString; 2506 if (const ObjCStringLiteral *OSL = 2507 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2508 FormatString = OSL->getString(); 2509 else 2510 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2511 if (!FormatString) 2512 return; 2513 if (S.FormatStringHasSArg(FormatString)) { 2514 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2515 << "%s" << 1 << 1; 2516 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2517 << FDecl->getDeclName(); 2518 } 2519 } 2520 2521 /// Determine whether the given type has a non-null nullability annotation. 2522 static bool isNonNullType(ASTContext &ctx, QualType type) { 2523 if (auto nullability = type->getNullability(ctx)) 2524 return *nullability == NullabilityKind::NonNull; 2525 2526 return false; 2527 } 2528 2529 static void CheckNonNullArguments(Sema &S, 2530 const NamedDecl *FDecl, 2531 const FunctionProtoType *Proto, 2532 ArrayRef<const Expr *> Args, 2533 SourceLocation CallSiteLoc) { 2534 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2535 2536 // Check the attributes attached to the method/function itself. 2537 llvm::SmallBitVector NonNullArgs; 2538 if (FDecl) { 2539 // Handle the nonnull attribute on the function/method declaration itself. 2540 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2541 if (!NonNull->args_size()) { 2542 // Easy case: all pointer arguments are nonnull. 2543 for (const auto *Arg : Args) 2544 if (S.isValidPointerAttrType(Arg->getType())) 2545 CheckNonNullArgument(S, Arg, CallSiteLoc); 2546 return; 2547 } 2548 2549 for (unsigned Val : NonNull->args()) { 2550 if (Val >= Args.size()) 2551 continue; 2552 if (NonNullArgs.empty()) 2553 NonNullArgs.resize(Args.size()); 2554 NonNullArgs.set(Val); 2555 } 2556 } 2557 } 2558 2559 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2560 // Handle the nonnull attribute on the parameters of the 2561 // function/method. 2562 ArrayRef<ParmVarDecl*> parms; 2563 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2564 parms = FD->parameters(); 2565 else 2566 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2567 2568 unsigned ParamIndex = 0; 2569 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2570 I != E; ++I, ++ParamIndex) { 2571 const ParmVarDecl *PVD = *I; 2572 if (PVD->hasAttr<NonNullAttr>() || 2573 isNonNullType(S.Context, PVD->getType())) { 2574 if (NonNullArgs.empty()) 2575 NonNullArgs.resize(Args.size()); 2576 2577 NonNullArgs.set(ParamIndex); 2578 } 2579 } 2580 } else { 2581 // If we have a non-function, non-method declaration but no 2582 // function prototype, try to dig out the function prototype. 2583 if (!Proto) { 2584 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2585 QualType type = VD->getType().getNonReferenceType(); 2586 if (auto pointerType = type->getAs<PointerType>()) 2587 type = pointerType->getPointeeType(); 2588 else if (auto blockType = type->getAs<BlockPointerType>()) 2589 type = blockType->getPointeeType(); 2590 // FIXME: data member pointers? 2591 2592 // Dig out the function prototype, if there is one. 2593 Proto = type->getAs<FunctionProtoType>(); 2594 } 2595 } 2596 2597 // Fill in non-null argument information from the nullability 2598 // information on the parameter types (if we have them). 2599 if (Proto) { 2600 unsigned Index = 0; 2601 for (auto paramType : Proto->getParamTypes()) { 2602 if (isNonNullType(S.Context, paramType)) { 2603 if (NonNullArgs.empty()) 2604 NonNullArgs.resize(Args.size()); 2605 2606 NonNullArgs.set(Index); 2607 } 2608 2609 ++Index; 2610 } 2611 } 2612 } 2613 2614 // Check for non-null arguments. 2615 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2616 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2617 if (NonNullArgs[ArgIndex]) 2618 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2619 } 2620 } 2621 2622 /// Handles the checks for format strings, non-POD arguments to vararg 2623 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 2624 /// attributes. 2625 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2626 const Expr *ThisArg, ArrayRef<const Expr *> Args, 2627 bool IsMemberFunction, SourceLocation Loc, 2628 SourceRange Range, VariadicCallType CallType) { 2629 // FIXME: We should check as much as we can in the template definition. 2630 if (CurContext->isDependentContext()) 2631 return; 2632 2633 // Printf and scanf checking. 2634 llvm::SmallBitVector CheckedVarArgs; 2635 if (FDecl) { 2636 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2637 // Only create vector if there are format attributes. 2638 CheckedVarArgs.resize(Args.size()); 2639 2640 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2641 CheckedVarArgs); 2642 } 2643 } 2644 2645 // Refuse POD arguments that weren't caught by the format string 2646 // checks above. 2647 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 2648 if (CallType != VariadicDoesNotApply && 2649 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 2650 unsigned NumParams = Proto ? Proto->getNumParams() 2651 : FDecl && isa<FunctionDecl>(FDecl) 2652 ? cast<FunctionDecl>(FDecl)->getNumParams() 2653 : FDecl && isa<ObjCMethodDecl>(FDecl) 2654 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2655 : 0; 2656 2657 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2658 // Args[ArgIdx] can be null in malformed code. 2659 if (const Expr *Arg = Args[ArgIdx]) { 2660 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 2661 checkVariadicArgument(Arg, CallType); 2662 } 2663 } 2664 } 2665 2666 if (FDecl || Proto) { 2667 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 2668 2669 // Type safety checking. 2670 if (FDecl) { 2671 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 2672 CheckArgumentWithTypeTag(I, Args.data()); 2673 } 2674 } 2675 2676 if (FD) 2677 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 2678 } 2679 2680 /// CheckConstructorCall - Check a constructor call for correctness and safety 2681 /// properties not enforced by the C type system. 2682 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 2683 ArrayRef<const Expr *> Args, 2684 const FunctionProtoType *Proto, 2685 SourceLocation Loc) { 2686 VariadicCallType CallType = 2687 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 2688 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 2689 Loc, SourceRange(), CallType); 2690 } 2691 2692 /// CheckFunctionCall - Check a direct function call for various correctness 2693 /// and safety properties not strictly enforced by the C type system. 2694 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2695 const FunctionProtoType *Proto) { 2696 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 2697 isa<CXXMethodDecl>(FDecl); 2698 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 2699 IsMemberOperatorCall; 2700 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 2701 TheCall->getCallee()); 2702 Expr** Args = TheCall->getArgs(); 2703 unsigned NumArgs = TheCall->getNumArgs(); 2704 2705 Expr *ImplicitThis = nullptr; 2706 if (IsMemberOperatorCall) { 2707 // If this is a call to a member operator, hide the first argument 2708 // from checkCall. 2709 // FIXME: Our choice of AST representation here is less than ideal. 2710 ImplicitThis = Args[0]; 2711 ++Args; 2712 --NumArgs; 2713 } else if (IsMemberFunction) 2714 ImplicitThis = 2715 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 2716 2717 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 2718 IsMemberFunction, TheCall->getRParenLoc(), 2719 TheCall->getCallee()->getSourceRange(), CallType); 2720 2721 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 2722 // None of the checks below are needed for functions that don't have 2723 // simple names (e.g., C++ conversion functions). 2724 if (!FnInfo) 2725 return false; 2726 2727 CheckAbsoluteValueFunction(TheCall, FDecl); 2728 CheckMaxUnsignedZero(TheCall, FDecl); 2729 2730 if (getLangOpts().ObjC1) 2731 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 2732 2733 unsigned CMId = FDecl->getMemoryFunctionKind(); 2734 if (CMId == 0) 2735 return false; 2736 2737 // Handle memory setting and copying functions. 2738 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 2739 CheckStrlcpycatArguments(TheCall, FnInfo); 2740 else if (CMId == Builtin::BIstrncat) 2741 CheckStrncatArguments(TheCall, FnInfo); 2742 else 2743 CheckMemaccessArguments(TheCall, CMId, FnInfo); 2744 2745 return false; 2746 } 2747 2748 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 2749 ArrayRef<const Expr *> Args) { 2750 VariadicCallType CallType = 2751 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 2752 2753 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 2754 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 2755 CallType); 2756 2757 return false; 2758 } 2759 2760 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2761 const FunctionProtoType *Proto) { 2762 QualType Ty; 2763 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 2764 Ty = V->getType().getNonReferenceType(); 2765 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 2766 Ty = F->getType().getNonReferenceType(); 2767 else 2768 return false; 2769 2770 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 2771 !Ty->isFunctionProtoType()) 2772 return false; 2773 2774 VariadicCallType CallType; 2775 if (!Proto || !Proto->isVariadic()) { 2776 CallType = VariadicDoesNotApply; 2777 } else if (Ty->isBlockPointerType()) { 2778 CallType = VariadicBlock; 2779 } else { // Ty->isFunctionPointerType() 2780 CallType = VariadicFunction; 2781 } 2782 2783 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 2784 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2785 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2786 TheCall->getCallee()->getSourceRange(), CallType); 2787 2788 return false; 2789 } 2790 2791 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2792 /// such as function pointers returned from functions. 2793 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 2794 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 2795 TheCall->getCallee()); 2796 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 2797 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2798 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2799 TheCall->getCallee()->getSourceRange(), CallType); 2800 2801 return false; 2802 } 2803 2804 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 2805 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 2806 return false; 2807 2808 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 2809 switch (Op) { 2810 case AtomicExpr::AO__c11_atomic_init: 2811 case AtomicExpr::AO__opencl_atomic_init: 2812 llvm_unreachable("There is no ordering argument for an init"); 2813 2814 case AtomicExpr::AO__c11_atomic_load: 2815 case AtomicExpr::AO__opencl_atomic_load: 2816 case AtomicExpr::AO__atomic_load_n: 2817 case AtomicExpr::AO__atomic_load: 2818 return OrderingCABI != llvm::AtomicOrderingCABI::release && 2819 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2820 2821 case AtomicExpr::AO__c11_atomic_store: 2822 case AtomicExpr::AO__opencl_atomic_store: 2823 case AtomicExpr::AO__atomic_store: 2824 case AtomicExpr::AO__atomic_store_n: 2825 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 2826 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 2827 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2828 2829 default: 2830 return true; 2831 } 2832 } 2833 2834 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 2835 AtomicExpr::AtomicOp Op) { 2836 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 2837 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2838 2839 // All the non-OpenCL operations take one of the following forms. 2840 // The OpenCL operations take the __c11 forms with one extra argument for 2841 // synchronization scope. 2842 enum { 2843 // C __c11_atomic_init(A *, C) 2844 Init, 2845 // C __c11_atomic_load(A *, int) 2846 Load, 2847 // void __atomic_load(A *, CP, int) 2848 LoadCopy, 2849 // void __atomic_store(A *, CP, int) 2850 Copy, 2851 // C __c11_atomic_add(A *, M, int) 2852 Arithmetic, 2853 // C __atomic_exchange_n(A *, CP, int) 2854 Xchg, 2855 // void __atomic_exchange(A *, C *, CP, int) 2856 GNUXchg, 2857 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 2858 C11CmpXchg, 2859 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 2860 GNUCmpXchg 2861 } Form = Init; 2862 const unsigned NumForm = GNUCmpXchg + 1; 2863 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 2864 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 2865 // where: 2866 // C is an appropriate type, 2867 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 2868 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 2869 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 2870 // the int parameters are for orderings. 2871 2872 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 2873 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 2874 "need to update code for modified forms"); 2875 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 2876 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 2877 AtomicExpr::AO__atomic_load, 2878 "need to update code for modified C11 atomics"); 2879 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 2880 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 2881 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 2882 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 2883 IsOpenCL; 2884 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 2885 Op == AtomicExpr::AO__atomic_store_n || 2886 Op == AtomicExpr::AO__atomic_exchange_n || 2887 Op == AtomicExpr::AO__atomic_compare_exchange_n; 2888 bool IsAddSub = false; 2889 2890 switch (Op) { 2891 case AtomicExpr::AO__c11_atomic_init: 2892 case AtomicExpr::AO__opencl_atomic_init: 2893 Form = Init; 2894 break; 2895 2896 case AtomicExpr::AO__c11_atomic_load: 2897 case AtomicExpr::AO__opencl_atomic_load: 2898 case AtomicExpr::AO__atomic_load_n: 2899 Form = Load; 2900 break; 2901 2902 case AtomicExpr::AO__atomic_load: 2903 Form = LoadCopy; 2904 break; 2905 2906 case AtomicExpr::AO__c11_atomic_store: 2907 case AtomicExpr::AO__opencl_atomic_store: 2908 case AtomicExpr::AO__atomic_store: 2909 case AtomicExpr::AO__atomic_store_n: 2910 Form = Copy; 2911 break; 2912 2913 case AtomicExpr::AO__c11_atomic_fetch_add: 2914 case AtomicExpr::AO__c11_atomic_fetch_sub: 2915 case AtomicExpr::AO__opencl_atomic_fetch_add: 2916 case AtomicExpr::AO__opencl_atomic_fetch_sub: 2917 case AtomicExpr::AO__opencl_atomic_fetch_min: 2918 case AtomicExpr::AO__opencl_atomic_fetch_max: 2919 case AtomicExpr::AO__atomic_fetch_add: 2920 case AtomicExpr::AO__atomic_fetch_sub: 2921 case AtomicExpr::AO__atomic_add_fetch: 2922 case AtomicExpr::AO__atomic_sub_fetch: 2923 IsAddSub = true; 2924 // Fall through. 2925 case AtomicExpr::AO__c11_atomic_fetch_and: 2926 case AtomicExpr::AO__c11_atomic_fetch_or: 2927 case AtomicExpr::AO__c11_atomic_fetch_xor: 2928 case AtomicExpr::AO__opencl_atomic_fetch_and: 2929 case AtomicExpr::AO__opencl_atomic_fetch_or: 2930 case AtomicExpr::AO__opencl_atomic_fetch_xor: 2931 case AtomicExpr::AO__atomic_fetch_and: 2932 case AtomicExpr::AO__atomic_fetch_or: 2933 case AtomicExpr::AO__atomic_fetch_xor: 2934 case AtomicExpr::AO__atomic_fetch_nand: 2935 case AtomicExpr::AO__atomic_and_fetch: 2936 case AtomicExpr::AO__atomic_or_fetch: 2937 case AtomicExpr::AO__atomic_xor_fetch: 2938 case AtomicExpr::AO__atomic_nand_fetch: 2939 Form = Arithmetic; 2940 break; 2941 2942 case AtomicExpr::AO__c11_atomic_exchange: 2943 case AtomicExpr::AO__opencl_atomic_exchange: 2944 case AtomicExpr::AO__atomic_exchange_n: 2945 Form = Xchg; 2946 break; 2947 2948 case AtomicExpr::AO__atomic_exchange: 2949 Form = GNUXchg; 2950 break; 2951 2952 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 2953 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 2954 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 2955 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 2956 Form = C11CmpXchg; 2957 break; 2958 2959 case AtomicExpr::AO__atomic_compare_exchange: 2960 case AtomicExpr::AO__atomic_compare_exchange_n: 2961 Form = GNUCmpXchg; 2962 break; 2963 } 2964 2965 unsigned AdjustedNumArgs = NumArgs[Form]; 2966 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 2967 ++AdjustedNumArgs; 2968 // Check we have the right number of arguments. 2969 if (TheCall->getNumArgs() < AdjustedNumArgs) { 2970 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 2971 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 2972 << TheCall->getCallee()->getSourceRange(); 2973 return ExprError(); 2974 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 2975 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(), 2976 diag::err_typecheck_call_too_many_args) 2977 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 2978 << TheCall->getCallee()->getSourceRange(); 2979 return ExprError(); 2980 } 2981 2982 // Inspect the first argument of the atomic operation. 2983 Expr *Ptr = TheCall->getArg(0); 2984 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 2985 if (ConvertedPtr.isInvalid()) 2986 return ExprError(); 2987 2988 Ptr = ConvertedPtr.get(); 2989 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 2990 if (!pointerType) { 2991 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 2992 << Ptr->getType() << Ptr->getSourceRange(); 2993 return ExprError(); 2994 } 2995 2996 // For a __c11 builtin, this should be a pointer to an _Atomic type. 2997 QualType AtomTy = pointerType->getPointeeType(); // 'A' 2998 QualType ValType = AtomTy; // 'C' 2999 if (IsC11) { 3000 if (!AtomTy->isAtomicType()) { 3001 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 3002 << Ptr->getType() << Ptr->getSourceRange(); 3003 return ExprError(); 3004 } 3005 if (AtomTy.isConstQualified() || 3006 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 3007 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 3008 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 3009 << Ptr->getSourceRange(); 3010 return ExprError(); 3011 } 3012 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 3013 } else if (Form != Load && Form != LoadCopy) { 3014 if (ValType.isConstQualified()) { 3015 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 3016 << Ptr->getType() << Ptr->getSourceRange(); 3017 return ExprError(); 3018 } 3019 } 3020 3021 // For an arithmetic operation, the implied arithmetic must be well-formed. 3022 if (Form == Arithmetic) { 3023 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 3024 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 3025 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3026 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3027 return ExprError(); 3028 } 3029 if (!IsAddSub && !ValType->isIntegerType()) { 3030 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 3031 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3032 return ExprError(); 3033 } 3034 if (IsC11 && ValType->isPointerType() && 3035 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 3036 diag::err_incomplete_type)) { 3037 return ExprError(); 3038 } 3039 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 3040 // For __atomic_*_n operations, the value type must be a scalar integral or 3041 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 3042 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3043 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3044 return ExprError(); 3045 } 3046 3047 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 3048 !AtomTy->isScalarType()) { 3049 // For GNU atomics, require a trivially-copyable type. This is not part of 3050 // the GNU atomics specification, but we enforce it for sanity. 3051 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 3052 << Ptr->getType() << Ptr->getSourceRange(); 3053 return ExprError(); 3054 } 3055 3056 switch (ValType.getObjCLifetime()) { 3057 case Qualifiers::OCL_None: 3058 case Qualifiers::OCL_ExplicitNone: 3059 // okay 3060 break; 3061 3062 case Qualifiers::OCL_Weak: 3063 case Qualifiers::OCL_Strong: 3064 case Qualifiers::OCL_Autoreleasing: 3065 // FIXME: Can this happen? By this point, ValType should be known 3066 // to be trivially copyable. 3067 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3068 << ValType << Ptr->getSourceRange(); 3069 return ExprError(); 3070 } 3071 3072 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 3073 // volatile-ness of the pointee-type inject itself into the result or the 3074 // other operands. Similarly atomic_load can take a pointer to a const 'A'. 3075 ValType.removeLocalVolatile(); 3076 ValType.removeLocalConst(); 3077 QualType ResultType = ValType; 3078 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 3079 Form == Init) 3080 ResultType = Context.VoidTy; 3081 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 3082 ResultType = Context.BoolTy; 3083 3084 // The type of a parameter passed 'by value'. In the GNU atomics, such 3085 // arguments are actually passed as pointers. 3086 QualType ByValType = ValType; // 'CP' 3087 if (!IsC11 && !IsN) 3088 ByValType = Ptr->getType(); 3089 3090 // The first argument --- the pointer --- has a fixed type; we 3091 // deduce the types of the rest of the arguments accordingly. Walk 3092 // the remaining arguments, converting them to the deduced value type. 3093 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) { 3094 QualType Ty; 3095 if (i < NumVals[Form] + 1) { 3096 switch (i) { 3097 case 1: 3098 // The second argument is the non-atomic operand. For arithmetic, this 3099 // is always passed by value, and for a compare_exchange it is always 3100 // passed by address. For the rest, GNU uses by-address and C11 uses 3101 // by-value. 3102 assert(Form != Load); 3103 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 3104 Ty = ValType; 3105 else if (Form == Copy || Form == Xchg) 3106 Ty = ByValType; 3107 else if (Form == Arithmetic) 3108 Ty = Context.getPointerDiffType(); 3109 else { 3110 Expr *ValArg = TheCall->getArg(i); 3111 // Treat this argument as _Nonnull as we want to show a warning if 3112 // NULL is passed into it. 3113 CheckNonNullArgument(*this, ValArg, DRE->getLocStart()); 3114 unsigned AS = 0; 3115 // Keep address space of non-atomic pointer type. 3116 if (const PointerType *PtrTy = 3117 ValArg->getType()->getAs<PointerType>()) { 3118 AS = PtrTy->getPointeeType().getAddressSpace(); 3119 } 3120 Ty = Context.getPointerType( 3121 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 3122 } 3123 break; 3124 case 2: 3125 // The third argument to compare_exchange / GNU exchange is a 3126 // (pointer to a) desired value. 3127 Ty = ByValType; 3128 break; 3129 case 3: 3130 // The fourth argument to GNU compare_exchange is a 'weak' flag. 3131 Ty = Context.BoolTy; 3132 break; 3133 } 3134 } else { 3135 // The order(s) and scope are always converted to int. 3136 Ty = Context.IntTy; 3137 } 3138 3139 InitializedEntity Entity = 3140 InitializedEntity::InitializeParameter(Context, Ty, false); 3141 ExprResult Arg = TheCall->getArg(i); 3142 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3143 if (Arg.isInvalid()) 3144 return true; 3145 TheCall->setArg(i, Arg.get()); 3146 } 3147 3148 Expr *Scope; 3149 if (Form != Init) { 3150 if (IsOpenCL) { 3151 Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 3152 llvm::APSInt Result(32); 3153 if (!Scope->isIntegerConstantExpr(Result, Context)) 3154 Diag(Scope->getLocStart(), 3155 diag::err_atomic_op_has_non_constant_synch_scope) 3156 << Scope->getSourceRange(); 3157 else if (!isValidSyncScopeValue(Result.getZExtValue())) 3158 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope) 3159 << Scope->getSourceRange(); 3160 } else { 3161 Scope = IntegerLiteral::Create( 3162 Context, 3163 llvm::APInt(Context.getTypeSize(Context.IntTy), 3164 static_cast<unsigned>(SyncScope::OpenCLAllSVMDevices)), 3165 Context.IntTy, SourceLocation()); 3166 } 3167 } 3168 3169 // Permute the arguments into a 'consistent' order. 3170 SmallVector<Expr*, 5> SubExprs; 3171 SubExprs.push_back(Ptr); 3172 switch (Form) { 3173 case Init: 3174 // Note, AtomicExpr::getVal1() has a special case for this atomic. 3175 SubExprs.push_back(TheCall->getArg(1)); // Val1 3176 break; 3177 case Load: 3178 SubExprs.push_back(TheCall->getArg(1)); // Order 3179 SubExprs.push_back(Scope); // Scope 3180 break; 3181 case LoadCopy: 3182 case Copy: 3183 case Arithmetic: 3184 case Xchg: 3185 SubExprs.push_back(TheCall->getArg(2)); // Order 3186 SubExprs.push_back(Scope); // Scope 3187 SubExprs.push_back(TheCall->getArg(1)); // Val1 3188 break; 3189 case GNUXchg: 3190 // Note, AtomicExpr::getVal2() has a special case for this atomic. 3191 SubExprs.push_back(TheCall->getArg(3)); // Order 3192 SubExprs.push_back(Scope); // Scope 3193 SubExprs.push_back(TheCall->getArg(1)); // Val1 3194 SubExprs.push_back(TheCall->getArg(2)); // Val2 3195 break; 3196 case C11CmpXchg: 3197 SubExprs.push_back(TheCall->getArg(3)); // Order 3198 SubExprs.push_back(Scope); // Scope 3199 SubExprs.push_back(TheCall->getArg(1)); // Val1 3200 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 3201 SubExprs.push_back(TheCall->getArg(2)); // Val2 3202 break; 3203 case GNUCmpXchg: 3204 SubExprs.push_back(TheCall->getArg(4)); // Order 3205 SubExprs.push_back(Scope); // Scope 3206 SubExprs.push_back(TheCall->getArg(1)); // Val1 3207 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 3208 SubExprs.push_back(TheCall->getArg(2)); // Val2 3209 SubExprs.push_back(TheCall->getArg(3)); // Weak 3210 break; 3211 } 3212 3213 if (SubExprs.size() >= 2 && Form != Init) { 3214 llvm::APSInt Result(32); 3215 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 3216 !isValidOrderingForOp(Result.getSExtValue(), Op)) 3217 Diag(SubExprs[1]->getLocStart(), 3218 diag::warn_atomic_op_has_invalid_memory_order) 3219 << SubExprs[1]->getSourceRange(); 3220 } 3221 3222 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 3223 SubExprs, ResultType, Op, 3224 TheCall->getRParenLoc()); 3225 3226 if ((Op == AtomicExpr::AO__c11_atomic_load || 3227 Op == AtomicExpr::AO__c11_atomic_store || 3228 Op == AtomicExpr::AO__opencl_atomic_load || 3229 Op == AtomicExpr::AO__opencl_atomic_store ) && 3230 Context.AtomicUsesUnsupportedLibcall(AE)) 3231 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) 3232 << ((Op == AtomicExpr::AO__c11_atomic_load || 3233 Op == AtomicExpr::AO__opencl_atomic_load) 3234 ? 0 : 1); 3235 3236 return AE; 3237 } 3238 3239 /// checkBuiltinArgument - Given a call to a builtin function, perform 3240 /// normal type-checking on the given argument, updating the call in 3241 /// place. This is useful when a builtin function requires custom 3242 /// type-checking for some of its arguments but not necessarily all of 3243 /// them. 3244 /// 3245 /// Returns true on error. 3246 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 3247 FunctionDecl *Fn = E->getDirectCallee(); 3248 assert(Fn && "builtin call without direct callee!"); 3249 3250 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 3251 InitializedEntity Entity = 3252 InitializedEntity::InitializeParameter(S.Context, Param); 3253 3254 ExprResult Arg = E->getArg(0); 3255 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 3256 if (Arg.isInvalid()) 3257 return true; 3258 3259 E->setArg(ArgIndex, Arg.get()); 3260 return false; 3261 } 3262 3263 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 3264 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 3265 /// type of its first argument. The main ActOnCallExpr routines have already 3266 /// promoted the types of arguments because all of these calls are prototyped as 3267 /// void(...). 3268 /// 3269 /// This function goes through and does final semantic checking for these 3270 /// builtins, 3271 ExprResult 3272 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3273 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3274 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3275 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3276 3277 // Ensure that we have at least one argument to do type inference from. 3278 if (TheCall->getNumArgs() < 1) { 3279 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3280 << 0 << 1 << TheCall->getNumArgs() 3281 << TheCall->getCallee()->getSourceRange(); 3282 return ExprError(); 3283 } 3284 3285 // Inspect the first argument of the atomic builtin. This should always be 3286 // a pointer type, whose element is an integral scalar or pointer type. 3287 // Because it is a pointer type, we don't have to worry about any implicit 3288 // casts here. 3289 // FIXME: We don't allow floating point scalars as input. 3290 Expr *FirstArg = TheCall->getArg(0); 3291 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3292 if (FirstArgResult.isInvalid()) 3293 return ExprError(); 3294 FirstArg = FirstArgResult.get(); 3295 TheCall->setArg(0, FirstArg); 3296 3297 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3298 if (!pointerType) { 3299 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3300 << FirstArg->getType() << FirstArg->getSourceRange(); 3301 return ExprError(); 3302 } 3303 3304 QualType ValType = pointerType->getPointeeType(); 3305 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3306 !ValType->isBlockPointerType()) { 3307 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3308 << FirstArg->getType() << FirstArg->getSourceRange(); 3309 return ExprError(); 3310 } 3311 3312 switch (ValType.getObjCLifetime()) { 3313 case Qualifiers::OCL_None: 3314 case Qualifiers::OCL_ExplicitNone: 3315 // okay 3316 break; 3317 3318 case Qualifiers::OCL_Weak: 3319 case Qualifiers::OCL_Strong: 3320 case Qualifiers::OCL_Autoreleasing: 3321 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3322 << ValType << FirstArg->getSourceRange(); 3323 return ExprError(); 3324 } 3325 3326 // Strip any qualifiers off ValType. 3327 ValType = ValType.getUnqualifiedType(); 3328 3329 // The majority of builtins return a value, but a few have special return 3330 // types, so allow them to override appropriately below. 3331 QualType ResultType = ValType; 3332 3333 // We need to figure out which concrete builtin this maps onto. For example, 3334 // __sync_fetch_and_add with a 2 byte object turns into 3335 // __sync_fetch_and_add_2. 3336 #define BUILTIN_ROW(x) \ 3337 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3338 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3339 3340 static const unsigned BuiltinIndices[][5] = { 3341 BUILTIN_ROW(__sync_fetch_and_add), 3342 BUILTIN_ROW(__sync_fetch_and_sub), 3343 BUILTIN_ROW(__sync_fetch_and_or), 3344 BUILTIN_ROW(__sync_fetch_and_and), 3345 BUILTIN_ROW(__sync_fetch_and_xor), 3346 BUILTIN_ROW(__sync_fetch_and_nand), 3347 3348 BUILTIN_ROW(__sync_add_and_fetch), 3349 BUILTIN_ROW(__sync_sub_and_fetch), 3350 BUILTIN_ROW(__sync_and_and_fetch), 3351 BUILTIN_ROW(__sync_or_and_fetch), 3352 BUILTIN_ROW(__sync_xor_and_fetch), 3353 BUILTIN_ROW(__sync_nand_and_fetch), 3354 3355 BUILTIN_ROW(__sync_val_compare_and_swap), 3356 BUILTIN_ROW(__sync_bool_compare_and_swap), 3357 BUILTIN_ROW(__sync_lock_test_and_set), 3358 BUILTIN_ROW(__sync_lock_release), 3359 BUILTIN_ROW(__sync_swap) 3360 }; 3361 #undef BUILTIN_ROW 3362 3363 // Determine the index of the size. 3364 unsigned SizeIndex; 3365 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3366 case 1: SizeIndex = 0; break; 3367 case 2: SizeIndex = 1; break; 3368 case 4: SizeIndex = 2; break; 3369 case 8: SizeIndex = 3; break; 3370 case 16: SizeIndex = 4; break; 3371 default: 3372 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3373 << FirstArg->getType() << FirstArg->getSourceRange(); 3374 return ExprError(); 3375 } 3376 3377 // Each of these builtins has one pointer argument, followed by some number of 3378 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3379 // that we ignore. Find out which row of BuiltinIndices to read from as well 3380 // as the number of fixed args. 3381 unsigned BuiltinID = FDecl->getBuiltinID(); 3382 unsigned BuiltinIndex, NumFixed = 1; 3383 bool WarnAboutSemanticsChange = false; 3384 switch (BuiltinID) { 3385 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3386 case Builtin::BI__sync_fetch_and_add: 3387 case Builtin::BI__sync_fetch_and_add_1: 3388 case Builtin::BI__sync_fetch_and_add_2: 3389 case Builtin::BI__sync_fetch_and_add_4: 3390 case Builtin::BI__sync_fetch_and_add_8: 3391 case Builtin::BI__sync_fetch_and_add_16: 3392 BuiltinIndex = 0; 3393 break; 3394 3395 case Builtin::BI__sync_fetch_and_sub: 3396 case Builtin::BI__sync_fetch_and_sub_1: 3397 case Builtin::BI__sync_fetch_and_sub_2: 3398 case Builtin::BI__sync_fetch_and_sub_4: 3399 case Builtin::BI__sync_fetch_and_sub_8: 3400 case Builtin::BI__sync_fetch_and_sub_16: 3401 BuiltinIndex = 1; 3402 break; 3403 3404 case Builtin::BI__sync_fetch_and_or: 3405 case Builtin::BI__sync_fetch_and_or_1: 3406 case Builtin::BI__sync_fetch_and_or_2: 3407 case Builtin::BI__sync_fetch_and_or_4: 3408 case Builtin::BI__sync_fetch_and_or_8: 3409 case Builtin::BI__sync_fetch_and_or_16: 3410 BuiltinIndex = 2; 3411 break; 3412 3413 case Builtin::BI__sync_fetch_and_and: 3414 case Builtin::BI__sync_fetch_and_and_1: 3415 case Builtin::BI__sync_fetch_and_and_2: 3416 case Builtin::BI__sync_fetch_and_and_4: 3417 case Builtin::BI__sync_fetch_and_and_8: 3418 case Builtin::BI__sync_fetch_and_and_16: 3419 BuiltinIndex = 3; 3420 break; 3421 3422 case Builtin::BI__sync_fetch_and_xor: 3423 case Builtin::BI__sync_fetch_and_xor_1: 3424 case Builtin::BI__sync_fetch_and_xor_2: 3425 case Builtin::BI__sync_fetch_and_xor_4: 3426 case Builtin::BI__sync_fetch_and_xor_8: 3427 case Builtin::BI__sync_fetch_and_xor_16: 3428 BuiltinIndex = 4; 3429 break; 3430 3431 case Builtin::BI__sync_fetch_and_nand: 3432 case Builtin::BI__sync_fetch_and_nand_1: 3433 case Builtin::BI__sync_fetch_and_nand_2: 3434 case Builtin::BI__sync_fetch_and_nand_4: 3435 case Builtin::BI__sync_fetch_and_nand_8: 3436 case Builtin::BI__sync_fetch_and_nand_16: 3437 BuiltinIndex = 5; 3438 WarnAboutSemanticsChange = true; 3439 break; 3440 3441 case Builtin::BI__sync_add_and_fetch: 3442 case Builtin::BI__sync_add_and_fetch_1: 3443 case Builtin::BI__sync_add_and_fetch_2: 3444 case Builtin::BI__sync_add_and_fetch_4: 3445 case Builtin::BI__sync_add_and_fetch_8: 3446 case Builtin::BI__sync_add_and_fetch_16: 3447 BuiltinIndex = 6; 3448 break; 3449 3450 case Builtin::BI__sync_sub_and_fetch: 3451 case Builtin::BI__sync_sub_and_fetch_1: 3452 case Builtin::BI__sync_sub_and_fetch_2: 3453 case Builtin::BI__sync_sub_and_fetch_4: 3454 case Builtin::BI__sync_sub_and_fetch_8: 3455 case Builtin::BI__sync_sub_and_fetch_16: 3456 BuiltinIndex = 7; 3457 break; 3458 3459 case Builtin::BI__sync_and_and_fetch: 3460 case Builtin::BI__sync_and_and_fetch_1: 3461 case Builtin::BI__sync_and_and_fetch_2: 3462 case Builtin::BI__sync_and_and_fetch_4: 3463 case Builtin::BI__sync_and_and_fetch_8: 3464 case Builtin::BI__sync_and_and_fetch_16: 3465 BuiltinIndex = 8; 3466 break; 3467 3468 case Builtin::BI__sync_or_and_fetch: 3469 case Builtin::BI__sync_or_and_fetch_1: 3470 case Builtin::BI__sync_or_and_fetch_2: 3471 case Builtin::BI__sync_or_and_fetch_4: 3472 case Builtin::BI__sync_or_and_fetch_8: 3473 case Builtin::BI__sync_or_and_fetch_16: 3474 BuiltinIndex = 9; 3475 break; 3476 3477 case Builtin::BI__sync_xor_and_fetch: 3478 case Builtin::BI__sync_xor_and_fetch_1: 3479 case Builtin::BI__sync_xor_and_fetch_2: 3480 case Builtin::BI__sync_xor_and_fetch_4: 3481 case Builtin::BI__sync_xor_and_fetch_8: 3482 case Builtin::BI__sync_xor_and_fetch_16: 3483 BuiltinIndex = 10; 3484 break; 3485 3486 case Builtin::BI__sync_nand_and_fetch: 3487 case Builtin::BI__sync_nand_and_fetch_1: 3488 case Builtin::BI__sync_nand_and_fetch_2: 3489 case Builtin::BI__sync_nand_and_fetch_4: 3490 case Builtin::BI__sync_nand_and_fetch_8: 3491 case Builtin::BI__sync_nand_and_fetch_16: 3492 BuiltinIndex = 11; 3493 WarnAboutSemanticsChange = true; 3494 break; 3495 3496 case Builtin::BI__sync_val_compare_and_swap: 3497 case Builtin::BI__sync_val_compare_and_swap_1: 3498 case Builtin::BI__sync_val_compare_and_swap_2: 3499 case Builtin::BI__sync_val_compare_and_swap_4: 3500 case Builtin::BI__sync_val_compare_and_swap_8: 3501 case Builtin::BI__sync_val_compare_and_swap_16: 3502 BuiltinIndex = 12; 3503 NumFixed = 2; 3504 break; 3505 3506 case Builtin::BI__sync_bool_compare_and_swap: 3507 case Builtin::BI__sync_bool_compare_and_swap_1: 3508 case Builtin::BI__sync_bool_compare_and_swap_2: 3509 case Builtin::BI__sync_bool_compare_and_swap_4: 3510 case Builtin::BI__sync_bool_compare_and_swap_8: 3511 case Builtin::BI__sync_bool_compare_and_swap_16: 3512 BuiltinIndex = 13; 3513 NumFixed = 2; 3514 ResultType = Context.BoolTy; 3515 break; 3516 3517 case Builtin::BI__sync_lock_test_and_set: 3518 case Builtin::BI__sync_lock_test_and_set_1: 3519 case Builtin::BI__sync_lock_test_and_set_2: 3520 case Builtin::BI__sync_lock_test_and_set_4: 3521 case Builtin::BI__sync_lock_test_and_set_8: 3522 case Builtin::BI__sync_lock_test_and_set_16: 3523 BuiltinIndex = 14; 3524 break; 3525 3526 case Builtin::BI__sync_lock_release: 3527 case Builtin::BI__sync_lock_release_1: 3528 case Builtin::BI__sync_lock_release_2: 3529 case Builtin::BI__sync_lock_release_4: 3530 case Builtin::BI__sync_lock_release_8: 3531 case Builtin::BI__sync_lock_release_16: 3532 BuiltinIndex = 15; 3533 NumFixed = 0; 3534 ResultType = Context.VoidTy; 3535 break; 3536 3537 case Builtin::BI__sync_swap: 3538 case Builtin::BI__sync_swap_1: 3539 case Builtin::BI__sync_swap_2: 3540 case Builtin::BI__sync_swap_4: 3541 case Builtin::BI__sync_swap_8: 3542 case Builtin::BI__sync_swap_16: 3543 BuiltinIndex = 16; 3544 break; 3545 } 3546 3547 // Now that we know how many fixed arguments we expect, first check that we 3548 // have at least that many. 3549 if (TheCall->getNumArgs() < 1+NumFixed) { 3550 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3551 << 0 << 1+NumFixed << TheCall->getNumArgs() 3552 << TheCall->getCallee()->getSourceRange(); 3553 return ExprError(); 3554 } 3555 3556 if (WarnAboutSemanticsChange) { 3557 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 3558 << TheCall->getCallee()->getSourceRange(); 3559 } 3560 3561 // Get the decl for the concrete builtin from this, we can tell what the 3562 // concrete integer type we should convert to is. 3563 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 3564 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 3565 FunctionDecl *NewBuiltinDecl; 3566 if (NewBuiltinID == BuiltinID) 3567 NewBuiltinDecl = FDecl; 3568 else { 3569 // Perform builtin lookup to avoid redeclaring it. 3570 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3571 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3572 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3573 assert(Res.getFoundDecl()); 3574 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3575 if (!NewBuiltinDecl) 3576 return ExprError(); 3577 } 3578 3579 // The first argument --- the pointer --- has a fixed type; we 3580 // deduce the types of the rest of the arguments accordingly. Walk 3581 // the remaining arguments, converting them to the deduced value type. 3582 for (unsigned i = 0; i != NumFixed; ++i) { 3583 ExprResult Arg = TheCall->getArg(i+1); 3584 3585 // GCC does an implicit conversion to the pointer or integer ValType. This 3586 // can fail in some cases (1i -> int**), check for this error case now. 3587 // Initialize the argument. 3588 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3589 ValType, /*consume*/ false); 3590 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3591 if (Arg.isInvalid()) 3592 return ExprError(); 3593 3594 // Okay, we have something that *can* be converted to the right type. Check 3595 // to see if there is a potentially weird extension going on here. This can 3596 // happen when you do an atomic operation on something like an char* and 3597 // pass in 42. The 42 gets converted to char. This is even more strange 3598 // for things like 45.123 -> char, etc. 3599 // FIXME: Do this check. 3600 TheCall->setArg(i+1, Arg.get()); 3601 } 3602 3603 ASTContext& Context = this->getASTContext(); 3604 3605 // Create a new DeclRefExpr to refer to the new decl. 3606 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3607 Context, 3608 DRE->getQualifierLoc(), 3609 SourceLocation(), 3610 NewBuiltinDecl, 3611 /*enclosing*/ false, 3612 DRE->getLocation(), 3613 Context.BuiltinFnTy, 3614 DRE->getValueKind()); 3615 3616 // Set the callee in the CallExpr. 3617 // FIXME: This loses syntactic information. 3618 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3619 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3620 CK_BuiltinFnToFnPtr); 3621 TheCall->setCallee(PromotedCall.get()); 3622 3623 // Change the result type of the call to match the original value type. This 3624 // is arbitrary, but the codegen for these builtins ins design to handle it 3625 // gracefully. 3626 TheCall->setType(ResultType); 3627 3628 return TheCallResult; 3629 } 3630 3631 /// SemaBuiltinNontemporalOverloaded - We have a call to 3632 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 3633 /// overloaded function based on the pointer type of its last argument. 3634 /// 3635 /// This function goes through and does final semantic checking for these 3636 /// builtins. 3637 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 3638 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3639 DeclRefExpr *DRE = 3640 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3641 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3642 unsigned BuiltinID = FDecl->getBuiltinID(); 3643 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 3644 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 3645 "Unexpected nontemporal load/store builtin!"); 3646 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 3647 unsigned numArgs = isStore ? 2 : 1; 3648 3649 // Ensure that we have the proper number of arguments. 3650 if (checkArgCount(*this, TheCall, numArgs)) 3651 return ExprError(); 3652 3653 // Inspect the last argument of the nontemporal builtin. This should always 3654 // be a pointer type, from which we imply the type of the memory access. 3655 // Because it is a pointer type, we don't have to worry about any implicit 3656 // casts here. 3657 Expr *PointerArg = TheCall->getArg(numArgs - 1); 3658 ExprResult PointerArgResult = 3659 DefaultFunctionArrayLvalueConversion(PointerArg); 3660 3661 if (PointerArgResult.isInvalid()) 3662 return ExprError(); 3663 PointerArg = PointerArgResult.get(); 3664 TheCall->setArg(numArgs - 1, PointerArg); 3665 3666 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3667 if (!pointerType) { 3668 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 3669 << PointerArg->getType() << PointerArg->getSourceRange(); 3670 return ExprError(); 3671 } 3672 3673 QualType ValType = pointerType->getPointeeType(); 3674 3675 // Strip any qualifiers off ValType. 3676 ValType = ValType.getUnqualifiedType(); 3677 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3678 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 3679 !ValType->isVectorType()) { 3680 Diag(DRE->getLocStart(), 3681 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 3682 << PointerArg->getType() << PointerArg->getSourceRange(); 3683 return ExprError(); 3684 } 3685 3686 if (!isStore) { 3687 TheCall->setType(ValType); 3688 return TheCallResult; 3689 } 3690 3691 ExprResult ValArg = TheCall->getArg(0); 3692 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3693 Context, ValType, /*consume*/ false); 3694 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3695 if (ValArg.isInvalid()) 3696 return ExprError(); 3697 3698 TheCall->setArg(0, ValArg.get()); 3699 TheCall->setType(Context.VoidTy); 3700 return TheCallResult; 3701 } 3702 3703 /// CheckObjCString - Checks that the argument to the builtin 3704 /// CFString constructor is correct 3705 /// Note: It might also make sense to do the UTF-16 conversion here (would 3706 /// simplify the backend). 3707 bool Sema::CheckObjCString(Expr *Arg) { 3708 Arg = Arg->IgnoreParenCasts(); 3709 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 3710 3711 if (!Literal || !Literal->isAscii()) { 3712 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 3713 << Arg->getSourceRange(); 3714 return true; 3715 } 3716 3717 if (Literal->containsNonAsciiOrNull()) { 3718 StringRef String = Literal->getString(); 3719 unsigned NumBytes = String.size(); 3720 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 3721 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 3722 llvm::UTF16 *ToPtr = &ToBuf[0]; 3723 3724 llvm::ConversionResult Result = 3725 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 3726 ToPtr + NumBytes, llvm::strictConversion); 3727 // Check for conversion failure. 3728 if (Result != llvm::conversionOK) 3729 Diag(Arg->getLocStart(), 3730 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 3731 } 3732 return false; 3733 } 3734 3735 /// CheckObjCString - Checks that the format string argument to the os_log() 3736 /// and os_trace() functions is correct, and converts it to const char *. 3737 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 3738 Arg = Arg->IgnoreParenCasts(); 3739 auto *Literal = dyn_cast<StringLiteral>(Arg); 3740 if (!Literal) { 3741 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 3742 Literal = ObjcLiteral->getString(); 3743 } 3744 } 3745 3746 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 3747 return ExprError( 3748 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 3749 << Arg->getSourceRange()); 3750 } 3751 3752 ExprResult Result(Literal); 3753 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 3754 InitializedEntity Entity = 3755 InitializedEntity::InitializeParameter(Context, ResultTy, false); 3756 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 3757 return Result; 3758 } 3759 3760 /// Check that the user is calling the appropriate va_start builtin for the 3761 /// target and calling convention. 3762 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 3763 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 3764 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 3765 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 3766 bool IsWindows = TT.isOSWindows(); 3767 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 3768 if (IsX64 || IsAArch64) { 3769 clang::CallingConv CC = CC_C; 3770 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 3771 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3772 if (IsMSVAStart) { 3773 // Don't allow this in System V ABI functions. 3774 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 3775 return S.Diag(Fn->getLocStart(), 3776 diag::err_ms_va_start_used_in_sysv_function); 3777 } else { 3778 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 3779 // On x64 Windows, don't allow this in System V ABI functions. 3780 // (Yes, that means there's no corresponding way to support variadic 3781 // System V ABI functions on Windows.) 3782 if ((IsWindows && CC == CC_X86_64SysV) || 3783 (!IsWindows && CC == CC_Win64)) 3784 return S.Diag(Fn->getLocStart(), 3785 diag::err_va_start_used_in_wrong_abi_function) 3786 << !IsWindows; 3787 } 3788 return false; 3789 } 3790 3791 if (IsMSVAStart) 3792 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only); 3793 return false; 3794 } 3795 3796 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 3797 ParmVarDecl **LastParam = nullptr) { 3798 // Determine whether the current function, block, or obj-c method is variadic 3799 // and get its parameter list. 3800 bool IsVariadic = false; 3801 ArrayRef<ParmVarDecl *> Params; 3802 DeclContext *Caller = S.CurContext; 3803 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 3804 IsVariadic = Block->isVariadic(); 3805 Params = Block->parameters(); 3806 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 3807 IsVariadic = FD->isVariadic(); 3808 Params = FD->parameters(); 3809 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 3810 IsVariadic = MD->isVariadic(); 3811 // FIXME: This isn't correct for methods (results in bogus warning). 3812 Params = MD->parameters(); 3813 } else if (isa<CapturedDecl>(Caller)) { 3814 // We don't support va_start in a CapturedDecl. 3815 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt); 3816 return true; 3817 } else { 3818 // This must be some other declcontext that parses exprs. 3819 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function); 3820 return true; 3821 } 3822 3823 if (!IsVariadic) { 3824 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function); 3825 return true; 3826 } 3827 3828 if (LastParam) 3829 *LastParam = Params.empty() ? nullptr : Params.back(); 3830 3831 return false; 3832 } 3833 3834 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 3835 /// for validity. Emit an error and return true on failure; return false 3836 /// on success. 3837 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 3838 Expr *Fn = TheCall->getCallee(); 3839 3840 if (checkVAStartABI(*this, BuiltinID, Fn)) 3841 return true; 3842 3843 if (TheCall->getNumArgs() > 2) { 3844 Diag(TheCall->getArg(2)->getLocStart(), 3845 diag::err_typecheck_call_too_many_args) 3846 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3847 << Fn->getSourceRange() 3848 << SourceRange(TheCall->getArg(2)->getLocStart(), 3849 (*(TheCall->arg_end()-1))->getLocEnd()); 3850 return true; 3851 } 3852 3853 if (TheCall->getNumArgs() < 2) { 3854 return Diag(TheCall->getLocEnd(), 3855 diag::err_typecheck_call_too_few_args_at_least) 3856 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 3857 } 3858 3859 // Type-check the first argument normally. 3860 if (checkBuiltinArgument(*this, TheCall, 0)) 3861 return true; 3862 3863 // Check that the current function is variadic, and get its last parameter. 3864 ParmVarDecl *LastParam; 3865 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 3866 return true; 3867 3868 // Verify that the second argument to the builtin is the last argument of the 3869 // current function or method. 3870 bool SecondArgIsLastNamedArgument = false; 3871 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 3872 3873 // These are valid if SecondArgIsLastNamedArgument is false after the next 3874 // block. 3875 QualType Type; 3876 SourceLocation ParamLoc; 3877 bool IsCRegister = false; 3878 3879 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 3880 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 3881 SecondArgIsLastNamedArgument = PV == LastParam; 3882 3883 Type = PV->getType(); 3884 ParamLoc = PV->getLocation(); 3885 IsCRegister = 3886 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 3887 } 3888 } 3889 3890 if (!SecondArgIsLastNamedArgument) 3891 Diag(TheCall->getArg(1)->getLocStart(), 3892 diag::warn_second_arg_of_va_start_not_last_named_param); 3893 else if (IsCRegister || Type->isReferenceType() || 3894 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 3895 // Promotable integers are UB, but enumerations need a bit of 3896 // extra checking to see what their promotable type actually is. 3897 if (!Type->isPromotableIntegerType()) 3898 return false; 3899 if (!Type->isEnumeralType()) 3900 return true; 3901 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 3902 return !(ED && 3903 Context.typesAreCompatible(ED->getPromotionType(), Type)); 3904 }()) { 3905 unsigned Reason = 0; 3906 if (Type->isReferenceType()) Reason = 1; 3907 else if (IsCRegister) Reason = 2; 3908 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 3909 Diag(ParamLoc, diag::note_parameter_type) << Type; 3910 } 3911 3912 TheCall->setType(Context.VoidTy); 3913 return false; 3914 } 3915 3916 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) { 3917 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 3918 // const char *named_addr); 3919 3920 Expr *Func = Call->getCallee(); 3921 3922 if (Call->getNumArgs() < 3) 3923 return Diag(Call->getLocEnd(), 3924 diag::err_typecheck_call_too_few_args_at_least) 3925 << 0 /*function call*/ << 3 << Call->getNumArgs(); 3926 3927 // Type-check the first argument normally. 3928 if (checkBuiltinArgument(*this, Call, 0)) 3929 return true; 3930 3931 // Check that the current function is variadic. 3932 if (checkVAStartIsInVariadicFunction(*this, Func)) 3933 return true; 3934 3935 const struct { 3936 unsigned ArgNo; 3937 QualType Type; 3938 } ArgumentTypes[] = { 3939 { 1, Context.getPointerType(Context.CharTy.withConst()) }, 3940 { 2, Context.getSizeType() }, 3941 }; 3942 3943 for (const auto &AT : ArgumentTypes) { 3944 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens(); 3945 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType()) 3946 continue; 3947 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible) 3948 << Arg->getType() << AT.Type << 1 /* different class */ 3949 << 0 /* qualifier difference */ << 3 /* parameter mismatch */ 3950 << AT.ArgNo + 1 << Arg->getType() << AT.Type; 3951 } 3952 3953 return false; 3954 } 3955 3956 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 3957 /// friends. This is declared to take (...), so we have to check everything. 3958 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 3959 if (TheCall->getNumArgs() < 2) 3960 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3961 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 3962 if (TheCall->getNumArgs() > 2) 3963 return Diag(TheCall->getArg(2)->getLocStart(), 3964 diag::err_typecheck_call_too_many_args) 3965 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3966 << SourceRange(TheCall->getArg(2)->getLocStart(), 3967 (*(TheCall->arg_end()-1))->getLocEnd()); 3968 3969 ExprResult OrigArg0 = TheCall->getArg(0); 3970 ExprResult OrigArg1 = TheCall->getArg(1); 3971 3972 // Do standard promotions between the two arguments, returning their common 3973 // type. 3974 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 3975 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 3976 return true; 3977 3978 // Make sure any conversions are pushed back into the call; this is 3979 // type safe since unordered compare builtins are declared as "_Bool 3980 // foo(...)". 3981 TheCall->setArg(0, OrigArg0.get()); 3982 TheCall->setArg(1, OrigArg1.get()); 3983 3984 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 3985 return false; 3986 3987 // If the common type isn't a real floating type, then the arguments were 3988 // invalid for this operation. 3989 if (Res.isNull() || !Res->isRealFloatingType()) 3990 return Diag(OrigArg0.get()->getLocStart(), 3991 diag::err_typecheck_call_invalid_ordered_compare) 3992 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 3993 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 3994 3995 return false; 3996 } 3997 3998 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 3999 /// __builtin_isnan and friends. This is declared to take (...), so we have 4000 /// to check everything. We expect the last argument to be a floating point 4001 /// value. 4002 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 4003 if (TheCall->getNumArgs() < NumArgs) 4004 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4005 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 4006 if (TheCall->getNumArgs() > NumArgs) 4007 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 4008 diag::err_typecheck_call_too_many_args) 4009 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 4010 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 4011 (*(TheCall->arg_end()-1))->getLocEnd()); 4012 4013 Expr *OrigArg = TheCall->getArg(NumArgs-1); 4014 4015 if (OrigArg->isTypeDependent()) 4016 return false; 4017 4018 // This operation requires a non-_Complex floating-point number. 4019 if (!OrigArg->getType()->isRealFloatingType()) 4020 return Diag(OrigArg->getLocStart(), 4021 diag::err_typecheck_call_invalid_unary_fp) 4022 << OrigArg->getType() << OrigArg->getSourceRange(); 4023 4024 // If this is an implicit conversion from float -> float or double, remove it. 4025 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 4026 // Only remove standard FloatCasts, leaving other casts inplace 4027 if (Cast->getCastKind() == CK_FloatingCast) { 4028 Expr *CastArg = Cast->getSubExpr(); 4029 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 4030 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 4031 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) && 4032 "promotion from float to either float or double is the only expected cast here"); 4033 Cast->setSubExpr(nullptr); 4034 TheCall->setArg(NumArgs-1, CastArg); 4035 } 4036 } 4037 } 4038 4039 return false; 4040 } 4041 4042 // Customized Sema Checking for VSX builtins that have the following signature: 4043 // vector [...] builtinName(vector [...], vector [...], const int); 4044 // Which takes the same type of vectors (any legal vector type) for the first 4045 // two arguments and takes compile time constant for the third argument. 4046 // Example builtins are : 4047 // vector double vec_xxpermdi(vector double, vector double, int); 4048 // vector short vec_xxsldwi(vector short, vector short, int); 4049 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 4050 unsigned ExpectedNumArgs = 3; 4051 if (TheCall->getNumArgs() < ExpectedNumArgs) 4052 return Diag(TheCall->getLocEnd(), 4053 diag::err_typecheck_call_too_few_args_at_least) 4054 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4055 << TheCall->getSourceRange(); 4056 4057 if (TheCall->getNumArgs() > ExpectedNumArgs) 4058 return Diag(TheCall->getLocEnd(), 4059 diag::err_typecheck_call_too_many_args_at_most) 4060 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4061 << TheCall->getSourceRange(); 4062 4063 // Check the third argument is a compile time constant 4064 llvm::APSInt Value; 4065 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 4066 return Diag(TheCall->getLocStart(), 4067 diag::err_vsx_builtin_nonconstant_argument) 4068 << 3 /* argument index */ << TheCall->getDirectCallee() 4069 << SourceRange(TheCall->getArg(2)->getLocStart(), 4070 TheCall->getArg(2)->getLocEnd()); 4071 4072 QualType Arg1Ty = TheCall->getArg(0)->getType(); 4073 QualType Arg2Ty = TheCall->getArg(1)->getType(); 4074 4075 // Check the type of argument 1 and argument 2 are vectors. 4076 SourceLocation BuiltinLoc = TheCall->getLocStart(); 4077 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 4078 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 4079 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 4080 << TheCall->getDirectCallee() 4081 << SourceRange(TheCall->getArg(0)->getLocStart(), 4082 TheCall->getArg(1)->getLocEnd()); 4083 } 4084 4085 // Check the first two arguments are the same type. 4086 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 4087 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 4088 << TheCall->getDirectCallee() 4089 << SourceRange(TheCall->getArg(0)->getLocStart(), 4090 TheCall->getArg(1)->getLocEnd()); 4091 } 4092 4093 // When default clang type checking is turned off and the customized type 4094 // checking is used, the returning type of the function must be explicitly 4095 // set. Otherwise it is _Bool by default. 4096 TheCall->setType(Arg1Ty); 4097 4098 return false; 4099 } 4100 4101 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 4102 // This is declared to take (...), so we have to check everything. 4103 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 4104 if (TheCall->getNumArgs() < 2) 4105 return ExprError(Diag(TheCall->getLocEnd(), 4106 diag::err_typecheck_call_too_few_args_at_least) 4107 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4108 << TheCall->getSourceRange()); 4109 4110 // Determine which of the following types of shufflevector we're checking: 4111 // 1) unary, vector mask: (lhs, mask) 4112 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 4113 QualType resType = TheCall->getArg(0)->getType(); 4114 unsigned numElements = 0; 4115 4116 if (!TheCall->getArg(0)->isTypeDependent() && 4117 !TheCall->getArg(1)->isTypeDependent()) { 4118 QualType LHSType = TheCall->getArg(0)->getType(); 4119 QualType RHSType = TheCall->getArg(1)->getType(); 4120 4121 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 4122 return ExprError(Diag(TheCall->getLocStart(), 4123 diag::err_vec_builtin_non_vector) 4124 << TheCall->getDirectCallee() 4125 << SourceRange(TheCall->getArg(0)->getLocStart(), 4126 TheCall->getArg(1)->getLocEnd())); 4127 4128 numElements = LHSType->getAs<VectorType>()->getNumElements(); 4129 unsigned numResElements = TheCall->getNumArgs() - 2; 4130 4131 // Check to see if we have a call with 2 vector arguments, the unary shuffle 4132 // with mask. If so, verify that RHS is an integer vector type with the 4133 // same number of elts as lhs. 4134 if (TheCall->getNumArgs() == 2) { 4135 if (!RHSType->hasIntegerRepresentation() || 4136 RHSType->getAs<VectorType>()->getNumElements() != numElements) 4137 return ExprError(Diag(TheCall->getLocStart(), 4138 diag::err_vec_builtin_incompatible_vector) 4139 << TheCall->getDirectCallee() 4140 << SourceRange(TheCall->getArg(1)->getLocStart(), 4141 TheCall->getArg(1)->getLocEnd())); 4142 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 4143 return ExprError(Diag(TheCall->getLocStart(), 4144 diag::err_vec_builtin_incompatible_vector) 4145 << TheCall->getDirectCallee() 4146 << SourceRange(TheCall->getArg(0)->getLocStart(), 4147 TheCall->getArg(1)->getLocEnd())); 4148 } else if (numElements != numResElements) { 4149 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 4150 resType = Context.getVectorType(eltType, numResElements, 4151 VectorType::GenericVector); 4152 } 4153 } 4154 4155 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 4156 if (TheCall->getArg(i)->isTypeDependent() || 4157 TheCall->getArg(i)->isValueDependent()) 4158 continue; 4159 4160 llvm::APSInt Result(32); 4161 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 4162 return ExprError(Diag(TheCall->getLocStart(), 4163 diag::err_shufflevector_nonconstant_argument) 4164 << TheCall->getArg(i)->getSourceRange()); 4165 4166 // Allow -1 which will be translated to undef in the IR. 4167 if (Result.isSigned() && Result.isAllOnesValue()) 4168 continue; 4169 4170 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 4171 return ExprError(Diag(TheCall->getLocStart(), 4172 diag::err_shufflevector_argument_too_large) 4173 << TheCall->getArg(i)->getSourceRange()); 4174 } 4175 4176 SmallVector<Expr*, 32> exprs; 4177 4178 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 4179 exprs.push_back(TheCall->getArg(i)); 4180 TheCall->setArg(i, nullptr); 4181 } 4182 4183 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 4184 TheCall->getCallee()->getLocStart(), 4185 TheCall->getRParenLoc()); 4186 } 4187 4188 /// SemaConvertVectorExpr - Handle __builtin_convertvector 4189 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 4190 SourceLocation BuiltinLoc, 4191 SourceLocation RParenLoc) { 4192 ExprValueKind VK = VK_RValue; 4193 ExprObjectKind OK = OK_Ordinary; 4194 QualType DstTy = TInfo->getType(); 4195 QualType SrcTy = E->getType(); 4196 4197 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 4198 return ExprError(Diag(BuiltinLoc, 4199 diag::err_convertvector_non_vector) 4200 << E->getSourceRange()); 4201 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 4202 return ExprError(Diag(BuiltinLoc, 4203 diag::err_convertvector_non_vector_type)); 4204 4205 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 4206 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 4207 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 4208 if (SrcElts != DstElts) 4209 return ExprError(Diag(BuiltinLoc, 4210 diag::err_convertvector_incompatible_vector) 4211 << E->getSourceRange()); 4212 } 4213 4214 return new (Context) 4215 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4216 } 4217 4218 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 4219 // This is declared to take (const void*, ...) and can take two 4220 // optional constant int args. 4221 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 4222 unsigned NumArgs = TheCall->getNumArgs(); 4223 4224 if (NumArgs > 3) 4225 return Diag(TheCall->getLocEnd(), 4226 diag::err_typecheck_call_too_many_args_at_most) 4227 << 0 /*function call*/ << 3 << NumArgs 4228 << TheCall->getSourceRange(); 4229 4230 // Argument 0 is checked for us and the remaining arguments must be 4231 // constant integers. 4232 for (unsigned i = 1; i != NumArgs; ++i) 4233 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 4234 return true; 4235 4236 return false; 4237 } 4238 4239 /// SemaBuiltinAssume - Handle __assume (MS Extension). 4240 // __assume does not evaluate its arguments, and should warn if its argument 4241 // has side effects. 4242 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 4243 Expr *Arg = TheCall->getArg(0); 4244 if (Arg->isInstantiationDependent()) return false; 4245 4246 if (Arg->HasSideEffects(Context)) 4247 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 4248 << Arg->getSourceRange() 4249 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 4250 4251 return false; 4252 } 4253 4254 /// Handle __builtin_alloca_with_align. This is declared 4255 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 4256 /// than 8. 4257 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 4258 // The alignment must be a constant integer. 4259 Expr *Arg = TheCall->getArg(1); 4260 4261 // We can't check the value of a dependent argument. 4262 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4263 if (const auto *UE = 4264 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 4265 if (UE->getKind() == UETT_AlignOf) 4266 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 4267 << Arg->getSourceRange(); 4268 4269 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 4270 4271 if (!Result.isPowerOf2()) 4272 return Diag(TheCall->getLocStart(), 4273 diag::err_alignment_not_power_of_two) 4274 << Arg->getSourceRange(); 4275 4276 if (Result < Context.getCharWidth()) 4277 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 4278 << (unsigned)Context.getCharWidth() 4279 << Arg->getSourceRange(); 4280 4281 if (Result > INT32_MAX) 4282 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 4283 << INT32_MAX 4284 << Arg->getSourceRange(); 4285 } 4286 4287 return false; 4288 } 4289 4290 /// Handle __builtin_assume_aligned. This is declared 4291 /// as (const void*, size_t, ...) and can take one optional constant int arg. 4292 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 4293 unsigned NumArgs = TheCall->getNumArgs(); 4294 4295 if (NumArgs > 3) 4296 return Diag(TheCall->getLocEnd(), 4297 diag::err_typecheck_call_too_many_args_at_most) 4298 << 0 /*function call*/ << 3 << NumArgs 4299 << TheCall->getSourceRange(); 4300 4301 // The alignment must be a constant integer. 4302 Expr *Arg = TheCall->getArg(1); 4303 4304 // We can't check the value of a dependent argument. 4305 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4306 llvm::APSInt Result; 4307 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4308 return true; 4309 4310 if (!Result.isPowerOf2()) 4311 return Diag(TheCall->getLocStart(), 4312 diag::err_alignment_not_power_of_two) 4313 << Arg->getSourceRange(); 4314 } 4315 4316 if (NumArgs > 2) { 4317 ExprResult Arg(TheCall->getArg(2)); 4318 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4319 Context.getSizeType(), false); 4320 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4321 if (Arg.isInvalid()) return true; 4322 TheCall->setArg(2, Arg.get()); 4323 } 4324 4325 return false; 4326 } 4327 4328 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 4329 unsigned BuiltinID = 4330 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 4331 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 4332 4333 unsigned NumArgs = TheCall->getNumArgs(); 4334 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 4335 if (NumArgs < NumRequiredArgs) { 4336 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4337 << 0 /* function call */ << NumRequiredArgs << NumArgs 4338 << TheCall->getSourceRange(); 4339 } 4340 if (NumArgs >= NumRequiredArgs + 0x100) { 4341 return Diag(TheCall->getLocEnd(), 4342 diag::err_typecheck_call_too_many_args_at_most) 4343 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 4344 << TheCall->getSourceRange(); 4345 } 4346 unsigned i = 0; 4347 4348 // For formatting call, check buffer arg. 4349 if (!IsSizeCall) { 4350 ExprResult Arg(TheCall->getArg(i)); 4351 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4352 Context, Context.VoidPtrTy, false); 4353 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4354 if (Arg.isInvalid()) 4355 return true; 4356 TheCall->setArg(i, Arg.get()); 4357 i++; 4358 } 4359 4360 // Check string literal arg. 4361 unsigned FormatIdx = i; 4362 { 4363 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4364 if (Arg.isInvalid()) 4365 return true; 4366 TheCall->setArg(i, Arg.get()); 4367 i++; 4368 } 4369 4370 // Make sure variadic args are scalar. 4371 unsigned FirstDataArg = i; 4372 while (i < NumArgs) { 4373 ExprResult Arg = DefaultVariadicArgumentPromotion( 4374 TheCall->getArg(i), VariadicFunction, nullptr); 4375 if (Arg.isInvalid()) 4376 return true; 4377 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4378 if (ArgSize.getQuantity() >= 0x100) { 4379 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4380 << i << (int)ArgSize.getQuantity() << 0xff 4381 << TheCall->getSourceRange(); 4382 } 4383 TheCall->setArg(i, Arg.get()); 4384 i++; 4385 } 4386 4387 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4388 // call to avoid duplicate diagnostics. 4389 if (!IsSizeCall) { 4390 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4391 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4392 bool Success = CheckFormatArguments( 4393 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4394 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4395 CheckedVarArgs); 4396 if (!Success) 4397 return true; 4398 } 4399 4400 if (IsSizeCall) { 4401 TheCall->setType(Context.getSizeType()); 4402 } else { 4403 TheCall->setType(Context.VoidPtrTy); 4404 } 4405 return false; 4406 } 4407 4408 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4409 /// TheCall is a constant expression. 4410 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4411 llvm::APSInt &Result) { 4412 Expr *Arg = TheCall->getArg(ArgNum); 4413 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4414 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4415 4416 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4417 4418 if (!Arg->isIntegerConstantExpr(Result, Context)) 4419 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 4420 << FDecl->getDeclName() << Arg->getSourceRange(); 4421 4422 return false; 4423 } 4424 4425 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 4426 /// TheCall is a constant expression in the range [Low, High]. 4427 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 4428 int Low, int High) { 4429 llvm::APSInt Result; 4430 4431 // We can't check the value of a dependent argument. 4432 Expr *Arg = TheCall->getArg(ArgNum); 4433 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4434 return false; 4435 4436 // Check constant-ness first. 4437 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4438 return true; 4439 4440 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 4441 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 4442 << Low << High << Arg->getSourceRange(); 4443 4444 return false; 4445 } 4446 4447 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 4448 /// TheCall is a constant expression is a multiple of Num.. 4449 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 4450 unsigned Num) { 4451 llvm::APSInt Result; 4452 4453 // We can't check the value of a dependent argument. 4454 Expr *Arg = TheCall->getArg(ArgNum); 4455 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4456 return false; 4457 4458 // Check constant-ness first. 4459 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4460 return true; 4461 4462 if (Result.getSExtValue() % Num != 0) 4463 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 4464 << Num << Arg->getSourceRange(); 4465 4466 return false; 4467 } 4468 4469 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 4470 /// TheCall is an ARM/AArch64 special register string literal. 4471 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 4472 int ArgNum, unsigned ExpectedFieldNum, 4473 bool AllowName) { 4474 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 4475 BuiltinID == ARM::BI__builtin_arm_wsr64 || 4476 BuiltinID == ARM::BI__builtin_arm_rsr || 4477 BuiltinID == ARM::BI__builtin_arm_rsrp || 4478 BuiltinID == ARM::BI__builtin_arm_wsr || 4479 BuiltinID == ARM::BI__builtin_arm_wsrp; 4480 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 4481 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 4482 BuiltinID == AArch64::BI__builtin_arm_rsr || 4483 BuiltinID == AArch64::BI__builtin_arm_rsrp || 4484 BuiltinID == AArch64::BI__builtin_arm_wsr || 4485 BuiltinID == AArch64::BI__builtin_arm_wsrp; 4486 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 4487 4488 // We can't check the value of a dependent argument. 4489 Expr *Arg = TheCall->getArg(ArgNum); 4490 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4491 return false; 4492 4493 // Check if the argument is a string literal. 4494 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4495 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 4496 << Arg->getSourceRange(); 4497 4498 // Check the type of special register given. 4499 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4500 SmallVector<StringRef, 6> Fields; 4501 Reg.split(Fields, ":"); 4502 4503 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 4504 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4505 << Arg->getSourceRange(); 4506 4507 // If the string is the name of a register then we cannot check that it is 4508 // valid here but if the string is of one the forms described in ACLE then we 4509 // can check that the supplied fields are integers and within the valid 4510 // ranges. 4511 if (Fields.size() > 1) { 4512 bool FiveFields = Fields.size() == 5; 4513 4514 bool ValidString = true; 4515 if (IsARMBuiltin) { 4516 ValidString &= Fields[0].startswith_lower("cp") || 4517 Fields[0].startswith_lower("p"); 4518 if (ValidString) 4519 Fields[0] = 4520 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 4521 4522 ValidString &= Fields[2].startswith_lower("c"); 4523 if (ValidString) 4524 Fields[2] = Fields[2].drop_front(1); 4525 4526 if (FiveFields) { 4527 ValidString &= Fields[3].startswith_lower("c"); 4528 if (ValidString) 4529 Fields[3] = Fields[3].drop_front(1); 4530 } 4531 } 4532 4533 SmallVector<int, 5> Ranges; 4534 if (FiveFields) 4535 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 4536 else 4537 Ranges.append({15, 7, 15}); 4538 4539 for (unsigned i=0; i<Fields.size(); ++i) { 4540 int IntField; 4541 ValidString &= !Fields[i].getAsInteger(10, IntField); 4542 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 4543 } 4544 4545 if (!ValidString) 4546 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4547 << Arg->getSourceRange(); 4548 4549 } else if (IsAArch64Builtin && Fields.size() == 1) { 4550 // If the register name is one of those that appear in the condition below 4551 // and the special register builtin being used is one of the write builtins, 4552 // then we require that the argument provided for writing to the register 4553 // is an integer constant expression. This is because it will be lowered to 4554 // an MSR (immediate) instruction, so we need to know the immediate at 4555 // compile time. 4556 if (TheCall->getNumArgs() != 2) 4557 return false; 4558 4559 std::string RegLower = Reg.lower(); 4560 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 4561 RegLower != "pan" && RegLower != "uao") 4562 return false; 4563 4564 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4565 } 4566 4567 return false; 4568 } 4569 4570 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 4571 /// This checks that the target supports __builtin_longjmp and 4572 /// that val is a constant 1. 4573 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 4574 if (!Context.getTargetInfo().hasSjLjLowering()) 4575 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 4576 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4577 4578 Expr *Arg = TheCall->getArg(1); 4579 llvm::APSInt Result; 4580 4581 // TODO: This is less than ideal. Overload this to take a value. 4582 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4583 return true; 4584 4585 if (Result != 1) 4586 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 4587 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 4588 4589 return false; 4590 } 4591 4592 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 4593 /// This checks that the target supports __builtin_setjmp. 4594 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 4595 if (!Context.getTargetInfo().hasSjLjLowering()) 4596 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 4597 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4598 return false; 4599 } 4600 4601 namespace { 4602 class UncoveredArgHandler { 4603 enum { Unknown = -1, AllCovered = -2 }; 4604 signed FirstUncoveredArg; 4605 SmallVector<const Expr *, 4> DiagnosticExprs; 4606 4607 public: 4608 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { } 4609 4610 bool hasUncoveredArg() const { 4611 return (FirstUncoveredArg >= 0); 4612 } 4613 4614 unsigned getUncoveredArg() const { 4615 assert(hasUncoveredArg() && "no uncovered argument"); 4616 return FirstUncoveredArg; 4617 } 4618 4619 void setAllCovered() { 4620 // A string has been found with all arguments covered, so clear out 4621 // the diagnostics. 4622 DiagnosticExprs.clear(); 4623 FirstUncoveredArg = AllCovered; 4624 } 4625 4626 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 4627 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 4628 4629 // Don't update if a previous string covers all arguments. 4630 if (FirstUncoveredArg == AllCovered) 4631 return; 4632 4633 // UncoveredArgHandler tracks the highest uncovered argument index 4634 // and with it all the strings that match this index. 4635 if (NewFirstUncoveredArg == FirstUncoveredArg) 4636 DiagnosticExprs.push_back(StrExpr); 4637 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 4638 DiagnosticExprs.clear(); 4639 DiagnosticExprs.push_back(StrExpr); 4640 FirstUncoveredArg = NewFirstUncoveredArg; 4641 } 4642 } 4643 4644 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 4645 }; 4646 4647 enum StringLiteralCheckType { 4648 SLCT_NotALiteral, 4649 SLCT_UncheckedLiteral, 4650 SLCT_CheckedLiteral 4651 }; 4652 } // end anonymous namespace 4653 4654 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 4655 BinaryOperatorKind BinOpKind, 4656 bool AddendIsRight) { 4657 unsigned BitWidth = Offset.getBitWidth(); 4658 unsigned AddendBitWidth = Addend.getBitWidth(); 4659 // There might be negative interim results. 4660 if (Addend.isUnsigned()) { 4661 Addend = Addend.zext(++AddendBitWidth); 4662 Addend.setIsSigned(true); 4663 } 4664 // Adjust the bit width of the APSInts. 4665 if (AddendBitWidth > BitWidth) { 4666 Offset = Offset.sext(AddendBitWidth); 4667 BitWidth = AddendBitWidth; 4668 } else if (BitWidth > AddendBitWidth) { 4669 Addend = Addend.sext(BitWidth); 4670 } 4671 4672 bool Ov = false; 4673 llvm::APSInt ResOffset = Offset; 4674 if (BinOpKind == BO_Add) 4675 ResOffset = Offset.sadd_ov(Addend, Ov); 4676 else { 4677 assert(AddendIsRight && BinOpKind == BO_Sub && 4678 "operator must be add or sub with addend on the right"); 4679 ResOffset = Offset.ssub_ov(Addend, Ov); 4680 } 4681 4682 // We add an offset to a pointer here so we should support an offset as big as 4683 // possible. 4684 if (Ov) { 4685 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big"); 4686 Offset = Offset.sext(2 * BitWidth); 4687 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 4688 return; 4689 } 4690 4691 Offset = ResOffset; 4692 } 4693 4694 namespace { 4695 // This is a wrapper class around StringLiteral to support offsetted string 4696 // literals as format strings. It takes the offset into account when returning 4697 // the string and its length or the source locations to display notes correctly. 4698 class FormatStringLiteral { 4699 const StringLiteral *FExpr; 4700 int64_t Offset; 4701 4702 public: 4703 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 4704 : FExpr(fexpr), Offset(Offset) {} 4705 4706 StringRef getString() const { 4707 return FExpr->getString().drop_front(Offset); 4708 } 4709 4710 unsigned getByteLength() const { 4711 return FExpr->getByteLength() - getCharByteWidth() * Offset; 4712 } 4713 unsigned getLength() const { return FExpr->getLength() - Offset; } 4714 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 4715 4716 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 4717 4718 QualType getType() const { return FExpr->getType(); } 4719 4720 bool isAscii() const { return FExpr->isAscii(); } 4721 bool isWide() const { return FExpr->isWide(); } 4722 bool isUTF8() const { return FExpr->isUTF8(); } 4723 bool isUTF16() const { return FExpr->isUTF16(); } 4724 bool isUTF32() const { return FExpr->isUTF32(); } 4725 bool isPascal() const { return FExpr->isPascal(); } 4726 4727 SourceLocation getLocationOfByte( 4728 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 4729 const TargetInfo &Target, unsigned *StartToken = nullptr, 4730 unsigned *StartTokenByteOffset = nullptr) const { 4731 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 4732 StartToken, StartTokenByteOffset); 4733 } 4734 4735 SourceLocation getLocStart() const LLVM_READONLY { 4736 return FExpr->getLocStart().getLocWithOffset(Offset); 4737 } 4738 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 4739 }; 4740 } // end anonymous namespace 4741 4742 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 4743 const Expr *OrigFormatExpr, 4744 ArrayRef<const Expr *> Args, 4745 bool HasVAListArg, unsigned format_idx, 4746 unsigned firstDataArg, 4747 Sema::FormatStringType Type, 4748 bool inFunctionCall, 4749 Sema::VariadicCallType CallType, 4750 llvm::SmallBitVector &CheckedVarArgs, 4751 UncoveredArgHandler &UncoveredArg); 4752 4753 // Determine if an expression is a string literal or constant string. 4754 // If this function returns false on the arguments to a function expecting a 4755 // format string, we will usually need to emit a warning. 4756 // True string literals are then checked by CheckFormatString. 4757 static StringLiteralCheckType 4758 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 4759 bool HasVAListArg, unsigned format_idx, 4760 unsigned firstDataArg, Sema::FormatStringType Type, 4761 Sema::VariadicCallType CallType, bool InFunctionCall, 4762 llvm::SmallBitVector &CheckedVarArgs, 4763 UncoveredArgHandler &UncoveredArg, 4764 llvm::APSInt Offset) { 4765 tryAgain: 4766 assert(Offset.isSigned() && "invalid offset"); 4767 4768 if (E->isTypeDependent() || E->isValueDependent()) 4769 return SLCT_NotALiteral; 4770 4771 E = E->IgnoreParenCasts(); 4772 4773 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 4774 // Technically -Wformat-nonliteral does not warn about this case. 4775 // The behavior of printf and friends in this case is implementation 4776 // dependent. Ideally if the format string cannot be null then 4777 // it should have a 'nonnull' attribute in the function prototype. 4778 return SLCT_UncheckedLiteral; 4779 4780 switch (E->getStmtClass()) { 4781 case Stmt::BinaryConditionalOperatorClass: 4782 case Stmt::ConditionalOperatorClass: { 4783 // The expression is a literal if both sub-expressions were, and it was 4784 // completely checked only if both sub-expressions were checked. 4785 const AbstractConditionalOperator *C = 4786 cast<AbstractConditionalOperator>(E); 4787 4788 // Determine whether it is necessary to check both sub-expressions, for 4789 // example, because the condition expression is a constant that can be 4790 // evaluated at compile time. 4791 bool CheckLeft = true, CheckRight = true; 4792 4793 bool Cond; 4794 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 4795 if (Cond) 4796 CheckRight = false; 4797 else 4798 CheckLeft = false; 4799 } 4800 4801 // We need to maintain the offsets for the right and the left hand side 4802 // separately to check if every possible indexed expression is a valid 4803 // string literal. They might have different offsets for different string 4804 // literals in the end. 4805 StringLiteralCheckType Left; 4806 if (!CheckLeft) 4807 Left = SLCT_UncheckedLiteral; 4808 else { 4809 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 4810 HasVAListArg, format_idx, firstDataArg, 4811 Type, CallType, InFunctionCall, 4812 CheckedVarArgs, UncoveredArg, Offset); 4813 if (Left == SLCT_NotALiteral || !CheckRight) { 4814 return Left; 4815 } 4816 } 4817 4818 StringLiteralCheckType Right = 4819 checkFormatStringExpr(S, C->getFalseExpr(), Args, 4820 HasVAListArg, format_idx, firstDataArg, 4821 Type, CallType, InFunctionCall, CheckedVarArgs, 4822 UncoveredArg, Offset); 4823 4824 return (CheckLeft && Left < Right) ? Left : Right; 4825 } 4826 4827 case Stmt::ImplicitCastExprClass: { 4828 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4829 goto tryAgain; 4830 } 4831 4832 case Stmt::OpaqueValueExprClass: 4833 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 4834 E = src; 4835 goto tryAgain; 4836 } 4837 return SLCT_NotALiteral; 4838 4839 case Stmt::PredefinedExprClass: 4840 // While __func__, etc., are technically not string literals, they 4841 // cannot contain format specifiers and thus are not a security 4842 // liability. 4843 return SLCT_UncheckedLiteral; 4844 4845 case Stmt::DeclRefExprClass: { 4846 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 4847 4848 // As an exception, do not flag errors for variables binding to 4849 // const string literals. 4850 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 4851 bool isConstant = false; 4852 QualType T = DR->getType(); 4853 4854 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 4855 isConstant = AT->getElementType().isConstant(S.Context); 4856 } else if (const PointerType *PT = T->getAs<PointerType>()) { 4857 isConstant = T.isConstant(S.Context) && 4858 PT->getPointeeType().isConstant(S.Context); 4859 } else if (T->isObjCObjectPointerType()) { 4860 // In ObjC, there is usually no "const ObjectPointer" type, 4861 // so don't check if the pointee type is constant. 4862 isConstant = T.isConstant(S.Context); 4863 } 4864 4865 if (isConstant) { 4866 if (const Expr *Init = VD->getAnyInitializer()) { 4867 // Look through initializers like const char c[] = { "foo" } 4868 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4869 if (InitList->isStringLiteralInit()) 4870 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 4871 } 4872 return checkFormatStringExpr(S, Init, Args, 4873 HasVAListArg, format_idx, 4874 firstDataArg, Type, CallType, 4875 /*InFunctionCall*/ false, CheckedVarArgs, 4876 UncoveredArg, Offset); 4877 } 4878 } 4879 4880 // For vprintf* functions (i.e., HasVAListArg==true), we add a 4881 // special check to see if the format string is a function parameter 4882 // of the function calling the printf function. If the function 4883 // has an attribute indicating it is a printf-like function, then we 4884 // should suppress warnings concerning non-literals being used in a call 4885 // to a vprintf function. For example: 4886 // 4887 // void 4888 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 4889 // va_list ap; 4890 // va_start(ap, fmt); 4891 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 4892 // ... 4893 // } 4894 if (HasVAListArg) { 4895 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 4896 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 4897 int PVIndex = PV->getFunctionScopeIndex() + 1; 4898 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 4899 // adjust for implicit parameter 4900 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4901 if (MD->isInstance()) 4902 ++PVIndex; 4903 // We also check if the formats are compatible. 4904 // We can't pass a 'scanf' string to a 'printf' function. 4905 if (PVIndex == PVFormat->getFormatIdx() && 4906 Type == S.GetFormatStringType(PVFormat)) 4907 return SLCT_UncheckedLiteral; 4908 } 4909 } 4910 } 4911 } 4912 } 4913 4914 return SLCT_NotALiteral; 4915 } 4916 4917 case Stmt::CallExprClass: 4918 case Stmt::CXXMemberCallExprClass: { 4919 const CallExpr *CE = cast<CallExpr>(E); 4920 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 4921 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 4922 unsigned ArgIndex = FA->getFormatIdx(); 4923 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4924 if (MD->isInstance()) 4925 --ArgIndex; 4926 const Expr *Arg = CE->getArg(ArgIndex - 1); 4927 4928 return checkFormatStringExpr(S, Arg, Args, 4929 HasVAListArg, format_idx, firstDataArg, 4930 Type, CallType, InFunctionCall, 4931 CheckedVarArgs, UncoveredArg, Offset); 4932 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 4933 unsigned BuiltinID = FD->getBuiltinID(); 4934 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 4935 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 4936 const Expr *Arg = CE->getArg(0); 4937 return checkFormatStringExpr(S, Arg, Args, 4938 HasVAListArg, format_idx, 4939 firstDataArg, Type, CallType, 4940 InFunctionCall, CheckedVarArgs, 4941 UncoveredArg, Offset); 4942 } 4943 } 4944 } 4945 4946 return SLCT_NotALiteral; 4947 } 4948 case Stmt::ObjCMessageExprClass: { 4949 const auto *ME = cast<ObjCMessageExpr>(E); 4950 if (const auto *ND = ME->getMethodDecl()) { 4951 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 4952 unsigned ArgIndex = FA->getFormatIdx(); 4953 const Expr *Arg = ME->getArg(ArgIndex - 1); 4954 return checkFormatStringExpr( 4955 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 4956 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 4957 } 4958 } 4959 4960 return SLCT_NotALiteral; 4961 } 4962 case Stmt::ObjCStringLiteralClass: 4963 case Stmt::StringLiteralClass: { 4964 const StringLiteral *StrE = nullptr; 4965 4966 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 4967 StrE = ObjCFExpr->getString(); 4968 else 4969 StrE = cast<StringLiteral>(E); 4970 4971 if (StrE) { 4972 if (Offset.isNegative() || Offset > StrE->getLength()) { 4973 // TODO: It would be better to have an explicit warning for out of 4974 // bounds literals. 4975 return SLCT_NotALiteral; 4976 } 4977 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 4978 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 4979 firstDataArg, Type, InFunctionCall, CallType, 4980 CheckedVarArgs, UncoveredArg); 4981 return SLCT_CheckedLiteral; 4982 } 4983 4984 return SLCT_NotALiteral; 4985 } 4986 case Stmt::BinaryOperatorClass: { 4987 llvm::APSInt LResult; 4988 llvm::APSInt RResult; 4989 4990 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 4991 4992 // A string literal + an int offset is still a string literal. 4993 if (BinOp->isAdditiveOp()) { 4994 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 4995 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 4996 4997 if (LIsInt != RIsInt) { 4998 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 4999 5000 if (LIsInt) { 5001 if (BinOpKind == BO_Add) { 5002 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 5003 E = BinOp->getRHS(); 5004 goto tryAgain; 5005 } 5006 } else { 5007 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 5008 E = BinOp->getLHS(); 5009 goto tryAgain; 5010 } 5011 } 5012 } 5013 5014 return SLCT_NotALiteral; 5015 } 5016 case Stmt::UnaryOperatorClass: { 5017 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 5018 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 5019 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) { 5020 llvm::APSInt IndexResult; 5021 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 5022 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 5023 E = ASE->getBase(); 5024 goto tryAgain; 5025 } 5026 } 5027 5028 return SLCT_NotALiteral; 5029 } 5030 5031 default: 5032 return SLCT_NotALiteral; 5033 } 5034 } 5035 5036 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 5037 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 5038 .Case("scanf", FST_Scanf) 5039 .Cases("printf", "printf0", FST_Printf) 5040 .Cases("NSString", "CFString", FST_NSString) 5041 .Case("strftime", FST_Strftime) 5042 .Case("strfmon", FST_Strfmon) 5043 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 5044 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 5045 .Case("os_trace", FST_OSLog) 5046 .Case("os_log", FST_OSLog) 5047 .Default(FST_Unknown); 5048 } 5049 5050 /// CheckFormatArguments - Check calls to printf and scanf (and similar 5051 /// functions) for correct use of format strings. 5052 /// Returns true if a format string has been fully checked. 5053 bool Sema::CheckFormatArguments(const FormatAttr *Format, 5054 ArrayRef<const Expr *> Args, 5055 bool IsCXXMember, 5056 VariadicCallType CallType, 5057 SourceLocation Loc, SourceRange Range, 5058 llvm::SmallBitVector &CheckedVarArgs) { 5059 FormatStringInfo FSI; 5060 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 5061 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 5062 FSI.FirstDataArg, GetFormatStringType(Format), 5063 CallType, Loc, Range, CheckedVarArgs); 5064 return false; 5065 } 5066 5067 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 5068 bool HasVAListArg, unsigned format_idx, 5069 unsigned firstDataArg, FormatStringType Type, 5070 VariadicCallType CallType, 5071 SourceLocation Loc, SourceRange Range, 5072 llvm::SmallBitVector &CheckedVarArgs) { 5073 // CHECK: printf/scanf-like function is called with no format string. 5074 if (format_idx >= Args.size()) { 5075 Diag(Loc, diag::warn_missing_format_string) << Range; 5076 return false; 5077 } 5078 5079 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 5080 5081 // CHECK: format string is not a string literal. 5082 // 5083 // Dynamically generated format strings are difficult to 5084 // automatically vet at compile time. Requiring that format strings 5085 // are string literals: (1) permits the checking of format strings by 5086 // the compiler and thereby (2) can practically remove the source of 5087 // many format string exploits. 5088 5089 // Format string can be either ObjC string (e.g. @"%d") or 5090 // C string (e.g. "%d") 5091 // ObjC string uses the same format specifiers as C string, so we can use 5092 // the same format string checking logic for both ObjC and C strings. 5093 UncoveredArgHandler UncoveredArg; 5094 StringLiteralCheckType CT = 5095 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 5096 format_idx, firstDataArg, Type, CallType, 5097 /*IsFunctionCall*/ true, CheckedVarArgs, 5098 UncoveredArg, 5099 /*no string offset*/ llvm::APSInt(64, false) = 0); 5100 5101 // Generate a diagnostic where an uncovered argument is detected. 5102 if (UncoveredArg.hasUncoveredArg()) { 5103 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 5104 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 5105 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 5106 } 5107 5108 if (CT != SLCT_NotALiteral) 5109 // Literal format string found, check done! 5110 return CT == SLCT_CheckedLiteral; 5111 5112 // Strftime is particular as it always uses a single 'time' argument, 5113 // so it is safe to pass a non-literal string. 5114 if (Type == FST_Strftime) 5115 return false; 5116 5117 // Do not emit diag when the string param is a macro expansion and the 5118 // format is either NSString or CFString. This is a hack to prevent 5119 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 5120 // which are usually used in place of NS and CF string literals. 5121 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 5122 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 5123 return false; 5124 5125 // If there are no arguments specified, warn with -Wformat-security, otherwise 5126 // warn only with -Wformat-nonliteral. 5127 if (Args.size() == firstDataArg) { 5128 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 5129 << OrigFormatExpr->getSourceRange(); 5130 switch (Type) { 5131 default: 5132 break; 5133 case FST_Kprintf: 5134 case FST_FreeBSDKPrintf: 5135 case FST_Printf: 5136 Diag(FormatLoc, diag::note_format_security_fixit) 5137 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 5138 break; 5139 case FST_NSString: 5140 Diag(FormatLoc, diag::note_format_security_fixit) 5141 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 5142 break; 5143 } 5144 } else { 5145 Diag(FormatLoc, diag::warn_format_nonliteral) 5146 << OrigFormatExpr->getSourceRange(); 5147 } 5148 return false; 5149 } 5150 5151 namespace { 5152 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 5153 protected: 5154 Sema &S; 5155 const FormatStringLiteral *FExpr; 5156 const Expr *OrigFormatExpr; 5157 const Sema::FormatStringType FSType; 5158 const unsigned FirstDataArg; 5159 const unsigned NumDataArgs; 5160 const char *Beg; // Start of format string. 5161 const bool HasVAListArg; 5162 ArrayRef<const Expr *> Args; 5163 unsigned FormatIdx; 5164 llvm::SmallBitVector CoveredArgs; 5165 bool usesPositionalArgs; 5166 bool atFirstArg; 5167 bool inFunctionCall; 5168 Sema::VariadicCallType CallType; 5169 llvm::SmallBitVector &CheckedVarArgs; 5170 UncoveredArgHandler &UncoveredArg; 5171 5172 public: 5173 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 5174 const Expr *origFormatExpr, 5175 const Sema::FormatStringType type, unsigned firstDataArg, 5176 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5177 ArrayRef<const Expr *> Args, unsigned formatIdx, 5178 bool inFunctionCall, Sema::VariadicCallType callType, 5179 llvm::SmallBitVector &CheckedVarArgs, 5180 UncoveredArgHandler &UncoveredArg) 5181 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 5182 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 5183 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 5184 usesPositionalArgs(false), atFirstArg(true), 5185 inFunctionCall(inFunctionCall), CallType(callType), 5186 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 5187 CoveredArgs.resize(numDataArgs); 5188 CoveredArgs.reset(); 5189 } 5190 5191 void DoneProcessing(); 5192 5193 void HandleIncompleteSpecifier(const char *startSpecifier, 5194 unsigned specifierLen) override; 5195 5196 void HandleInvalidLengthModifier( 5197 const analyze_format_string::FormatSpecifier &FS, 5198 const analyze_format_string::ConversionSpecifier &CS, 5199 const char *startSpecifier, unsigned specifierLen, 5200 unsigned DiagID); 5201 5202 void HandleNonStandardLengthModifier( 5203 const analyze_format_string::FormatSpecifier &FS, 5204 const char *startSpecifier, unsigned specifierLen); 5205 5206 void HandleNonStandardConversionSpecifier( 5207 const analyze_format_string::ConversionSpecifier &CS, 5208 const char *startSpecifier, unsigned specifierLen); 5209 5210 void HandlePosition(const char *startPos, unsigned posLen) override; 5211 5212 void HandleInvalidPosition(const char *startSpecifier, 5213 unsigned specifierLen, 5214 analyze_format_string::PositionContext p) override; 5215 5216 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 5217 5218 void HandleNullChar(const char *nullCharacter) override; 5219 5220 template <typename Range> 5221 static void 5222 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 5223 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 5224 bool IsStringLocation, Range StringRange, 5225 ArrayRef<FixItHint> Fixit = None); 5226 5227 protected: 5228 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 5229 const char *startSpec, 5230 unsigned specifierLen, 5231 const char *csStart, unsigned csLen); 5232 5233 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 5234 const char *startSpec, 5235 unsigned specifierLen); 5236 5237 SourceRange getFormatStringRange(); 5238 CharSourceRange getSpecifierRange(const char *startSpecifier, 5239 unsigned specifierLen); 5240 SourceLocation getLocationOfByte(const char *x); 5241 5242 const Expr *getDataArg(unsigned i) const; 5243 5244 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 5245 const analyze_format_string::ConversionSpecifier &CS, 5246 const char *startSpecifier, unsigned specifierLen, 5247 unsigned argIndex); 5248 5249 template <typename Range> 5250 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5251 bool IsStringLocation, Range StringRange, 5252 ArrayRef<FixItHint> Fixit = None); 5253 }; 5254 } // end anonymous namespace 5255 5256 SourceRange CheckFormatHandler::getFormatStringRange() { 5257 return OrigFormatExpr->getSourceRange(); 5258 } 5259 5260 CharSourceRange CheckFormatHandler:: 5261 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 5262 SourceLocation Start = getLocationOfByte(startSpecifier); 5263 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 5264 5265 // Advance the end SourceLocation by one due to half-open ranges. 5266 End = End.getLocWithOffset(1); 5267 5268 return CharSourceRange::getCharRange(Start, End); 5269 } 5270 5271 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 5272 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 5273 S.getLangOpts(), S.Context.getTargetInfo()); 5274 } 5275 5276 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 5277 unsigned specifierLen){ 5278 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 5279 getLocationOfByte(startSpecifier), 5280 /*IsStringLocation*/true, 5281 getSpecifierRange(startSpecifier, specifierLen)); 5282 } 5283 5284 void CheckFormatHandler::HandleInvalidLengthModifier( 5285 const analyze_format_string::FormatSpecifier &FS, 5286 const analyze_format_string::ConversionSpecifier &CS, 5287 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 5288 using namespace analyze_format_string; 5289 5290 const LengthModifier &LM = FS.getLengthModifier(); 5291 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5292 5293 // See if we know how to fix this length modifier. 5294 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5295 if (FixedLM) { 5296 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5297 getLocationOfByte(LM.getStart()), 5298 /*IsStringLocation*/true, 5299 getSpecifierRange(startSpecifier, specifierLen)); 5300 5301 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5302 << FixedLM->toString() 5303 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5304 5305 } else { 5306 FixItHint Hint; 5307 if (DiagID == diag::warn_format_nonsensical_length) 5308 Hint = FixItHint::CreateRemoval(LMRange); 5309 5310 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5311 getLocationOfByte(LM.getStart()), 5312 /*IsStringLocation*/true, 5313 getSpecifierRange(startSpecifier, specifierLen), 5314 Hint); 5315 } 5316 } 5317 5318 void CheckFormatHandler::HandleNonStandardLengthModifier( 5319 const analyze_format_string::FormatSpecifier &FS, 5320 const char *startSpecifier, unsigned specifierLen) { 5321 using namespace analyze_format_string; 5322 5323 const LengthModifier &LM = FS.getLengthModifier(); 5324 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5325 5326 // See if we know how to fix this length modifier. 5327 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5328 if (FixedLM) { 5329 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5330 << LM.toString() << 0, 5331 getLocationOfByte(LM.getStart()), 5332 /*IsStringLocation*/true, 5333 getSpecifierRange(startSpecifier, specifierLen)); 5334 5335 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5336 << FixedLM->toString() 5337 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5338 5339 } else { 5340 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5341 << LM.toString() << 0, 5342 getLocationOfByte(LM.getStart()), 5343 /*IsStringLocation*/true, 5344 getSpecifierRange(startSpecifier, specifierLen)); 5345 } 5346 } 5347 5348 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5349 const analyze_format_string::ConversionSpecifier &CS, 5350 const char *startSpecifier, unsigned specifierLen) { 5351 using namespace analyze_format_string; 5352 5353 // See if we know how to fix this conversion specifier. 5354 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5355 if (FixedCS) { 5356 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5357 << CS.toString() << /*conversion specifier*/1, 5358 getLocationOfByte(CS.getStart()), 5359 /*IsStringLocation*/true, 5360 getSpecifierRange(startSpecifier, specifierLen)); 5361 5362 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5363 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5364 << FixedCS->toString() 5365 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5366 } else { 5367 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5368 << CS.toString() << /*conversion specifier*/1, 5369 getLocationOfByte(CS.getStart()), 5370 /*IsStringLocation*/true, 5371 getSpecifierRange(startSpecifier, specifierLen)); 5372 } 5373 } 5374 5375 void CheckFormatHandler::HandlePosition(const char *startPos, 5376 unsigned posLen) { 5377 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5378 getLocationOfByte(startPos), 5379 /*IsStringLocation*/true, 5380 getSpecifierRange(startPos, posLen)); 5381 } 5382 5383 void 5384 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5385 analyze_format_string::PositionContext p) { 5386 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5387 << (unsigned) p, 5388 getLocationOfByte(startPos), /*IsStringLocation*/true, 5389 getSpecifierRange(startPos, posLen)); 5390 } 5391 5392 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5393 unsigned posLen) { 5394 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5395 getLocationOfByte(startPos), 5396 /*IsStringLocation*/true, 5397 getSpecifierRange(startPos, posLen)); 5398 } 5399 5400 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5401 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5402 // The presence of a null character is likely an error. 5403 EmitFormatDiagnostic( 5404 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5405 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5406 getFormatStringRange()); 5407 } 5408 } 5409 5410 // Note that this may return NULL if there was an error parsing or building 5411 // one of the argument expressions. 5412 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5413 return Args[FirstDataArg + i]; 5414 } 5415 5416 void CheckFormatHandler::DoneProcessing() { 5417 // Does the number of data arguments exceed the number of 5418 // format conversions in the format string? 5419 if (!HasVAListArg) { 5420 // Find any arguments that weren't covered. 5421 CoveredArgs.flip(); 5422 signed notCoveredArg = CoveredArgs.find_first(); 5423 if (notCoveredArg >= 0) { 5424 assert((unsigned)notCoveredArg < NumDataArgs); 5425 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 5426 } else { 5427 UncoveredArg.setAllCovered(); 5428 } 5429 } 5430 } 5431 5432 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 5433 const Expr *ArgExpr) { 5434 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 5435 "Invalid state"); 5436 5437 if (!ArgExpr) 5438 return; 5439 5440 SourceLocation Loc = ArgExpr->getLocStart(); 5441 5442 if (S.getSourceManager().isInSystemMacro(Loc)) 5443 return; 5444 5445 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 5446 for (auto E : DiagnosticExprs) 5447 PDiag << E->getSourceRange(); 5448 5449 CheckFormatHandler::EmitFormatDiagnostic( 5450 S, IsFunctionCall, DiagnosticExprs[0], 5451 PDiag, Loc, /*IsStringLocation*/false, 5452 DiagnosticExprs[0]->getSourceRange()); 5453 } 5454 5455 bool 5456 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 5457 SourceLocation Loc, 5458 const char *startSpec, 5459 unsigned specifierLen, 5460 const char *csStart, 5461 unsigned csLen) { 5462 bool keepGoing = true; 5463 if (argIndex < NumDataArgs) { 5464 // Consider the argument coverered, even though the specifier doesn't 5465 // make sense. 5466 CoveredArgs.set(argIndex); 5467 } 5468 else { 5469 // If argIndex exceeds the number of data arguments we 5470 // don't issue a warning because that is just a cascade of warnings (and 5471 // they may have intended '%%' anyway). We don't want to continue processing 5472 // the format string after this point, however, as we will like just get 5473 // gibberish when trying to match arguments. 5474 keepGoing = false; 5475 } 5476 5477 StringRef Specifier(csStart, csLen); 5478 5479 // If the specifier in non-printable, it could be the first byte of a UTF-8 5480 // sequence. In that case, print the UTF-8 code point. If not, print the byte 5481 // hex value. 5482 std::string CodePointStr; 5483 if (!llvm::sys::locale::isPrint(*csStart)) { 5484 llvm::UTF32 CodePoint; 5485 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 5486 const llvm::UTF8 *E = 5487 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 5488 llvm::ConversionResult Result = 5489 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 5490 5491 if (Result != llvm::conversionOK) { 5492 unsigned char FirstChar = *csStart; 5493 CodePoint = (llvm::UTF32)FirstChar; 5494 } 5495 5496 llvm::raw_string_ostream OS(CodePointStr); 5497 if (CodePoint < 256) 5498 OS << "\\x" << llvm::format("%02x", CodePoint); 5499 else if (CodePoint <= 0xFFFF) 5500 OS << "\\u" << llvm::format("%04x", CodePoint); 5501 else 5502 OS << "\\U" << llvm::format("%08x", CodePoint); 5503 OS.flush(); 5504 Specifier = CodePointStr; 5505 } 5506 5507 EmitFormatDiagnostic( 5508 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 5509 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 5510 5511 return keepGoing; 5512 } 5513 5514 void 5515 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 5516 const char *startSpec, 5517 unsigned specifierLen) { 5518 EmitFormatDiagnostic( 5519 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 5520 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 5521 } 5522 5523 bool 5524 CheckFormatHandler::CheckNumArgs( 5525 const analyze_format_string::FormatSpecifier &FS, 5526 const analyze_format_string::ConversionSpecifier &CS, 5527 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 5528 5529 if (argIndex >= NumDataArgs) { 5530 PartialDiagnostic PDiag = FS.usesPositionalArg() 5531 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 5532 << (argIndex+1) << NumDataArgs) 5533 : S.PDiag(diag::warn_printf_insufficient_data_args); 5534 EmitFormatDiagnostic( 5535 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 5536 getSpecifierRange(startSpecifier, specifierLen)); 5537 5538 // Since more arguments than conversion tokens are given, by extension 5539 // all arguments are covered, so mark this as so. 5540 UncoveredArg.setAllCovered(); 5541 return false; 5542 } 5543 return true; 5544 } 5545 5546 template<typename Range> 5547 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 5548 SourceLocation Loc, 5549 bool IsStringLocation, 5550 Range StringRange, 5551 ArrayRef<FixItHint> FixIt) { 5552 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 5553 Loc, IsStringLocation, StringRange, FixIt); 5554 } 5555 5556 /// \brief If the format string is not within the funcion call, emit a note 5557 /// so that the function call and string are in diagnostic messages. 5558 /// 5559 /// \param InFunctionCall if true, the format string is within the function 5560 /// call and only one diagnostic message will be produced. Otherwise, an 5561 /// extra note will be emitted pointing to location of the format string. 5562 /// 5563 /// \param ArgumentExpr the expression that is passed as the format string 5564 /// argument in the function call. Used for getting locations when two 5565 /// diagnostics are emitted. 5566 /// 5567 /// \param PDiag the callee should already have provided any strings for the 5568 /// diagnostic message. This function only adds locations and fixits 5569 /// to diagnostics. 5570 /// 5571 /// \param Loc primary location for diagnostic. If two diagnostics are 5572 /// required, one will be at Loc and a new SourceLocation will be created for 5573 /// the other one. 5574 /// 5575 /// \param IsStringLocation if true, Loc points to the format string should be 5576 /// used for the note. Otherwise, Loc points to the argument list and will 5577 /// be used with PDiag. 5578 /// 5579 /// \param StringRange some or all of the string to highlight. This is 5580 /// templated so it can accept either a CharSourceRange or a SourceRange. 5581 /// 5582 /// \param FixIt optional fix it hint for the format string. 5583 template <typename Range> 5584 void CheckFormatHandler::EmitFormatDiagnostic( 5585 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 5586 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 5587 Range StringRange, ArrayRef<FixItHint> FixIt) { 5588 if (InFunctionCall) { 5589 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 5590 D << StringRange; 5591 D << FixIt; 5592 } else { 5593 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 5594 << ArgumentExpr->getSourceRange(); 5595 5596 const Sema::SemaDiagnosticBuilder &Note = 5597 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 5598 diag::note_format_string_defined); 5599 5600 Note << StringRange; 5601 Note << FixIt; 5602 } 5603 } 5604 5605 //===--- CHECK: Printf format string checking ------------------------------===// 5606 5607 namespace { 5608 class CheckPrintfHandler : public CheckFormatHandler { 5609 public: 5610 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 5611 const Expr *origFormatExpr, 5612 const Sema::FormatStringType type, unsigned firstDataArg, 5613 unsigned numDataArgs, bool isObjC, const char *beg, 5614 bool hasVAListArg, ArrayRef<const Expr *> Args, 5615 unsigned formatIdx, bool inFunctionCall, 5616 Sema::VariadicCallType CallType, 5617 llvm::SmallBitVector &CheckedVarArgs, 5618 UncoveredArgHandler &UncoveredArg) 5619 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 5620 numDataArgs, beg, hasVAListArg, Args, formatIdx, 5621 inFunctionCall, CallType, CheckedVarArgs, 5622 UncoveredArg) {} 5623 5624 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 5625 5626 /// Returns true if '%@' specifiers are allowed in the format string. 5627 bool allowsObjCArg() const { 5628 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 5629 FSType == Sema::FST_OSTrace; 5630 } 5631 5632 bool HandleInvalidPrintfConversionSpecifier( 5633 const analyze_printf::PrintfSpecifier &FS, 5634 const char *startSpecifier, 5635 unsigned specifierLen) override; 5636 5637 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 5638 const char *startSpecifier, 5639 unsigned specifierLen) override; 5640 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5641 const char *StartSpecifier, 5642 unsigned SpecifierLen, 5643 const Expr *E); 5644 5645 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 5646 const char *startSpecifier, unsigned specifierLen); 5647 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 5648 const analyze_printf::OptionalAmount &Amt, 5649 unsigned type, 5650 const char *startSpecifier, unsigned specifierLen); 5651 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5652 const analyze_printf::OptionalFlag &flag, 5653 const char *startSpecifier, unsigned specifierLen); 5654 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 5655 const analyze_printf::OptionalFlag &ignoredFlag, 5656 const analyze_printf::OptionalFlag &flag, 5657 const char *startSpecifier, unsigned specifierLen); 5658 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 5659 const Expr *E); 5660 5661 void HandleEmptyObjCModifierFlag(const char *startFlag, 5662 unsigned flagLen) override; 5663 5664 void HandleInvalidObjCModifierFlag(const char *startFlag, 5665 unsigned flagLen) override; 5666 5667 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 5668 const char *flagsEnd, 5669 const char *conversionPosition) 5670 override; 5671 }; 5672 } // end anonymous namespace 5673 5674 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 5675 const analyze_printf::PrintfSpecifier &FS, 5676 const char *startSpecifier, 5677 unsigned specifierLen) { 5678 const analyze_printf::PrintfConversionSpecifier &CS = 5679 FS.getConversionSpecifier(); 5680 5681 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5682 getLocationOfByte(CS.getStart()), 5683 startSpecifier, specifierLen, 5684 CS.getStart(), CS.getLength()); 5685 } 5686 5687 bool CheckPrintfHandler::HandleAmount( 5688 const analyze_format_string::OptionalAmount &Amt, 5689 unsigned k, const char *startSpecifier, 5690 unsigned specifierLen) { 5691 if (Amt.hasDataArgument()) { 5692 if (!HasVAListArg) { 5693 unsigned argIndex = Amt.getArgIndex(); 5694 if (argIndex >= NumDataArgs) { 5695 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 5696 << k, 5697 getLocationOfByte(Amt.getStart()), 5698 /*IsStringLocation*/true, 5699 getSpecifierRange(startSpecifier, specifierLen)); 5700 // Don't do any more checking. We will just emit 5701 // spurious errors. 5702 return false; 5703 } 5704 5705 // Type check the data argument. It should be an 'int'. 5706 // Although not in conformance with C99, we also allow the argument to be 5707 // an 'unsigned int' as that is a reasonably safe case. GCC also 5708 // doesn't emit a warning for that case. 5709 CoveredArgs.set(argIndex); 5710 const Expr *Arg = getDataArg(argIndex); 5711 if (!Arg) 5712 return false; 5713 5714 QualType T = Arg->getType(); 5715 5716 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 5717 assert(AT.isValid()); 5718 5719 if (!AT.matchesType(S.Context, T)) { 5720 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 5721 << k << AT.getRepresentativeTypeName(S.Context) 5722 << T << Arg->getSourceRange(), 5723 getLocationOfByte(Amt.getStart()), 5724 /*IsStringLocation*/true, 5725 getSpecifierRange(startSpecifier, specifierLen)); 5726 // Don't do any more checking. We will just emit 5727 // spurious errors. 5728 return false; 5729 } 5730 } 5731 } 5732 return true; 5733 } 5734 5735 void CheckPrintfHandler::HandleInvalidAmount( 5736 const analyze_printf::PrintfSpecifier &FS, 5737 const analyze_printf::OptionalAmount &Amt, 5738 unsigned type, 5739 const char *startSpecifier, 5740 unsigned specifierLen) { 5741 const analyze_printf::PrintfConversionSpecifier &CS = 5742 FS.getConversionSpecifier(); 5743 5744 FixItHint fixit = 5745 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 5746 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 5747 Amt.getConstantLength())) 5748 : FixItHint(); 5749 5750 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 5751 << type << CS.toString(), 5752 getLocationOfByte(Amt.getStart()), 5753 /*IsStringLocation*/true, 5754 getSpecifierRange(startSpecifier, specifierLen), 5755 fixit); 5756 } 5757 5758 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5759 const analyze_printf::OptionalFlag &flag, 5760 const char *startSpecifier, 5761 unsigned specifierLen) { 5762 // Warn about pointless flag with a fixit removal. 5763 const analyze_printf::PrintfConversionSpecifier &CS = 5764 FS.getConversionSpecifier(); 5765 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 5766 << flag.toString() << CS.toString(), 5767 getLocationOfByte(flag.getPosition()), 5768 /*IsStringLocation*/true, 5769 getSpecifierRange(startSpecifier, specifierLen), 5770 FixItHint::CreateRemoval( 5771 getSpecifierRange(flag.getPosition(), 1))); 5772 } 5773 5774 void CheckPrintfHandler::HandleIgnoredFlag( 5775 const analyze_printf::PrintfSpecifier &FS, 5776 const analyze_printf::OptionalFlag &ignoredFlag, 5777 const analyze_printf::OptionalFlag &flag, 5778 const char *startSpecifier, 5779 unsigned specifierLen) { 5780 // Warn about ignored flag with a fixit removal. 5781 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 5782 << ignoredFlag.toString() << flag.toString(), 5783 getLocationOfByte(ignoredFlag.getPosition()), 5784 /*IsStringLocation*/true, 5785 getSpecifierRange(startSpecifier, specifierLen), 5786 FixItHint::CreateRemoval( 5787 getSpecifierRange(ignoredFlag.getPosition(), 1))); 5788 } 5789 5790 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5791 // bool IsStringLocation, Range StringRange, 5792 // ArrayRef<FixItHint> Fixit = None); 5793 5794 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 5795 unsigned flagLen) { 5796 // Warn about an empty flag. 5797 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 5798 getLocationOfByte(startFlag), 5799 /*IsStringLocation*/true, 5800 getSpecifierRange(startFlag, flagLen)); 5801 } 5802 5803 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 5804 unsigned flagLen) { 5805 // Warn about an invalid flag. 5806 auto Range = getSpecifierRange(startFlag, flagLen); 5807 StringRef flag(startFlag, flagLen); 5808 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 5809 getLocationOfByte(startFlag), 5810 /*IsStringLocation*/true, 5811 Range, FixItHint::CreateRemoval(Range)); 5812 } 5813 5814 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 5815 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 5816 // Warn about using '[...]' without a '@' conversion. 5817 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 5818 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 5819 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 5820 getLocationOfByte(conversionPosition), 5821 /*IsStringLocation*/true, 5822 Range, FixItHint::CreateRemoval(Range)); 5823 } 5824 5825 // Determines if the specified is a C++ class or struct containing 5826 // a member with the specified name and kind (e.g. a CXXMethodDecl named 5827 // "c_str()"). 5828 template<typename MemberKind> 5829 static llvm::SmallPtrSet<MemberKind*, 1> 5830 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 5831 const RecordType *RT = Ty->getAs<RecordType>(); 5832 llvm::SmallPtrSet<MemberKind*, 1> Results; 5833 5834 if (!RT) 5835 return Results; 5836 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 5837 if (!RD || !RD->getDefinition()) 5838 return Results; 5839 5840 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 5841 Sema::LookupMemberName); 5842 R.suppressDiagnostics(); 5843 5844 // We just need to include all members of the right kind turned up by the 5845 // filter, at this point. 5846 if (S.LookupQualifiedName(R, RT->getDecl())) 5847 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 5848 NamedDecl *decl = (*I)->getUnderlyingDecl(); 5849 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 5850 Results.insert(FK); 5851 } 5852 return Results; 5853 } 5854 5855 /// Check if we could call '.c_str()' on an object. 5856 /// 5857 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 5858 /// allow the call, or if it would be ambiguous). 5859 bool Sema::hasCStrMethod(const Expr *E) { 5860 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5861 MethodSet Results = 5862 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 5863 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5864 MI != ME; ++MI) 5865 if ((*MI)->getMinRequiredArguments() == 0) 5866 return true; 5867 return false; 5868 } 5869 5870 // Check if a (w)string was passed when a (w)char* was needed, and offer a 5871 // better diagnostic if so. AT is assumed to be valid. 5872 // Returns true when a c_str() conversion method is found. 5873 bool CheckPrintfHandler::checkForCStrMembers( 5874 const analyze_printf::ArgType &AT, const Expr *E) { 5875 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5876 5877 MethodSet Results = 5878 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 5879 5880 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5881 MI != ME; ++MI) { 5882 const CXXMethodDecl *Method = *MI; 5883 if (Method->getMinRequiredArguments() == 0 && 5884 AT.matchesType(S.Context, Method->getReturnType())) { 5885 // FIXME: Suggest parens if the expression needs them. 5886 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 5887 S.Diag(E->getLocStart(), diag::note_printf_c_str) 5888 << "c_str()" 5889 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 5890 return true; 5891 } 5892 } 5893 5894 return false; 5895 } 5896 5897 bool 5898 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 5899 &FS, 5900 const char *startSpecifier, 5901 unsigned specifierLen) { 5902 using namespace analyze_format_string; 5903 using namespace analyze_printf; 5904 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 5905 5906 if (FS.consumesDataArgument()) { 5907 if (atFirstArg) { 5908 atFirstArg = false; 5909 usesPositionalArgs = FS.usesPositionalArg(); 5910 } 5911 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5912 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5913 startSpecifier, specifierLen); 5914 return false; 5915 } 5916 } 5917 5918 // First check if the field width, precision, and conversion specifier 5919 // have matching data arguments. 5920 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 5921 startSpecifier, specifierLen)) { 5922 return false; 5923 } 5924 5925 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 5926 startSpecifier, specifierLen)) { 5927 return false; 5928 } 5929 5930 if (!CS.consumesDataArgument()) { 5931 // FIXME: Technically specifying a precision or field width here 5932 // makes no sense. Worth issuing a warning at some point. 5933 return true; 5934 } 5935 5936 // Consume the argument. 5937 unsigned argIndex = FS.getArgIndex(); 5938 if (argIndex < NumDataArgs) { 5939 // The check to see if the argIndex is valid will come later. 5940 // We set the bit here because we may exit early from this 5941 // function if we encounter some other error. 5942 CoveredArgs.set(argIndex); 5943 } 5944 5945 // FreeBSD kernel extensions. 5946 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 5947 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 5948 // We need at least two arguments. 5949 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 5950 return false; 5951 5952 // Claim the second argument. 5953 CoveredArgs.set(argIndex + 1); 5954 5955 // Type check the first argument (int for %b, pointer for %D) 5956 const Expr *Ex = getDataArg(argIndex); 5957 const analyze_printf::ArgType &AT = 5958 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 5959 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 5960 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 5961 EmitFormatDiagnostic( 5962 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5963 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 5964 << false << Ex->getSourceRange(), 5965 Ex->getLocStart(), /*IsStringLocation*/false, 5966 getSpecifierRange(startSpecifier, specifierLen)); 5967 5968 // Type check the second argument (char * for both %b and %D) 5969 Ex = getDataArg(argIndex + 1); 5970 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 5971 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 5972 EmitFormatDiagnostic( 5973 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5974 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 5975 << false << Ex->getSourceRange(), 5976 Ex->getLocStart(), /*IsStringLocation*/false, 5977 getSpecifierRange(startSpecifier, specifierLen)); 5978 5979 return true; 5980 } 5981 5982 // Check for using an Objective-C specific conversion specifier 5983 // in a non-ObjC literal. 5984 if (!allowsObjCArg() && CS.isObjCArg()) { 5985 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5986 specifierLen); 5987 } 5988 5989 // %P can only be used with os_log. 5990 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 5991 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5992 specifierLen); 5993 } 5994 5995 // %n is not allowed with os_log. 5996 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 5997 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 5998 getLocationOfByte(CS.getStart()), 5999 /*IsStringLocation*/ false, 6000 getSpecifierRange(startSpecifier, specifierLen)); 6001 6002 return true; 6003 } 6004 6005 // Only scalars are allowed for os_trace. 6006 if (FSType == Sema::FST_OSTrace && 6007 (CS.getKind() == ConversionSpecifier::PArg || 6008 CS.getKind() == ConversionSpecifier::sArg || 6009 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 6010 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6011 specifierLen); 6012 } 6013 6014 // Check for use of public/private annotation outside of os_log(). 6015 if (FSType != Sema::FST_OSLog) { 6016 if (FS.isPublic().isSet()) { 6017 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6018 << "public", 6019 getLocationOfByte(FS.isPublic().getPosition()), 6020 /*IsStringLocation*/ false, 6021 getSpecifierRange(startSpecifier, specifierLen)); 6022 } 6023 if (FS.isPrivate().isSet()) { 6024 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6025 << "private", 6026 getLocationOfByte(FS.isPrivate().getPosition()), 6027 /*IsStringLocation*/ false, 6028 getSpecifierRange(startSpecifier, specifierLen)); 6029 } 6030 } 6031 6032 // Check for invalid use of field width 6033 if (!FS.hasValidFieldWidth()) { 6034 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 6035 startSpecifier, specifierLen); 6036 } 6037 6038 // Check for invalid use of precision 6039 if (!FS.hasValidPrecision()) { 6040 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 6041 startSpecifier, specifierLen); 6042 } 6043 6044 // Precision is mandatory for %P specifier. 6045 if (CS.getKind() == ConversionSpecifier::PArg && 6046 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 6047 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 6048 getLocationOfByte(startSpecifier), 6049 /*IsStringLocation*/ false, 6050 getSpecifierRange(startSpecifier, specifierLen)); 6051 } 6052 6053 // Check each flag does not conflict with any other component. 6054 if (!FS.hasValidThousandsGroupingPrefix()) 6055 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 6056 if (!FS.hasValidLeadingZeros()) 6057 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 6058 if (!FS.hasValidPlusPrefix()) 6059 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 6060 if (!FS.hasValidSpacePrefix()) 6061 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 6062 if (!FS.hasValidAlternativeForm()) 6063 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 6064 if (!FS.hasValidLeftJustified()) 6065 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 6066 6067 // Check that flags are not ignored by another flag 6068 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 6069 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 6070 startSpecifier, specifierLen); 6071 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 6072 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 6073 startSpecifier, specifierLen); 6074 6075 // Check the length modifier is valid with the given conversion specifier. 6076 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6077 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6078 diag::warn_format_nonsensical_length); 6079 else if (!FS.hasStandardLengthModifier()) 6080 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6081 else if (!FS.hasStandardLengthConversionCombination()) 6082 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6083 diag::warn_format_non_standard_conversion_spec); 6084 6085 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6086 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6087 6088 // The remaining checks depend on the data arguments. 6089 if (HasVAListArg) 6090 return true; 6091 6092 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6093 return false; 6094 6095 const Expr *Arg = getDataArg(argIndex); 6096 if (!Arg) 6097 return true; 6098 6099 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 6100 } 6101 6102 static bool requiresParensToAddCast(const Expr *E) { 6103 // FIXME: We should have a general way to reason about operator 6104 // precedence and whether parens are actually needed here. 6105 // Take care of a few common cases where they aren't. 6106 const Expr *Inside = E->IgnoreImpCasts(); 6107 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 6108 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 6109 6110 switch (Inside->getStmtClass()) { 6111 case Stmt::ArraySubscriptExprClass: 6112 case Stmt::CallExprClass: 6113 case Stmt::CharacterLiteralClass: 6114 case Stmt::CXXBoolLiteralExprClass: 6115 case Stmt::DeclRefExprClass: 6116 case Stmt::FloatingLiteralClass: 6117 case Stmt::IntegerLiteralClass: 6118 case Stmt::MemberExprClass: 6119 case Stmt::ObjCArrayLiteralClass: 6120 case Stmt::ObjCBoolLiteralExprClass: 6121 case Stmt::ObjCBoxedExprClass: 6122 case Stmt::ObjCDictionaryLiteralClass: 6123 case Stmt::ObjCEncodeExprClass: 6124 case Stmt::ObjCIvarRefExprClass: 6125 case Stmt::ObjCMessageExprClass: 6126 case Stmt::ObjCPropertyRefExprClass: 6127 case Stmt::ObjCStringLiteralClass: 6128 case Stmt::ObjCSubscriptRefExprClass: 6129 case Stmt::ParenExprClass: 6130 case Stmt::StringLiteralClass: 6131 case Stmt::UnaryOperatorClass: 6132 return false; 6133 default: 6134 return true; 6135 } 6136 } 6137 6138 static std::pair<QualType, StringRef> 6139 shouldNotPrintDirectly(const ASTContext &Context, 6140 QualType IntendedTy, 6141 const Expr *E) { 6142 // Use a 'while' to peel off layers of typedefs. 6143 QualType TyTy = IntendedTy; 6144 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 6145 StringRef Name = UserTy->getDecl()->getName(); 6146 QualType CastTy = llvm::StringSwitch<QualType>(Name) 6147 .Case("CFIndex", Context.LongTy) 6148 .Case("NSInteger", Context.LongTy) 6149 .Case("NSUInteger", Context.UnsignedLongTy) 6150 .Case("SInt32", Context.IntTy) 6151 .Case("UInt32", Context.UnsignedIntTy) 6152 .Default(QualType()); 6153 6154 if (!CastTy.isNull()) 6155 return std::make_pair(CastTy, Name); 6156 6157 TyTy = UserTy->desugar(); 6158 } 6159 6160 // Strip parens if necessary. 6161 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 6162 return shouldNotPrintDirectly(Context, 6163 PE->getSubExpr()->getType(), 6164 PE->getSubExpr()); 6165 6166 // If this is a conditional expression, then its result type is constructed 6167 // via usual arithmetic conversions and thus there might be no necessary 6168 // typedef sugar there. Recurse to operands to check for NSInteger & 6169 // Co. usage condition. 6170 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6171 QualType TrueTy, FalseTy; 6172 StringRef TrueName, FalseName; 6173 6174 std::tie(TrueTy, TrueName) = 6175 shouldNotPrintDirectly(Context, 6176 CO->getTrueExpr()->getType(), 6177 CO->getTrueExpr()); 6178 std::tie(FalseTy, FalseName) = 6179 shouldNotPrintDirectly(Context, 6180 CO->getFalseExpr()->getType(), 6181 CO->getFalseExpr()); 6182 6183 if (TrueTy == FalseTy) 6184 return std::make_pair(TrueTy, TrueName); 6185 else if (TrueTy.isNull()) 6186 return std::make_pair(FalseTy, FalseName); 6187 else if (FalseTy.isNull()) 6188 return std::make_pair(TrueTy, TrueName); 6189 } 6190 6191 return std::make_pair(QualType(), StringRef()); 6192 } 6193 6194 bool 6195 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6196 const char *StartSpecifier, 6197 unsigned SpecifierLen, 6198 const Expr *E) { 6199 using namespace analyze_format_string; 6200 using namespace analyze_printf; 6201 // Now type check the data expression that matches the 6202 // format specifier. 6203 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 6204 if (!AT.isValid()) 6205 return true; 6206 6207 QualType ExprTy = E->getType(); 6208 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 6209 ExprTy = TET->getUnderlyingExpr()->getType(); 6210 } 6211 6212 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 6213 6214 if (match == analyze_printf::ArgType::Match) { 6215 return true; 6216 } 6217 6218 // Look through argument promotions for our error message's reported type. 6219 // This includes the integral and floating promotions, but excludes array 6220 // and function pointer decay; seeing that an argument intended to be a 6221 // string has type 'char [6]' is probably more confusing than 'char *'. 6222 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6223 if (ICE->getCastKind() == CK_IntegralCast || 6224 ICE->getCastKind() == CK_FloatingCast) { 6225 E = ICE->getSubExpr(); 6226 ExprTy = E->getType(); 6227 6228 // Check if we didn't match because of an implicit cast from a 'char' 6229 // or 'short' to an 'int'. This is done because printf is a varargs 6230 // function. 6231 if (ICE->getType() == S.Context.IntTy || 6232 ICE->getType() == S.Context.UnsignedIntTy) { 6233 // All further checking is done on the subexpression. 6234 if (AT.matchesType(S.Context, ExprTy)) 6235 return true; 6236 } 6237 } 6238 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 6239 // Special case for 'a', which has type 'int' in C. 6240 // Note, however, that we do /not/ want to treat multibyte constants like 6241 // 'MooV' as characters! This form is deprecated but still exists. 6242 if (ExprTy == S.Context.IntTy) 6243 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 6244 ExprTy = S.Context.CharTy; 6245 } 6246 6247 // Look through enums to their underlying type. 6248 bool IsEnum = false; 6249 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 6250 ExprTy = EnumTy->getDecl()->getIntegerType(); 6251 IsEnum = true; 6252 } 6253 6254 // %C in an Objective-C context prints a unichar, not a wchar_t. 6255 // If the argument is an integer of some kind, believe the %C and suggest 6256 // a cast instead of changing the conversion specifier. 6257 QualType IntendedTy = ExprTy; 6258 if (isObjCContext() && 6259 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 6260 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 6261 !ExprTy->isCharType()) { 6262 // 'unichar' is defined as a typedef of unsigned short, but we should 6263 // prefer using the typedef if it is visible. 6264 IntendedTy = S.Context.UnsignedShortTy; 6265 6266 // While we are here, check if the value is an IntegerLiteral that happens 6267 // to be within the valid range. 6268 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 6269 const llvm::APInt &V = IL->getValue(); 6270 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 6271 return true; 6272 } 6273 6274 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 6275 Sema::LookupOrdinaryName); 6276 if (S.LookupName(Result, S.getCurScope())) { 6277 NamedDecl *ND = Result.getFoundDecl(); 6278 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 6279 if (TD->getUnderlyingType() == IntendedTy) 6280 IntendedTy = S.Context.getTypedefType(TD); 6281 } 6282 } 6283 } 6284 6285 // Special-case some of Darwin's platform-independence types by suggesting 6286 // casts to primitive types that are known to be large enough. 6287 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 6288 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 6289 QualType CastTy; 6290 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 6291 if (!CastTy.isNull()) { 6292 IntendedTy = CastTy; 6293 ShouldNotPrintDirectly = true; 6294 } 6295 } 6296 6297 // We may be able to offer a FixItHint if it is a supported type. 6298 PrintfSpecifier fixedFS = FS; 6299 bool success = 6300 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 6301 6302 if (success) { 6303 // Get the fix string from the fixed format specifier 6304 SmallString<16> buf; 6305 llvm::raw_svector_ostream os(buf); 6306 fixedFS.toString(os); 6307 6308 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 6309 6310 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 6311 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6312 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6313 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6314 } 6315 // In this case, the specifier is wrong and should be changed to match 6316 // the argument. 6317 EmitFormatDiagnostic(S.PDiag(diag) 6318 << AT.getRepresentativeTypeName(S.Context) 6319 << IntendedTy << IsEnum << E->getSourceRange(), 6320 E->getLocStart(), 6321 /*IsStringLocation*/ false, SpecRange, 6322 FixItHint::CreateReplacement(SpecRange, os.str())); 6323 } else { 6324 // The canonical type for formatting this value is different from the 6325 // actual type of the expression. (This occurs, for example, with Darwin's 6326 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 6327 // should be printed as 'long' for 64-bit compatibility.) 6328 // Rather than emitting a normal format/argument mismatch, we want to 6329 // add a cast to the recommended type (and correct the format string 6330 // if necessary). 6331 SmallString<16> CastBuf; 6332 llvm::raw_svector_ostream CastFix(CastBuf); 6333 CastFix << "("; 6334 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 6335 CastFix << ")"; 6336 6337 SmallVector<FixItHint,4> Hints; 6338 if (!AT.matchesType(S.Context, IntendedTy)) 6339 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 6340 6341 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 6342 // If there's already a cast present, just replace it. 6343 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 6344 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 6345 6346 } else if (!requiresParensToAddCast(E)) { 6347 // If the expression has high enough precedence, 6348 // just write the C-style cast. 6349 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6350 CastFix.str())); 6351 } else { 6352 // Otherwise, add parens around the expression as well as the cast. 6353 CastFix << "("; 6354 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6355 CastFix.str())); 6356 6357 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6358 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6359 } 6360 6361 if (ShouldNotPrintDirectly) { 6362 // The expression has a type that should not be printed directly. 6363 // We extract the name from the typedef because we don't want to show 6364 // the underlying type in the diagnostic. 6365 StringRef Name; 6366 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6367 Name = TypedefTy->getDecl()->getName(); 6368 else 6369 Name = CastTyName; 6370 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6371 << Name << IntendedTy << IsEnum 6372 << E->getSourceRange(), 6373 E->getLocStart(), /*IsStringLocation=*/false, 6374 SpecRange, Hints); 6375 } else { 6376 // In this case, the expression could be printed using a different 6377 // specifier, but we've decided that the specifier is probably correct 6378 // and we should cast instead. Just use the normal warning message. 6379 EmitFormatDiagnostic( 6380 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6381 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6382 << E->getSourceRange(), 6383 E->getLocStart(), /*IsStringLocation*/false, 6384 SpecRange, Hints); 6385 } 6386 } 6387 } else { 6388 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6389 SpecifierLen); 6390 // Since the warning for passing non-POD types to variadic functions 6391 // was deferred until now, we emit a warning for non-POD 6392 // arguments here. 6393 switch (S.isValidVarArgType(ExprTy)) { 6394 case Sema::VAK_Valid: 6395 case Sema::VAK_ValidInCXX11: { 6396 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6397 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6398 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6399 } 6400 6401 EmitFormatDiagnostic( 6402 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6403 << IsEnum << CSR << E->getSourceRange(), 6404 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6405 break; 6406 } 6407 case Sema::VAK_Undefined: 6408 case Sema::VAK_MSVCUndefined: 6409 EmitFormatDiagnostic( 6410 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6411 << S.getLangOpts().CPlusPlus11 6412 << ExprTy 6413 << CallType 6414 << AT.getRepresentativeTypeName(S.Context) 6415 << CSR 6416 << E->getSourceRange(), 6417 E->getLocStart(), /*IsStringLocation*/false, CSR); 6418 checkForCStrMembers(AT, E); 6419 break; 6420 6421 case Sema::VAK_Invalid: 6422 if (ExprTy->isObjCObjectType()) 6423 EmitFormatDiagnostic( 6424 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 6425 << S.getLangOpts().CPlusPlus11 6426 << ExprTy 6427 << CallType 6428 << AT.getRepresentativeTypeName(S.Context) 6429 << CSR 6430 << E->getSourceRange(), 6431 E->getLocStart(), /*IsStringLocation*/false, CSR); 6432 else 6433 // FIXME: If this is an initializer list, suggest removing the braces 6434 // or inserting a cast to the target type. 6435 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 6436 << isa<InitListExpr>(E) << ExprTy << CallType 6437 << AT.getRepresentativeTypeName(S.Context) 6438 << E->getSourceRange(); 6439 break; 6440 } 6441 6442 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 6443 "format string specifier index out of range"); 6444 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 6445 } 6446 6447 return true; 6448 } 6449 6450 //===--- CHECK: Scanf format string checking ------------------------------===// 6451 6452 namespace { 6453 class CheckScanfHandler : public CheckFormatHandler { 6454 public: 6455 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 6456 const Expr *origFormatExpr, Sema::FormatStringType type, 6457 unsigned firstDataArg, unsigned numDataArgs, 6458 const char *beg, bool hasVAListArg, 6459 ArrayRef<const Expr *> Args, unsigned formatIdx, 6460 bool inFunctionCall, Sema::VariadicCallType CallType, 6461 llvm::SmallBitVector &CheckedVarArgs, 6462 UncoveredArgHandler &UncoveredArg) 6463 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6464 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6465 inFunctionCall, CallType, CheckedVarArgs, 6466 UncoveredArg) {} 6467 6468 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 6469 const char *startSpecifier, 6470 unsigned specifierLen) override; 6471 6472 bool HandleInvalidScanfConversionSpecifier( 6473 const analyze_scanf::ScanfSpecifier &FS, 6474 const char *startSpecifier, 6475 unsigned specifierLen) override; 6476 6477 void HandleIncompleteScanList(const char *start, const char *end) override; 6478 }; 6479 } // end anonymous namespace 6480 6481 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 6482 const char *end) { 6483 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 6484 getLocationOfByte(end), /*IsStringLocation*/true, 6485 getSpecifierRange(start, end - start)); 6486 } 6487 6488 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 6489 const analyze_scanf::ScanfSpecifier &FS, 6490 const char *startSpecifier, 6491 unsigned specifierLen) { 6492 6493 const analyze_scanf::ScanfConversionSpecifier &CS = 6494 FS.getConversionSpecifier(); 6495 6496 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6497 getLocationOfByte(CS.getStart()), 6498 startSpecifier, specifierLen, 6499 CS.getStart(), CS.getLength()); 6500 } 6501 6502 bool CheckScanfHandler::HandleScanfSpecifier( 6503 const analyze_scanf::ScanfSpecifier &FS, 6504 const char *startSpecifier, 6505 unsigned specifierLen) { 6506 using namespace analyze_scanf; 6507 using namespace analyze_format_string; 6508 6509 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 6510 6511 // Handle case where '%' and '*' don't consume an argument. These shouldn't 6512 // be used to decide if we are using positional arguments consistently. 6513 if (FS.consumesDataArgument()) { 6514 if (atFirstArg) { 6515 atFirstArg = false; 6516 usesPositionalArgs = FS.usesPositionalArg(); 6517 } 6518 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6519 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6520 startSpecifier, specifierLen); 6521 return false; 6522 } 6523 } 6524 6525 // Check if the field with is non-zero. 6526 const OptionalAmount &Amt = FS.getFieldWidth(); 6527 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 6528 if (Amt.getConstantAmount() == 0) { 6529 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 6530 Amt.getConstantLength()); 6531 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 6532 getLocationOfByte(Amt.getStart()), 6533 /*IsStringLocation*/true, R, 6534 FixItHint::CreateRemoval(R)); 6535 } 6536 } 6537 6538 if (!FS.consumesDataArgument()) { 6539 // FIXME: Technically specifying a precision or field width here 6540 // makes no sense. Worth issuing a warning at some point. 6541 return true; 6542 } 6543 6544 // Consume the argument. 6545 unsigned argIndex = FS.getArgIndex(); 6546 if (argIndex < NumDataArgs) { 6547 // The check to see if the argIndex is valid will come later. 6548 // We set the bit here because we may exit early from this 6549 // function if we encounter some other error. 6550 CoveredArgs.set(argIndex); 6551 } 6552 6553 // Check the length modifier is valid with the given conversion specifier. 6554 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6555 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6556 diag::warn_format_nonsensical_length); 6557 else if (!FS.hasStandardLengthModifier()) 6558 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6559 else if (!FS.hasStandardLengthConversionCombination()) 6560 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6561 diag::warn_format_non_standard_conversion_spec); 6562 6563 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6564 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6565 6566 // The remaining checks depend on the data arguments. 6567 if (HasVAListArg) 6568 return true; 6569 6570 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6571 return false; 6572 6573 // Check that the argument type matches the format specifier. 6574 const Expr *Ex = getDataArg(argIndex); 6575 if (!Ex) 6576 return true; 6577 6578 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 6579 6580 if (!AT.isValid()) { 6581 return true; 6582 } 6583 6584 analyze_format_string::ArgType::MatchKind match = 6585 AT.matchesType(S.Context, Ex->getType()); 6586 if (match == analyze_format_string::ArgType::Match) { 6587 return true; 6588 } 6589 6590 ScanfSpecifier fixedFS = FS; 6591 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 6592 S.getLangOpts(), S.Context); 6593 6594 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6595 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6596 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6597 } 6598 6599 if (success) { 6600 // Get the fix string from the fixed format specifier. 6601 SmallString<128> buf; 6602 llvm::raw_svector_ostream os(buf); 6603 fixedFS.toString(os); 6604 6605 EmitFormatDiagnostic( 6606 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 6607 << Ex->getType() << false << Ex->getSourceRange(), 6608 Ex->getLocStart(), 6609 /*IsStringLocation*/ false, 6610 getSpecifierRange(startSpecifier, specifierLen), 6611 FixItHint::CreateReplacement( 6612 getSpecifierRange(startSpecifier, specifierLen), os.str())); 6613 } else { 6614 EmitFormatDiagnostic(S.PDiag(diag) 6615 << AT.getRepresentativeTypeName(S.Context) 6616 << Ex->getType() << false << Ex->getSourceRange(), 6617 Ex->getLocStart(), 6618 /*IsStringLocation*/ false, 6619 getSpecifierRange(startSpecifier, specifierLen)); 6620 } 6621 6622 return true; 6623 } 6624 6625 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6626 const Expr *OrigFormatExpr, 6627 ArrayRef<const Expr *> Args, 6628 bool HasVAListArg, unsigned format_idx, 6629 unsigned firstDataArg, 6630 Sema::FormatStringType Type, 6631 bool inFunctionCall, 6632 Sema::VariadicCallType CallType, 6633 llvm::SmallBitVector &CheckedVarArgs, 6634 UncoveredArgHandler &UncoveredArg) { 6635 // CHECK: is the format string a wide literal? 6636 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 6637 CheckFormatHandler::EmitFormatDiagnostic( 6638 S, inFunctionCall, Args[format_idx], 6639 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 6640 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6641 return; 6642 } 6643 6644 // Str - The format string. NOTE: this is NOT null-terminated! 6645 StringRef StrRef = FExpr->getString(); 6646 const char *Str = StrRef.data(); 6647 // Account for cases where the string literal is truncated in a declaration. 6648 const ConstantArrayType *T = 6649 S.Context.getAsConstantArrayType(FExpr->getType()); 6650 assert(T && "String literal not of constant array type!"); 6651 size_t TypeSize = T->getSize().getZExtValue(); 6652 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6653 const unsigned numDataArgs = Args.size() - firstDataArg; 6654 6655 // Emit a warning if the string literal is truncated and does not contain an 6656 // embedded null character. 6657 if (TypeSize <= StrRef.size() && 6658 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 6659 CheckFormatHandler::EmitFormatDiagnostic( 6660 S, inFunctionCall, Args[format_idx], 6661 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 6662 FExpr->getLocStart(), 6663 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 6664 return; 6665 } 6666 6667 // CHECK: empty format string? 6668 if (StrLen == 0 && numDataArgs > 0) { 6669 CheckFormatHandler::EmitFormatDiagnostic( 6670 S, inFunctionCall, Args[format_idx], 6671 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 6672 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6673 return; 6674 } 6675 6676 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 6677 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 6678 Type == Sema::FST_OSTrace) { 6679 CheckPrintfHandler H( 6680 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 6681 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 6682 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 6683 CheckedVarArgs, UncoveredArg); 6684 6685 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 6686 S.getLangOpts(), 6687 S.Context.getTargetInfo(), 6688 Type == Sema::FST_FreeBSDKPrintf)) 6689 H.DoneProcessing(); 6690 } else if (Type == Sema::FST_Scanf) { 6691 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 6692 numDataArgs, Str, HasVAListArg, Args, format_idx, 6693 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 6694 6695 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 6696 S.getLangOpts(), 6697 S.Context.getTargetInfo())) 6698 H.DoneProcessing(); 6699 } // TODO: handle other formats 6700 } 6701 6702 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 6703 // Str - The format string. NOTE: this is NOT null-terminated! 6704 StringRef StrRef = FExpr->getString(); 6705 const char *Str = StrRef.data(); 6706 // Account for cases where the string literal is truncated in a declaration. 6707 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 6708 assert(T && "String literal not of constant array type!"); 6709 size_t TypeSize = T->getSize().getZExtValue(); 6710 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6711 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 6712 getLangOpts(), 6713 Context.getTargetInfo()); 6714 } 6715 6716 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 6717 6718 // Returns the related absolute value function that is larger, of 0 if one 6719 // does not exist. 6720 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 6721 switch (AbsFunction) { 6722 default: 6723 return 0; 6724 6725 case Builtin::BI__builtin_abs: 6726 return Builtin::BI__builtin_labs; 6727 case Builtin::BI__builtin_labs: 6728 return Builtin::BI__builtin_llabs; 6729 case Builtin::BI__builtin_llabs: 6730 return 0; 6731 6732 case Builtin::BI__builtin_fabsf: 6733 return Builtin::BI__builtin_fabs; 6734 case Builtin::BI__builtin_fabs: 6735 return Builtin::BI__builtin_fabsl; 6736 case Builtin::BI__builtin_fabsl: 6737 return 0; 6738 6739 case Builtin::BI__builtin_cabsf: 6740 return Builtin::BI__builtin_cabs; 6741 case Builtin::BI__builtin_cabs: 6742 return Builtin::BI__builtin_cabsl; 6743 case Builtin::BI__builtin_cabsl: 6744 return 0; 6745 6746 case Builtin::BIabs: 6747 return Builtin::BIlabs; 6748 case Builtin::BIlabs: 6749 return Builtin::BIllabs; 6750 case Builtin::BIllabs: 6751 return 0; 6752 6753 case Builtin::BIfabsf: 6754 return Builtin::BIfabs; 6755 case Builtin::BIfabs: 6756 return Builtin::BIfabsl; 6757 case Builtin::BIfabsl: 6758 return 0; 6759 6760 case Builtin::BIcabsf: 6761 return Builtin::BIcabs; 6762 case Builtin::BIcabs: 6763 return Builtin::BIcabsl; 6764 case Builtin::BIcabsl: 6765 return 0; 6766 } 6767 } 6768 6769 // Returns the argument type of the absolute value function. 6770 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 6771 unsigned AbsType) { 6772 if (AbsType == 0) 6773 return QualType(); 6774 6775 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 6776 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 6777 if (Error != ASTContext::GE_None) 6778 return QualType(); 6779 6780 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 6781 if (!FT) 6782 return QualType(); 6783 6784 if (FT->getNumParams() != 1) 6785 return QualType(); 6786 6787 return FT->getParamType(0); 6788 } 6789 6790 // Returns the best absolute value function, or zero, based on type and 6791 // current absolute value function. 6792 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 6793 unsigned AbsFunctionKind) { 6794 unsigned BestKind = 0; 6795 uint64_t ArgSize = Context.getTypeSize(ArgType); 6796 for (unsigned Kind = AbsFunctionKind; Kind != 0; 6797 Kind = getLargerAbsoluteValueFunction(Kind)) { 6798 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 6799 if (Context.getTypeSize(ParamType) >= ArgSize) { 6800 if (BestKind == 0) 6801 BestKind = Kind; 6802 else if (Context.hasSameType(ParamType, ArgType)) { 6803 BestKind = Kind; 6804 break; 6805 } 6806 } 6807 } 6808 return BestKind; 6809 } 6810 6811 enum AbsoluteValueKind { 6812 AVK_Integer, 6813 AVK_Floating, 6814 AVK_Complex 6815 }; 6816 6817 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 6818 if (T->isIntegralOrEnumerationType()) 6819 return AVK_Integer; 6820 if (T->isRealFloatingType()) 6821 return AVK_Floating; 6822 if (T->isAnyComplexType()) 6823 return AVK_Complex; 6824 6825 llvm_unreachable("Type not integer, floating, or complex"); 6826 } 6827 6828 // Changes the absolute value function to a different type. Preserves whether 6829 // the function is a builtin. 6830 static unsigned changeAbsFunction(unsigned AbsKind, 6831 AbsoluteValueKind ValueKind) { 6832 switch (ValueKind) { 6833 case AVK_Integer: 6834 switch (AbsKind) { 6835 default: 6836 return 0; 6837 case Builtin::BI__builtin_fabsf: 6838 case Builtin::BI__builtin_fabs: 6839 case Builtin::BI__builtin_fabsl: 6840 case Builtin::BI__builtin_cabsf: 6841 case Builtin::BI__builtin_cabs: 6842 case Builtin::BI__builtin_cabsl: 6843 return Builtin::BI__builtin_abs; 6844 case Builtin::BIfabsf: 6845 case Builtin::BIfabs: 6846 case Builtin::BIfabsl: 6847 case Builtin::BIcabsf: 6848 case Builtin::BIcabs: 6849 case Builtin::BIcabsl: 6850 return Builtin::BIabs; 6851 } 6852 case AVK_Floating: 6853 switch (AbsKind) { 6854 default: 6855 return 0; 6856 case Builtin::BI__builtin_abs: 6857 case Builtin::BI__builtin_labs: 6858 case Builtin::BI__builtin_llabs: 6859 case Builtin::BI__builtin_cabsf: 6860 case Builtin::BI__builtin_cabs: 6861 case Builtin::BI__builtin_cabsl: 6862 return Builtin::BI__builtin_fabsf; 6863 case Builtin::BIabs: 6864 case Builtin::BIlabs: 6865 case Builtin::BIllabs: 6866 case Builtin::BIcabsf: 6867 case Builtin::BIcabs: 6868 case Builtin::BIcabsl: 6869 return Builtin::BIfabsf; 6870 } 6871 case AVK_Complex: 6872 switch (AbsKind) { 6873 default: 6874 return 0; 6875 case Builtin::BI__builtin_abs: 6876 case Builtin::BI__builtin_labs: 6877 case Builtin::BI__builtin_llabs: 6878 case Builtin::BI__builtin_fabsf: 6879 case Builtin::BI__builtin_fabs: 6880 case Builtin::BI__builtin_fabsl: 6881 return Builtin::BI__builtin_cabsf; 6882 case Builtin::BIabs: 6883 case Builtin::BIlabs: 6884 case Builtin::BIllabs: 6885 case Builtin::BIfabsf: 6886 case Builtin::BIfabs: 6887 case Builtin::BIfabsl: 6888 return Builtin::BIcabsf; 6889 } 6890 } 6891 llvm_unreachable("Unable to convert function"); 6892 } 6893 6894 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 6895 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 6896 if (!FnInfo) 6897 return 0; 6898 6899 switch (FDecl->getBuiltinID()) { 6900 default: 6901 return 0; 6902 case Builtin::BI__builtin_abs: 6903 case Builtin::BI__builtin_fabs: 6904 case Builtin::BI__builtin_fabsf: 6905 case Builtin::BI__builtin_fabsl: 6906 case Builtin::BI__builtin_labs: 6907 case Builtin::BI__builtin_llabs: 6908 case Builtin::BI__builtin_cabs: 6909 case Builtin::BI__builtin_cabsf: 6910 case Builtin::BI__builtin_cabsl: 6911 case Builtin::BIabs: 6912 case Builtin::BIlabs: 6913 case Builtin::BIllabs: 6914 case Builtin::BIfabs: 6915 case Builtin::BIfabsf: 6916 case Builtin::BIfabsl: 6917 case Builtin::BIcabs: 6918 case Builtin::BIcabsf: 6919 case Builtin::BIcabsl: 6920 return FDecl->getBuiltinID(); 6921 } 6922 llvm_unreachable("Unknown Builtin type"); 6923 } 6924 6925 // If the replacement is valid, emit a note with replacement function. 6926 // Additionally, suggest including the proper header if not already included. 6927 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 6928 unsigned AbsKind, QualType ArgType) { 6929 bool EmitHeaderHint = true; 6930 const char *HeaderName = nullptr; 6931 const char *FunctionName = nullptr; 6932 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 6933 FunctionName = "std::abs"; 6934 if (ArgType->isIntegralOrEnumerationType()) { 6935 HeaderName = "cstdlib"; 6936 } else if (ArgType->isRealFloatingType()) { 6937 HeaderName = "cmath"; 6938 } else { 6939 llvm_unreachable("Invalid Type"); 6940 } 6941 6942 // Lookup all std::abs 6943 if (NamespaceDecl *Std = S.getStdNamespace()) { 6944 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 6945 R.suppressDiagnostics(); 6946 S.LookupQualifiedName(R, Std); 6947 6948 for (const auto *I : R) { 6949 const FunctionDecl *FDecl = nullptr; 6950 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 6951 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 6952 } else { 6953 FDecl = dyn_cast<FunctionDecl>(I); 6954 } 6955 if (!FDecl) 6956 continue; 6957 6958 // Found std::abs(), check that they are the right ones. 6959 if (FDecl->getNumParams() != 1) 6960 continue; 6961 6962 // Check that the parameter type can handle the argument. 6963 QualType ParamType = FDecl->getParamDecl(0)->getType(); 6964 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 6965 S.Context.getTypeSize(ArgType) <= 6966 S.Context.getTypeSize(ParamType)) { 6967 // Found a function, don't need the header hint. 6968 EmitHeaderHint = false; 6969 break; 6970 } 6971 } 6972 } 6973 } else { 6974 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 6975 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 6976 6977 if (HeaderName) { 6978 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 6979 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 6980 R.suppressDiagnostics(); 6981 S.LookupName(R, S.getCurScope()); 6982 6983 if (R.isSingleResult()) { 6984 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 6985 if (FD && FD->getBuiltinID() == AbsKind) { 6986 EmitHeaderHint = false; 6987 } else { 6988 return; 6989 } 6990 } else if (!R.empty()) { 6991 return; 6992 } 6993 } 6994 } 6995 6996 S.Diag(Loc, diag::note_replace_abs_function) 6997 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 6998 6999 if (!HeaderName) 7000 return; 7001 7002 if (!EmitHeaderHint) 7003 return; 7004 7005 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 7006 << FunctionName; 7007 } 7008 7009 template <std::size_t StrLen> 7010 static bool IsStdFunction(const FunctionDecl *FDecl, 7011 const char (&Str)[StrLen]) { 7012 if (!FDecl) 7013 return false; 7014 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 7015 return false; 7016 if (!FDecl->isInStdNamespace()) 7017 return false; 7018 7019 return true; 7020 } 7021 7022 // Warn when using the wrong abs() function. 7023 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 7024 const FunctionDecl *FDecl) { 7025 if (Call->getNumArgs() != 1) 7026 return; 7027 7028 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 7029 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 7030 if (AbsKind == 0 && !IsStdAbs) 7031 return; 7032 7033 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7034 QualType ParamType = Call->getArg(0)->getType(); 7035 7036 // Unsigned types cannot be negative. Suggest removing the absolute value 7037 // function call. 7038 if (ArgType->isUnsignedIntegerType()) { 7039 const char *FunctionName = 7040 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 7041 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 7042 Diag(Call->getExprLoc(), diag::note_remove_abs) 7043 << FunctionName 7044 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 7045 return; 7046 } 7047 7048 // Taking the absolute value of a pointer is very suspicious, they probably 7049 // wanted to index into an array, dereference a pointer, call a function, etc. 7050 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 7051 unsigned DiagType = 0; 7052 if (ArgType->isFunctionType()) 7053 DiagType = 1; 7054 else if (ArgType->isArrayType()) 7055 DiagType = 2; 7056 7057 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 7058 return; 7059 } 7060 7061 // std::abs has overloads which prevent most of the absolute value problems 7062 // from occurring. 7063 if (IsStdAbs) 7064 return; 7065 7066 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 7067 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 7068 7069 // The argument and parameter are the same kind. Check if they are the right 7070 // size. 7071 if (ArgValueKind == ParamValueKind) { 7072 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 7073 return; 7074 7075 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 7076 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 7077 << FDecl << ArgType << ParamType; 7078 7079 if (NewAbsKind == 0) 7080 return; 7081 7082 emitReplacement(*this, Call->getExprLoc(), 7083 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7084 return; 7085 } 7086 7087 // ArgValueKind != ParamValueKind 7088 // The wrong type of absolute value function was used. Attempt to find the 7089 // proper one. 7090 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 7091 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 7092 if (NewAbsKind == 0) 7093 return; 7094 7095 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 7096 << FDecl << ParamValueKind << ArgValueKind; 7097 7098 emitReplacement(*this, Call->getExprLoc(), 7099 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7100 } 7101 7102 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 7103 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 7104 const FunctionDecl *FDecl) { 7105 if (!Call || !FDecl) return; 7106 7107 // Ignore template specializations and macros. 7108 if (inTemplateInstantiation()) return; 7109 if (Call->getExprLoc().isMacroID()) return; 7110 7111 // Only care about the one template argument, two function parameter std::max 7112 if (Call->getNumArgs() != 2) return; 7113 if (!IsStdFunction(FDecl, "max")) return; 7114 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 7115 if (!ArgList) return; 7116 if (ArgList->size() != 1) return; 7117 7118 // Check that template type argument is unsigned integer. 7119 const auto& TA = ArgList->get(0); 7120 if (TA.getKind() != TemplateArgument::Type) return; 7121 QualType ArgType = TA.getAsType(); 7122 if (!ArgType->isUnsignedIntegerType()) return; 7123 7124 // See if either argument is a literal zero. 7125 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 7126 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 7127 if (!MTE) return false; 7128 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 7129 if (!Num) return false; 7130 if (Num->getValue() != 0) return false; 7131 return true; 7132 }; 7133 7134 const Expr *FirstArg = Call->getArg(0); 7135 const Expr *SecondArg = Call->getArg(1); 7136 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 7137 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 7138 7139 // Only warn when exactly one argument is zero. 7140 if (IsFirstArgZero == IsSecondArgZero) return; 7141 7142 SourceRange FirstRange = FirstArg->getSourceRange(); 7143 SourceRange SecondRange = SecondArg->getSourceRange(); 7144 7145 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 7146 7147 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 7148 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 7149 7150 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 7151 SourceRange RemovalRange; 7152 if (IsFirstArgZero) { 7153 RemovalRange = SourceRange(FirstRange.getBegin(), 7154 SecondRange.getBegin().getLocWithOffset(-1)); 7155 } else { 7156 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 7157 SecondRange.getEnd()); 7158 } 7159 7160 Diag(Call->getExprLoc(), diag::note_remove_max_call) 7161 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 7162 << FixItHint::CreateRemoval(RemovalRange); 7163 } 7164 7165 //===--- CHECK: Standard memory functions ---------------------------------===// 7166 7167 /// \brief Takes the expression passed to the size_t parameter of functions 7168 /// such as memcmp, strncat, etc and warns if it's a comparison. 7169 /// 7170 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 7171 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 7172 IdentifierInfo *FnName, 7173 SourceLocation FnLoc, 7174 SourceLocation RParenLoc) { 7175 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 7176 if (!Size) 7177 return false; 7178 7179 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 7180 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 7181 return false; 7182 7183 SourceRange SizeRange = Size->getSourceRange(); 7184 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 7185 << SizeRange << FnName; 7186 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 7187 << FnName << FixItHint::CreateInsertion( 7188 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 7189 << FixItHint::CreateRemoval(RParenLoc); 7190 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 7191 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 7192 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 7193 ")"); 7194 7195 return true; 7196 } 7197 7198 /// \brief Determine whether the given type is or contains a dynamic class type 7199 /// (e.g., whether it has a vtable). 7200 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 7201 bool &IsContained) { 7202 // Look through array types while ignoring qualifiers. 7203 const Type *Ty = T->getBaseElementTypeUnsafe(); 7204 IsContained = false; 7205 7206 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 7207 RD = RD ? RD->getDefinition() : nullptr; 7208 if (!RD || RD->isInvalidDecl()) 7209 return nullptr; 7210 7211 if (RD->isDynamicClass()) 7212 return RD; 7213 7214 // Check all the fields. If any bases were dynamic, the class is dynamic. 7215 // It's impossible for a class to transitively contain itself by value, so 7216 // infinite recursion is impossible. 7217 for (auto *FD : RD->fields()) { 7218 bool SubContained; 7219 if (const CXXRecordDecl *ContainedRD = 7220 getContainedDynamicClass(FD->getType(), SubContained)) { 7221 IsContained = true; 7222 return ContainedRD; 7223 } 7224 } 7225 7226 return nullptr; 7227 } 7228 7229 /// \brief If E is a sizeof expression, returns its argument expression, 7230 /// otherwise returns NULL. 7231 static const Expr *getSizeOfExprArg(const Expr *E) { 7232 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7233 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7234 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 7235 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 7236 7237 return nullptr; 7238 } 7239 7240 /// \brief If E is a sizeof expression, returns its argument type. 7241 static QualType getSizeOfArgType(const Expr *E) { 7242 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7243 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7244 if (SizeOf->getKind() == clang::UETT_SizeOf) 7245 return SizeOf->getTypeOfArgument(); 7246 7247 return QualType(); 7248 } 7249 7250 /// \brief Check for dangerous or invalid arguments to memset(). 7251 /// 7252 /// This issues warnings on known problematic, dangerous or unspecified 7253 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 7254 /// function calls. 7255 /// 7256 /// \param Call The call expression to diagnose. 7257 void Sema::CheckMemaccessArguments(const CallExpr *Call, 7258 unsigned BId, 7259 IdentifierInfo *FnName) { 7260 assert(BId != 0); 7261 7262 // It is possible to have a non-standard definition of memset. Validate 7263 // we have enough arguments, and if not, abort further checking. 7264 unsigned ExpectedNumArgs = 7265 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 7266 if (Call->getNumArgs() < ExpectedNumArgs) 7267 return; 7268 7269 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 7270 BId == Builtin::BIstrndup ? 1 : 2); 7271 unsigned LenArg = 7272 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 7273 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 7274 7275 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 7276 Call->getLocStart(), Call->getRParenLoc())) 7277 return; 7278 7279 // We have special checking when the length is a sizeof expression. 7280 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 7281 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 7282 llvm::FoldingSetNodeID SizeOfArgID; 7283 7284 // Although widely used, 'bzero' is not a standard function. Be more strict 7285 // with the argument types before allowing diagnostics and only allow the 7286 // form bzero(ptr, sizeof(...)). 7287 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7288 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 7289 return; 7290 7291 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 7292 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 7293 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 7294 7295 QualType DestTy = Dest->getType(); 7296 QualType PointeeTy; 7297 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 7298 PointeeTy = DestPtrTy->getPointeeType(); 7299 7300 // Never warn about void type pointers. This can be used to suppress 7301 // false positives. 7302 if (PointeeTy->isVoidType()) 7303 continue; 7304 7305 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 7306 // actually comparing the expressions for equality. Because computing the 7307 // expression IDs can be expensive, we only do this if the diagnostic is 7308 // enabled. 7309 if (SizeOfArg && 7310 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 7311 SizeOfArg->getExprLoc())) { 7312 // We only compute IDs for expressions if the warning is enabled, and 7313 // cache the sizeof arg's ID. 7314 if (SizeOfArgID == llvm::FoldingSetNodeID()) 7315 SizeOfArg->Profile(SizeOfArgID, Context, true); 7316 llvm::FoldingSetNodeID DestID; 7317 Dest->Profile(DestID, Context, true); 7318 if (DestID == SizeOfArgID) { 7319 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 7320 // over sizeof(src) as well. 7321 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 7322 StringRef ReadableName = FnName->getName(); 7323 7324 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 7325 if (UnaryOp->getOpcode() == UO_AddrOf) 7326 ActionIdx = 1; // If its an address-of operator, just remove it. 7327 if (!PointeeTy->isIncompleteType() && 7328 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 7329 ActionIdx = 2; // If the pointee's size is sizeof(char), 7330 // suggest an explicit length. 7331 7332 // If the function is defined as a builtin macro, do not show macro 7333 // expansion. 7334 SourceLocation SL = SizeOfArg->getExprLoc(); 7335 SourceRange DSR = Dest->getSourceRange(); 7336 SourceRange SSR = SizeOfArg->getSourceRange(); 7337 SourceManager &SM = getSourceManager(); 7338 7339 if (SM.isMacroArgExpansion(SL)) { 7340 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 7341 SL = SM.getSpellingLoc(SL); 7342 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 7343 SM.getSpellingLoc(DSR.getEnd())); 7344 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 7345 SM.getSpellingLoc(SSR.getEnd())); 7346 } 7347 7348 DiagRuntimeBehavior(SL, SizeOfArg, 7349 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 7350 << ReadableName 7351 << PointeeTy 7352 << DestTy 7353 << DSR 7354 << SSR); 7355 DiagRuntimeBehavior(SL, SizeOfArg, 7356 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 7357 << ActionIdx 7358 << SSR); 7359 7360 break; 7361 } 7362 } 7363 7364 // Also check for cases where the sizeof argument is the exact same 7365 // type as the memory argument, and where it points to a user-defined 7366 // record type. 7367 if (SizeOfArgTy != QualType()) { 7368 if (PointeeTy->isRecordType() && 7369 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 7370 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 7371 PDiag(diag::warn_sizeof_pointer_type_memaccess) 7372 << FnName << SizeOfArgTy << ArgIdx 7373 << PointeeTy << Dest->getSourceRange() 7374 << LenExpr->getSourceRange()); 7375 break; 7376 } 7377 } 7378 } else if (DestTy->isArrayType()) { 7379 PointeeTy = DestTy; 7380 } 7381 7382 if (PointeeTy == QualType()) 7383 continue; 7384 7385 // Always complain about dynamic classes. 7386 bool IsContained; 7387 if (const CXXRecordDecl *ContainedRD = 7388 getContainedDynamicClass(PointeeTy, IsContained)) { 7389 7390 unsigned OperationType = 0; 7391 // "overwritten" if we're warning about the destination for any call 7392 // but memcmp; otherwise a verb appropriate to the call. 7393 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 7394 if (BId == Builtin::BImemcpy) 7395 OperationType = 1; 7396 else if(BId == Builtin::BImemmove) 7397 OperationType = 2; 7398 else if (BId == Builtin::BImemcmp) 7399 OperationType = 3; 7400 } 7401 7402 DiagRuntimeBehavior( 7403 Dest->getExprLoc(), Dest, 7404 PDiag(diag::warn_dyn_class_memaccess) 7405 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 7406 << FnName << IsContained << ContainedRD << OperationType 7407 << Call->getCallee()->getSourceRange()); 7408 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 7409 BId != Builtin::BImemset) 7410 DiagRuntimeBehavior( 7411 Dest->getExprLoc(), Dest, 7412 PDiag(diag::warn_arc_object_memaccess) 7413 << ArgIdx << FnName << PointeeTy 7414 << Call->getCallee()->getSourceRange()); 7415 else 7416 continue; 7417 7418 DiagRuntimeBehavior( 7419 Dest->getExprLoc(), Dest, 7420 PDiag(diag::note_bad_memaccess_silence) 7421 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 7422 break; 7423 } 7424 } 7425 7426 // A little helper routine: ignore addition and subtraction of integer literals. 7427 // This intentionally does not ignore all integer constant expressions because 7428 // we don't want to remove sizeof(). 7429 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 7430 Ex = Ex->IgnoreParenCasts(); 7431 7432 for (;;) { 7433 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 7434 if (!BO || !BO->isAdditiveOp()) 7435 break; 7436 7437 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 7438 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 7439 7440 if (isa<IntegerLiteral>(RHS)) 7441 Ex = LHS; 7442 else if (isa<IntegerLiteral>(LHS)) 7443 Ex = RHS; 7444 else 7445 break; 7446 } 7447 7448 return Ex; 7449 } 7450 7451 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 7452 ASTContext &Context) { 7453 // Only handle constant-sized or VLAs, but not flexible members. 7454 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 7455 // Only issue the FIXIT for arrays of size > 1. 7456 if (CAT->getSize().getSExtValue() <= 1) 7457 return false; 7458 } else if (!Ty->isVariableArrayType()) { 7459 return false; 7460 } 7461 return true; 7462 } 7463 7464 // Warn if the user has made the 'size' argument to strlcpy or strlcat 7465 // be the size of the source, instead of the destination. 7466 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 7467 IdentifierInfo *FnName) { 7468 7469 // Don't crash if the user has the wrong number of arguments 7470 unsigned NumArgs = Call->getNumArgs(); 7471 if ((NumArgs != 3) && (NumArgs != 4)) 7472 return; 7473 7474 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 7475 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 7476 const Expr *CompareWithSrc = nullptr; 7477 7478 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 7479 Call->getLocStart(), Call->getRParenLoc())) 7480 return; 7481 7482 // Look for 'strlcpy(dst, x, sizeof(x))' 7483 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 7484 CompareWithSrc = Ex; 7485 else { 7486 // Look for 'strlcpy(dst, x, strlen(x))' 7487 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 7488 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 7489 SizeCall->getNumArgs() == 1) 7490 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 7491 } 7492 } 7493 7494 if (!CompareWithSrc) 7495 return; 7496 7497 // Determine if the argument to sizeof/strlen is equal to the source 7498 // argument. In principle there's all kinds of things you could do 7499 // here, for instance creating an == expression and evaluating it with 7500 // EvaluateAsBooleanCondition, but this uses a more direct technique: 7501 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 7502 if (!SrcArgDRE) 7503 return; 7504 7505 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 7506 if (!CompareWithSrcDRE || 7507 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 7508 return; 7509 7510 const Expr *OriginalSizeArg = Call->getArg(2); 7511 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 7512 << OriginalSizeArg->getSourceRange() << FnName; 7513 7514 // Output a FIXIT hint if the destination is an array (rather than a 7515 // pointer to an array). This could be enhanced to handle some 7516 // pointers if we know the actual size, like if DstArg is 'array+2' 7517 // we could say 'sizeof(array)-2'. 7518 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 7519 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 7520 return; 7521 7522 SmallString<128> sizeString; 7523 llvm::raw_svector_ostream OS(sizeString); 7524 OS << "sizeof("; 7525 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7526 OS << ")"; 7527 7528 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 7529 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 7530 OS.str()); 7531 } 7532 7533 /// Check if two expressions refer to the same declaration. 7534 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 7535 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 7536 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 7537 return D1->getDecl() == D2->getDecl(); 7538 return false; 7539 } 7540 7541 static const Expr *getStrlenExprArg(const Expr *E) { 7542 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7543 const FunctionDecl *FD = CE->getDirectCallee(); 7544 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 7545 return nullptr; 7546 return CE->getArg(0)->IgnoreParenCasts(); 7547 } 7548 return nullptr; 7549 } 7550 7551 // Warn on anti-patterns as the 'size' argument to strncat. 7552 // The correct size argument should look like following: 7553 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 7554 void Sema::CheckStrncatArguments(const CallExpr *CE, 7555 IdentifierInfo *FnName) { 7556 // Don't crash if the user has the wrong number of arguments. 7557 if (CE->getNumArgs() < 3) 7558 return; 7559 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 7560 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 7561 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 7562 7563 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 7564 CE->getRParenLoc())) 7565 return; 7566 7567 // Identify common expressions, which are wrongly used as the size argument 7568 // to strncat and may lead to buffer overflows. 7569 unsigned PatternType = 0; 7570 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 7571 // - sizeof(dst) 7572 if (referToTheSameDecl(SizeOfArg, DstArg)) 7573 PatternType = 1; 7574 // - sizeof(src) 7575 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 7576 PatternType = 2; 7577 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 7578 if (BE->getOpcode() == BO_Sub) { 7579 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 7580 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 7581 // - sizeof(dst) - strlen(dst) 7582 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 7583 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 7584 PatternType = 1; 7585 // - sizeof(src) - (anything) 7586 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 7587 PatternType = 2; 7588 } 7589 } 7590 7591 if (PatternType == 0) 7592 return; 7593 7594 // Generate the diagnostic. 7595 SourceLocation SL = LenArg->getLocStart(); 7596 SourceRange SR = LenArg->getSourceRange(); 7597 SourceManager &SM = getSourceManager(); 7598 7599 // If the function is defined as a builtin macro, do not show macro expansion. 7600 if (SM.isMacroArgExpansion(SL)) { 7601 SL = SM.getSpellingLoc(SL); 7602 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 7603 SM.getSpellingLoc(SR.getEnd())); 7604 } 7605 7606 // Check if the destination is an array (rather than a pointer to an array). 7607 QualType DstTy = DstArg->getType(); 7608 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 7609 Context); 7610 if (!isKnownSizeArray) { 7611 if (PatternType == 1) 7612 Diag(SL, diag::warn_strncat_wrong_size) << SR; 7613 else 7614 Diag(SL, diag::warn_strncat_src_size) << SR; 7615 return; 7616 } 7617 7618 if (PatternType == 1) 7619 Diag(SL, diag::warn_strncat_large_size) << SR; 7620 else 7621 Diag(SL, diag::warn_strncat_src_size) << SR; 7622 7623 SmallString<128> sizeString; 7624 llvm::raw_svector_ostream OS(sizeString); 7625 OS << "sizeof("; 7626 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7627 OS << ") - "; 7628 OS << "strlen("; 7629 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7630 OS << ") - 1"; 7631 7632 Diag(SL, diag::note_strncat_wrong_size) 7633 << FixItHint::CreateReplacement(SR, OS.str()); 7634 } 7635 7636 //===--- CHECK: Return Address of Stack Variable --------------------------===// 7637 7638 static const Expr *EvalVal(const Expr *E, 7639 SmallVectorImpl<const DeclRefExpr *> &refVars, 7640 const Decl *ParentDecl); 7641 static const Expr *EvalAddr(const Expr *E, 7642 SmallVectorImpl<const DeclRefExpr *> &refVars, 7643 const Decl *ParentDecl); 7644 7645 /// CheckReturnStackAddr - Check if a return statement returns the address 7646 /// of a stack variable. 7647 static void 7648 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 7649 SourceLocation ReturnLoc) { 7650 7651 const Expr *stackE = nullptr; 7652 SmallVector<const DeclRefExpr *, 8> refVars; 7653 7654 // Perform checking for returned stack addresses, local blocks, 7655 // label addresses or references to temporaries. 7656 if (lhsType->isPointerType() || 7657 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 7658 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 7659 } else if (lhsType->isReferenceType()) { 7660 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 7661 } 7662 7663 if (!stackE) 7664 return; // Nothing suspicious was found. 7665 7666 // Parameters are initialized in the calling scope, so taking the address 7667 // of a parameter reference doesn't need a warning. 7668 for (auto *DRE : refVars) 7669 if (isa<ParmVarDecl>(DRE->getDecl())) 7670 return; 7671 7672 SourceLocation diagLoc; 7673 SourceRange diagRange; 7674 if (refVars.empty()) { 7675 diagLoc = stackE->getLocStart(); 7676 diagRange = stackE->getSourceRange(); 7677 } else { 7678 // We followed through a reference variable. 'stackE' contains the 7679 // problematic expression but we will warn at the return statement pointing 7680 // at the reference variable. We will later display the "trail" of 7681 // reference variables using notes. 7682 diagLoc = refVars[0]->getLocStart(); 7683 diagRange = refVars[0]->getSourceRange(); 7684 } 7685 7686 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 7687 // address of local var 7688 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 7689 << DR->getDecl()->getDeclName() << diagRange; 7690 } else if (isa<BlockExpr>(stackE)) { // local block. 7691 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 7692 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 7693 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 7694 } else { // local temporary. 7695 // If there is an LValue->RValue conversion, then the value of the 7696 // reference type is used, not the reference. 7697 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 7698 if (ICE->getCastKind() == CK_LValueToRValue) { 7699 return; 7700 } 7701 } 7702 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 7703 << lhsType->isReferenceType() << diagRange; 7704 } 7705 7706 // Display the "trail" of reference variables that we followed until we 7707 // found the problematic expression using notes. 7708 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 7709 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 7710 // If this var binds to another reference var, show the range of the next 7711 // var, otherwise the var binds to the problematic expression, in which case 7712 // show the range of the expression. 7713 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 7714 : stackE->getSourceRange(); 7715 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 7716 << VD->getDeclName() << range; 7717 } 7718 } 7719 7720 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 7721 /// check if the expression in a return statement evaluates to an address 7722 /// to a location on the stack, a local block, an address of a label, or a 7723 /// reference to local temporary. The recursion is used to traverse the 7724 /// AST of the return expression, with recursion backtracking when we 7725 /// encounter a subexpression that (1) clearly does not lead to one of the 7726 /// above problematic expressions (2) is something we cannot determine leads to 7727 /// a problematic expression based on such local checking. 7728 /// 7729 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 7730 /// the expression that they point to. Such variables are added to the 7731 /// 'refVars' vector so that we know what the reference variable "trail" was. 7732 /// 7733 /// EvalAddr processes expressions that are pointers that are used as 7734 /// references (and not L-values). EvalVal handles all other values. 7735 /// At the base case of the recursion is a check for the above problematic 7736 /// expressions. 7737 /// 7738 /// This implementation handles: 7739 /// 7740 /// * pointer-to-pointer casts 7741 /// * implicit conversions from array references to pointers 7742 /// * taking the address of fields 7743 /// * arbitrary interplay between "&" and "*" operators 7744 /// * pointer arithmetic from an address of a stack variable 7745 /// * taking the address of an array element where the array is on the stack 7746 static const Expr *EvalAddr(const Expr *E, 7747 SmallVectorImpl<const DeclRefExpr *> &refVars, 7748 const Decl *ParentDecl) { 7749 if (E->isTypeDependent()) 7750 return nullptr; 7751 7752 // We should only be called for evaluating pointer expressions. 7753 assert((E->getType()->isAnyPointerType() || 7754 E->getType()->isBlockPointerType() || 7755 E->getType()->isObjCQualifiedIdType()) && 7756 "EvalAddr only works on pointers"); 7757 7758 E = E->IgnoreParens(); 7759 7760 // Our "symbolic interpreter" is just a dispatch off the currently 7761 // viewed AST node. We then recursively traverse the AST by calling 7762 // EvalAddr and EvalVal appropriately. 7763 switch (E->getStmtClass()) { 7764 case Stmt::DeclRefExprClass: { 7765 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7766 7767 // If we leave the immediate function, the lifetime isn't about to end. 7768 if (DR->refersToEnclosingVariableOrCapture()) 7769 return nullptr; 7770 7771 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 7772 // If this is a reference variable, follow through to the expression that 7773 // it points to. 7774 if (V->hasLocalStorage() && 7775 V->getType()->isReferenceType() && V->hasInit()) { 7776 // Add the reference variable to the "trail". 7777 refVars.push_back(DR); 7778 return EvalAddr(V->getInit(), refVars, ParentDecl); 7779 } 7780 7781 return nullptr; 7782 } 7783 7784 case Stmt::UnaryOperatorClass: { 7785 // The only unary operator that make sense to handle here 7786 // is AddrOf. All others don't make sense as pointers. 7787 const UnaryOperator *U = cast<UnaryOperator>(E); 7788 7789 if (U->getOpcode() == UO_AddrOf) 7790 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 7791 return nullptr; 7792 } 7793 7794 case Stmt::BinaryOperatorClass: { 7795 // Handle pointer arithmetic. All other binary operators are not valid 7796 // in this context. 7797 const BinaryOperator *B = cast<BinaryOperator>(E); 7798 BinaryOperatorKind op = B->getOpcode(); 7799 7800 if (op != BO_Add && op != BO_Sub) 7801 return nullptr; 7802 7803 const Expr *Base = B->getLHS(); 7804 7805 // Determine which argument is the real pointer base. It could be 7806 // the RHS argument instead of the LHS. 7807 if (!Base->getType()->isPointerType()) 7808 Base = B->getRHS(); 7809 7810 assert(Base->getType()->isPointerType()); 7811 return EvalAddr(Base, refVars, ParentDecl); 7812 } 7813 7814 // For conditional operators we need to see if either the LHS or RHS are 7815 // valid DeclRefExpr*s. If one of them is valid, we return it. 7816 case Stmt::ConditionalOperatorClass: { 7817 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7818 7819 // Handle the GNU extension for missing LHS. 7820 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 7821 if (const Expr *LHSExpr = C->getLHS()) { 7822 // In C++, we can have a throw-expression, which has 'void' type. 7823 if (!LHSExpr->getType()->isVoidType()) 7824 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 7825 return LHS; 7826 } 7827 7828 // In C++, we can have a throw-expression, which has 'void' type. 7829 if (C->getRHS()->getType()->isVoidType()) 7830 return nullptr; 7831 7832 return EvalAddr(C->getRHS(), refVars, ParentDecl); 7833 } 7834 7835 case Stmt::BlockExprClass: 7836 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 7837 return E; // local block. 7838 return nullptr; 7839 7840 case Stmt::AddrLabelExprClass: 7841 return E; // address of label. 7842 7843 case Stmt::ExprWithCleanupsClass: 7844 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7845 ParentDecl); 7846 7847 // For casts, we need to handle conversions from arrays to 7848 // pointer values, and pointer-to-pointer conversions. 7849 case Stmt::ImplicitCastExprClass: 7850 case Stmt::CStyleCastExprClass: 7851 case Stmt::CXXFunctionalCastExprClass: 7852 case Stmt::ObjCBridgedCastExprClass: 7853 case Stmt::CXXStaticCastExprClass: 7854 case Stmt::CXXDynamicCastExprClass: 7855 case Stmt::CXXConstCastExprClass: 7856 case Stmt::CXXReinterpretCastExprClass: { 7857 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 7858 switch (cast<CastExpr>(E)->getCastKind()) { 7859 case CK_LValueToRValue: 7860 case CK_NoOp: 7861 case CK_BaseToDerived: 7862 case CK_DerivedToBase: 7863 case CK_UncheckedDerivedToBase: 7864 case CK_Dynamic: 7865 case CK_CPointerToObjCPointerCast: 7866 case CK_BlockPointerToObjCPointerCast: 7867 case CK_AnyPointerToBlockPointerCast: 7868 return EvalAddr(SubExpr, refVars, ParentDecl); 7869 7870 case CK_ArrayToPointerDecay: 7871 return EvalVal(SubExpr, refVars, ParentDecl); 7872 7873 case CK_BitCast: 7874 if (SubExpr->getType()->isAnyPointerType() || 7875 SubExpr->getType()->isBlockPointerType() || 7876 SubExpr->getType()->isObjCQualifiedIdType()) 7877 return EvalAddr(SubExpr, refVars, ParentDecl); 7878 else 7879 return nullptr; 7880 7881 default: 7882 return nullptr; 7883 } 7884 } 7885 7886 case Stmt::MaterializeTemporaryExprClass: 7887 if (const Expr *Result = 7888 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7889 refVars, ParentDecl)) 7890 return Result; 7891 return E; 7892 7893 // Everything else: we simply don't reason about them. 7894 default: 7895 return nullptr; 7896 } 7897 } 7898 7899 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 7900 /// See the comments for EvalAddr for more details. 7901 static const Expr *EvalVal(const Expr *E, 7902 SmallVectorImpl<const DeclRefExpr *> &refVars, 7903 const Decl *ParentDecl) { 7904 do { 7905 // We should only be called for evaluating non-pointer expressions, or 7906 // expressions with a pointer type that are not used as references but 7907 // instead 7908 // are l-values (e.g., DeclRefExpr with a pointer type). 7909 7910 // Our "symbolic interpreter" is just a dispatch off the currently 7911 // viewed AST node. We then recursively traverse the AST by calling 7912 // EvalAddr and EvalVal appropriately. 7913 7914 E = E->IgnoreParens(); 7915 switch (E->getStmtClass()) { 7916 case Stmt::ImplicitCastExprClass: { 7917 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 7918 if (IE->getValueKind() == VK_LValue) { 7919 E = IE->getSubExpr(); 7920 continue; 7921 } 7922 return nullptr; 7923 } 7924 7925 case Stmt::ExprWithCleanupsClass: 7926 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7927 ParentDecl); 7928 7929 case Stmt::DeclRefExprClass: { 7930 // When we hit a DeclRefExpr we are looking at code that refers to a 7931 // variable's name. If it's not a reference variable we check if it has 7932 // local storage within the function, and if so, return the expression. 7933 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7934 7935 // If we leave the immediate function, the lifetime isn't about to end. 7936 if (DR->refersToEnclosingVariableOrCapture()) 7937 return nullptr; 7938 7939 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 7940 // Check if it refers to itself, e.g. "int& i = i;". 7941 if (V == ParentDecl) 7942 return DR; 7943 7944 if (V->hasLocalStorage()) { 7945 if (!V->getType()->isReferenceType()) 7946 return DR; 7947 7948 // Reference variable, follow through to the expression that 7949 // it points to. 7950 if (V->hasInit()) { 7951 // Add the reference variable to the "trail". 7952 refVars.push_back(DR); 7953 return EvalVal(V->getInit(), refVars, V); 7954 } 7955 } 7956 } 7957 7958 return nullptr; 7959 } 7960 7961 case Stmt::UnaryOperatorClass: { 7962 // The only unary operator that make sense to handle here 7963 // is Deref. All others don't resolve to a "name." This includes 7964 // handling all sorts of rvalues passed to a unary operator. 7965 const UnaryOperator *U = cast<UnaryOperator>(E); 7966 7967 if (U->getOpcode() == UO_Deref) 7968 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 7969 7970 return nullptr; 7971 } 7972 7973 case Stmt::ArraySubscriptExprClass: { 7974 // Array subscripts are potential references to data on the stack. We 7975 // retrieve the DeclRefExpr* for the array variable if it indeed 7976 // has local storage. 7977 const auto *ASE = cast<ArraySubscriptExpr>(E); 7978 if (ASE->isTypeDependent()) 7979 return nullptr; 7980 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 7981 } 7982 7983 case Stmt::OMPArraySectionExprClass: { 7984 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 7985 ParentDecl); 7986 } 7987 7988 case Stmt::ConditionalOperatorClass: { 7989 // For conditional operators we need to see if either the LHS or RHS are 7990 // non-NULL Expr's. If one is non-NULL, we return it. 7991 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7992 7993 // Handle the GNU extension for missing LHS. 7994 if (const Expr *LHSExpr = C->getLHS()) { 7995 // In C++, we can have a throw-expression, which has 'void' type. 7996 if (!LHSExpr->getType()->isVoidType()) 7997 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 7998 return LHS; 7999 } 8000 8001 // In C++, we can have a throw-expression, which has 'void' type. 8002 if (C->getRHS()->getType()->isVoidType()) 8003 return nullptr; 8004 8005 return EvalVal(C->getRHS(), refVars, ParentDecl); 8006 } 8007 8008 // Accesses to members are potential references to data on the stack. 8009 case Stmt::MemberExprClass: { 8010 const MemberExpr *M = cast<MemberExpr>(E); 8011 8012 // Check for indirect access. We only want direct field accesses. 8013 if (M->isArrow()) 8014 return nullptr; 8015 8016 // Check whether the member type is itself a reference, in which case 8017 // we're not going to refer to the member, but to what the member refers 8018 // to. 8019 if (M->getMemberDecl()->getType()->isReferenceType()) 8020 return nullptr; 8021 8022 return EvalVal(M->getBase(), refVars, ParentDecl); 8023 } 8024 8025 case Stmt::MaterializeTemporaryExprClass: 8026 if (const Expr *Result = 8027 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8028 refVars, ParentDecl)) 8029 return Result; 8030 return E; 8031 8032 default: 8033 // Check that we don't return or take the address of a reference to a 8034 // temporary. This is only useful in C++. 8035 if (!E->isTypeDependent() && E->isRValue()) 8036 return E; 8037 8038 // Everything else: we simply don't reason about them. 8039 return nullptr; 8040 } 8041 } while (true); 8042 } 8043 8044 void 8045 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 8046 SourceLocation ReturnLoc, 8047 bool isObjCMethod, 8048 const AttrVec *Attrs, 8049 const FunctionDecl *FD) { 8050 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 8051 8052 // Check if the return value is null but should not be. 8053 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 8054 (!isObjCMethod && isNonNullType(Context, lhsType))) && 8055 CheckNonNullExpr(*this, RetValExp)) 8056 Diag(ReturnLoc, diag::warn_null_ret) 8057 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 8058 8059 // C++11 [basic.stc.dynamic.allocation]p4: 8060 // If an allocation function declared with a non-throwing 8061 // exception-specification fails to allocate storage, it shall return 8062 // a null pointer. Any other allocation function that fails to allocate 8063 // storage shall indicate failure only by throwing an exception [...] 8064 if (FD) { 8065 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 8066 if (Op == OO_New || Op == OO_Array_New) { 8067 const FunctionProtoType *Proto 8068 = FD->getType()->castAs<FunctionProtoType>(); 8069 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 8070 CheckNonNullExpr(*this, RetValExp)) 8071 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 8072 << FD << getLangOpts().CPlusPlus11; 8073 } 8074 } 8075 } 8076 8077 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 8078 8079 /// Check for comparisons of floating point operands using != and ==. 8080 /// Issue a warning if these are no self-comparisons, as they are not likely 8081 /// to do what the programmer intended. 8082 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 8083 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 8084 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 8085 8086 // Special case: check for x == x (which is OK). 8087 // Do not emit warnings for such cases. 8088 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 8089 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 8090 if (DRL->getDecl() == DRR->getDecl()) 8091 return; 8092 8093 // Special case: check for comparisons against literals that can be exactly 8094 // represented by APFloat. In such cases, do not emit a warning. This 8095 // is a heuristic: often comparison against such literals are used to 8096 // detect if a value in a variable has not changed. This clearly can 8097 // lead to false negatives. 8098 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 8099 if (FLL->isExact()) 8100 return; 8101 } else 8102 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 8103 if (FLR->isExact()) 8104 return; 8105 8106 // Check for comparisons with builtin types. 8107 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 8108 if (CL->getBuiltinCallee()) 8109 return; 8110 8111 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 8112 if (CR->getBuiltinCallee()) 8113 return; 8114 8115 // Emit the diagnostic. 8116 Diag(Loc, diag::warn_floatingpoint_eq) 8117 << LHS->getSourceRange() << RHS->getSourceRange(); 8118 } 8119 8120 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 8121 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 8122 8123 namespace { 8124 8125 /// Structure recording the 'active' range of an integer-valued 8126 /// expression. 8127 struct IntRange { 8128 /// The number of bits active in the int. 8129 unsigned Width; 8130 8131 /// True if the int is known not to have negative values. 8132 bool NonNegative; 8133 8134 IntRange(unsigned Width, bool NonNegative) 8135 : Width(Width), NonNegative(NonNegative) 8136 {} 8137 8138 /// Returns the range of the bool type. 8139 static IntRange forBoolType() { 8140 return IntRange(1, true); 8141 } 8142 8143 /// Returns the range of an opaque value of the given integral type. 8144 static IntRange forValueOfType(ASTContext &C, QualType T) { 8145 return forValueOfCanonicalType(C, 8146 T->getCanonicalTypeInternal().getTypePtr()); 8147 } 8148 8149 /// Returns the range of an opaque value of a canonical integral type. 8150 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 8151 assert(T->isCanonicalUnqualified()); 8152 8153 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8154 T = VT->getElementType().getTypePtr(); 8155 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8156 T = CT->getElementType().getTypePtr(); 8157 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8158 T = AT->getValueType().getTypePtr(); 8159 8160 // For enum types, use the known bit width of the enumerators. 8161 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 8162 EnumDecl *Enum = ET->getDecl(); 8163 if (!Enum->isCompleteDefinition()) 8164 return IntRange(C.getIntWidth(QualType(T, 0)), false); 8165 8166 unsigned NumPositive = Enum->getNumPositiveBits(); 8167 unsigned NumNegative = Enum->getNumNegativeBits(); 8168 8169 if (NumNegative == 0) 8170 return IntRange(NumPositive, true/*NonNegative*/); 8171 else 8172 return IntRange(std::max(NumPositive + 1, NumNegative), 8173 false/*NonNegative*/); 8174 } 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 "target" range of a canonical integral type, i.e. 8183 /// the range of values expressible in the type. 8184 /// 8185 /// This matches forValueOfCanonicalType except that enums have the 8186 /// full range of their type, not the range of their enumerators. 8187 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 8188 assert(T->isCanonicalUnqualified()); 8189 8190 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8191 T = VT->getElementType().getTypePtr(); 8192 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8193 T = CT->getElementType().getTypePtr(); 8194 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8195 T = AT->getValueType().getTypePtr(); 8196 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8197 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 8198 8199 const BuiltinType *BT = cast<BuiltinType>(T); 8200 assert(BT->isInteger()); 8201 8202 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8203 } 8204 8205 /// Returns the supremum of two ranges: i.e. their conservative merge. 8206 static IntRange join(IntRange L, IntRange R) { 8207 return IntRange(std::max(L.Width, R.Width), 8208 L.NonNegative && R.NonNegative); 8209 } 8210 8211 /// Returns the infinum of two ranges: i.e. their aggressive merge. 8212 static IntRange meet(IntRange L, IntRange R) { 8213 return IntRange(std::min(L.Width, R.Width), 8214 L.NonNegative || R.NonNegative); 8215 } 8216 }; 8217 8218 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 8219 if (value.isSigned() && value.isNegative()) 8220 return IntRange(value.getMinSignedBits(), false); 8221 8222 if (value.getBitWidth() > MaxWidth) 8223 value = value.trunc(MaxWidth); 8224 8225 // isNonNegative() just checks the sign bit without considering 8226 // signedness. 8227 return IntRange(value.getActiveBits(), true); 8228 } 8229 8230 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 8231 unsigned MaxWidth) { 8232 if (result.isInt()) 8233 return GetValueRange(C, result.getInt(), MaxWidth); 8234 8235 if (result.isVector()) { 8236 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 8237 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 8238 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 8239 R = IntRange::join(R, El); 8240 } 8241 return R; 8242 } 8243 8244 if (result.isComplexInt()) { 8245 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 8246 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 8247 return IntRange::join(R, I); 8248 } 8249 8250 // This can happen with lossless casts to intptr_t of "based" lvalues. 8251 // Assume it might use arbitrary bits. 8252 // FIXME: The only reason we need to pass the type in here is to get 8253 // the sign right on this one case. It would be nice if APValue 8254 // preserved this. 8255 assert(result.isLValue() || result.isAddrLabelDiff()); 8256 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 8257 } 8258 8259 QualType GetExprType(const Expr *E) { 8260 QualType Ty = E->getType(); 8261 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 8262 Ty = AtomicRHS->getValueType(); 8263 return Ty; 8264 } 8265 8266 /// Pseudo-evaluate the given integer expression, estimating the 8267 /// range of values it might take. 8268 /// 8269 /// \param MaxWidth - the width to which the value will be truncated 8270 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 8271 E = E->IgnoreParens(); 8272 8273 // Try a full evaluation first. 8274 Expr::EvalResult result; 8275 if (E->EvaluateAsRValue(result, C)) 8276 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 8277 8278 // I think we only want to look through implicit casts here; if the 8279 // user has an explicit widening cast, we should treat the value as 8280 // being of the new, wider type. 8281 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 8282 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 8283 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 8284 8285 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 8286 8287 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 8288 CE->getCastKind() == CK_BooleanToSignedIntegral; 8289 8290 // Assume that non-integer casts can span the full range of the type. 8291 if (!isIntegerCast) 8292 return OutputTypeRange; 8293 8294 IntRange SubRange 8295 = GetExprRange(C, CE->getSubExpr(), 8296 std::min(MaxWidth, OutputTypeRange.Width)); 8297 8298 // Bail out if the subexpr's range is as wide as the cast type. 8299 if (SubRange.Width >= OutputTypeRange.Width) 8300 return OutputTypeRange; 8301 8302 // Otherwise, we take the smaller width, and we're non-negative if 8303 // either the output type or the subexpr is. 8304 return IntRange(SubRange.Width, 8305 SubRange.NonNegative || OutputTypeRange.NonNegative); 8306 } 8307 8308 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 8309 // If we can fold the condition, just take that operand. 8310 bool CondResult; 8311 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 8312 return GetExprRange(C, CondResult ? CO->getTrueExpr() 8313 : CO->getFalseExpr(), 8314 MaxWidth); 8315 8316 // Otherwise, conservatively merge. 8317 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 8318 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 8319 return IntRange::join(L, R); 8320 } 8321 8322 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 8323 switch (BO->getOpcode()) { 8324 8325 // Boolean-valued operations are single-bit and positive. 8326 case BO_LAnd: 8327 case BO_LOr: 8328 case BO_LT: 8329 case BO_GT: 8330 case BO_LE: 8331 case BO_GE: 8332 case BO_EQ: 8333 case BO_NE: 8334 return IntRange::forBoolType(); 8335 8336 // The type of the assignments is the type of the LHS, so the RHS 8337 // is not necessarily the same type. 8338 case BO_MulAssign: 8339 case BO_DivAssign: 8340 case BO_RemAssign: 8341 case BO_AddAssign: 8342 case BO_SubAssign: 8343 case BO_XorAssign: 8344 case BO_OrAssign: 8345 // TODO: bitfields? 8346 return IntRange::forValueOfType(C, GetExprType(E)); 8347 8348 // Simple assignments just pass through the RHS, which will have 8349 // been coerced to the LHS type. 8350 case BO_Assign: 8351 // TODO: bitfields? 8352 return GetExprRange(C, BO->getRHS(), MaxWidth); 8353 8354 // Operations with opaque sources are black-listed. 8355 case BO_PtrMemD: 8356 case BO_PtrMemI: 8357 return IntRange::forValueOfType(C, GetExprType(E)); 8358 8359 // Bitwise-and uses the *infinum* of the two source ranges. 8360 case BO_And: 8361 case BO_AndAssign: 8362 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 8363 GetExprRange(C, BO->getRHS(), MaxWidth)); 8364 8365 // Left shift gets black-listed based on a judgement call. 8366 case BO_Shl: 8367 // ...except that we want to treat '1 << (blah)' as logically 8368 // positive. It's an important idiom. 8369 if (IntegerLiteral *I 8370 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 8371 if (I->getValue() == 1) { 8372 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 8373 return IntRange(R.Width, /*NonNegative*/ true); 8374 } 8375 } 8376 // fallthrough 8377 8378 case BO_ShlAssign: 8379 return IntRange::forValueOfType(C, GetExprType(E)); 8380 8381 // Right shift by a constant can narrow its left argument. 8382 case BO_Shr: 8383 case BO_ShrAssign: { 8384 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8385 8386 // If the shift amount is a positive constant, drop the width by 8387 // that much. 8388 llvm::APSInt shift; 8389 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 8390 shift.isNonNegative()) { 8391 unsigned zext = shift.getZExtValue(); 8392 if (zext >= L.Width) 8393 L.Width = (L.NonNegative ? 0 : 1); 8394 else 8395 L.Width -= zext; 8396 } 8397 8398 return L; 8399 } 8400 8401 // Comma acts as its right operand. 8402 case BO_Comma: 8403 return GetExprRange(C, BO->getRHS(), MaxWidth); 8404 8405 // Black-list pointer subtractions. 8406 case BO_Sub: 8407 if (BO->getLHS()->getType()->isPointerType()) 8408 return IntRange::forValueOfType(C, GetExprType(E)); 8409 break; 8410 8411 // The width of a division result is mostly determined by the size 8412 // of the LHS. 8413 case BO_Div: { 8414 // Don't 'pre-truncate' the operands. 8415 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8416 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8417 8418 // If the divisor is constant, use that. 8419 llvm::APSInt divisor; 8420 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 8421 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 8422 if (log2 >= L.Width) 8423 L.Width = (L.NonNegative ? 0 : 1); 8424 else 8425 L.Width = std::min(L.Width - log2, MaxWidth); 8426 return L; 8427 } 8428 8429 // Otherwise, just use the LHS's width. 8430 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8431 return IntRange(L.Width, L.NonNegative && R.NonNegative); 8432 } 8433 8434 // The result of a remainder can't be larger than the result of 8435 // either side. 8436 case BO_Rem: { 8437 // Don't 'pre-truncate' the operands. 8438 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8439 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8440 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8441 8442 IntRange meet = IntRange::meet(L, R); 8443 meet.Width = std::min(meet.Width, MaxWidth); 8444 return meet; 8445 } 8446 8447 // The default behavior is okay for these. 8448 case BO_Mul: 8449 case BO_Add: 8450 case BO_Xor: 8451 case BO_Or: 8452 break; 8453 } 8454 8455 // The default case is to treat the operation as if it were closed 8456 // on the narrowest type that encompasses both operands. 8457 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8458 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 8459 return IntRange::join(L, R); 8460 } 8461 8462 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 8463 switch (UO->getOpcode()) { 8464 // Boolean-valued operations are white-listed. 8465 case UO_LNot: 8466 return IntRange::forBoolType(); 8467 8468 // Operations with opaque sources are black-listed. 8469 case UO_Deref: 8470 case UO_AddrOf: // should be impossible 8471 return IntRange::forValueOfType(C, GetExprType(E)); 8472 8473 default: 8474 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 8475 } 8476 } 8477 8478 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 8479 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 8480 8481 if (const auto *BitField = E->getSourceBitField()) 8482 return IntRange(BitField->getBitWidthValue(C), 8483 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 8484 8485 return IntRange::forValueOfType(C, GetExprType(E)); 8486 } 8487 8488 IntRange GetExprRange(ASTContext &C, const Expr *E) { 8489 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 8490 } 8491 8492 /// Checks whether the given value, which currently has the given 8493 /// source semantics, has the same value when coerced through the 8494 /// target semantics. 8495 bool IsSameFloatAfterCast(const llvm::APFloat &value, 8496 const llvm::fltSemantics &Src, 8497 const llvm::fltSemantics &Tgt) { 8498 llvm::APFloat truncated = value; 8499 8500 bool ignored; 8501 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 8502 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 8503 8504 return truncated.bitwiseIsEqual(value); 8505 } 8506 8507 /// Checks whether the given value, which currently has the given 8508 /// source semantics, has the same value when coerced through the 8509 /// target semantics. 8510 /// 8511 /// The value might be a vector of floats (or a complex number). 8512 bool IsSameFloatAfterCast(const APValue &value, 8513 const llvm::fltSemantics &Src, 8514 const llvm::fltSemantics &Tgt) { 8515 if (value.isFloat()) 8516 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 8517 8518 if (value.isVector()) { 8519 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 8520 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 8521 return false; 8522 return true; 8523 } 8524 8525 assert(value.isComplexFloat()); 8526 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 8527 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 8528 } 8529 8530 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 8531 8532 bool IsZero(Sema &S, Expr *E) { 8533 // Suppress cases where we are comparing against an enum constant. 8534 if (const DeclRefExpr *DR = 8535 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 8536 if (isa<EnumConstantDecl>(DR->getDecl())) 8537 return false; 8538 8539 // Suppress cases where the '0' value is expanded from a macro. 8540 if (E->getLocStart().isMacroID()) 8541 return false; 8542 8543 llvm::APSInt Value; 8544 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 8545 } 8546 8547 bool HasEnumType(Expr *E) { 8548 // Strip off implicit integral promotions. 8549 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8550 if (ICE->getCastKind() != CK_IntegralCast && 8551 ICE->getCastKind() != CK_NoOp) 8552 break; 8553 E = ICE->getSubExpr(); 8554 } 8555 8556 return E->getType()->isEnumeralType(); 8557 } 8558 8559 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 8560 // Disable warning in template instantiations. 8561 if (S.inTemplateInstantiation()) 8562 return; 8563 8564 BinaryOperatorKind op = E->getOpcode(); 8565 if (E->isValueDependent()) 8566 return; 8567 8568 if (op == BO_LT && IsZero(S, E->getRHS())) { 8569 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8570 << "< 0" << "false" << HasEnumType(E->getLHS()) 8571 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8572 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 8573 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8574 << ">= 0" << "true" << HasEnumType(E->getLHS()) 8575 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8576 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 8577 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8578 << "0 >" << "false" << HasEnumType(E->getRHS()) 8579 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8580 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 8581 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8582 << "0 <=" << "true" << HasEnumType(E->getRHS()) 8583 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8584 } 8585 } 8586 8587 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant, 8588 Expr *Other, const llvm::APSInt &Value, 8589 bool RhsConstant) { 8590 // Disable warning in template instantiations. 8591 if (S.inTemplateInstantiation()) 8592 return; 8593 8594 // TODO: Investigate using GetExprRange() to get tighter bounds 8595 // on the bit ranges. 8596 QualType OtherT = Other->getType(); 8597 if (const auto *AT = OtherT->getAs<AtomicType>()) 8598 OtherT = AT->getValueType(); 8599 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 8600 unsigned OtherWidth = OtherRange.Width; 8601 8602 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 8603 8604 // 0 values are handled later by CheckTrivialUnsignedComparison(). 8605 if ((Value == 0) && (!OtherIsBooleanType)) 8606 return; 8607 8608 BinaryOperatorKind op = E->getOpcode(); 8609 bool IsTrue = true; 8610 8611 // Used for diagnostic printout. 8612 enum { 8613 LiteralConstant = 0, 8614 CXXBoolLiteralTrue, 8615 CXXBoolLiteralFalse 8616 } LiteralOrBoolConstant = LiteralConstant; 8617 8618 if (!OtherIsBooleanType) { 8619 QualType ConstantT = Constant->getType(); 8620 QualType CommonT = E->getLHS()->getType(); 8621 8622 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 8623 return; 8624 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 8625 "comparison with non-integer type"); 8626 8627 bool ConstantSigned = ConstantT->isSignedIntegerType(); 8628 bool CommonSigned = CommonT->isSignedIntegerType(); 8629 8630 bool EqualityOnly = false; 8631 8632 if (CommonSigned) { 8633 // The common type is signed, therefore no signed to unsigned conversion. 8634 if (!OtherRange.NonNegative) { 8635 // Check that the constant is representable in type OtherT. 8636 if (ConstantSigned) { 8637 if (OtherWidth >= Value.getMinSignedBits()) 8638 return; 8639 } else { // !ConstantSigned 8640 if (OtherWidth >= Value.getActiveBits() + 1) 8641 return; 8642 } 8643 } else { // !OtherSigned 8644 // Check that the constant is representable in type OtherT. 8645 // Negative values are out of range. 8646 if (ConstantSigned) { 8647 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 8648 return; 8649 } else { // !ConstantSigned 8650 if (OtherWidth >= Value.getActiveBits()) 8651 return; 8652 } 8653 } 8654 } else { // !CommonSigned 8655 if (OtherRange.NonNegative) { 8656 if (OtherWidth >= Value.getActiveBits()) 8657 return; 8658 } else { // OtherSigned 8659 assert(!ConstantSigned && 8660 "Two signed types converted to unsigned types."); 8661 // Check to see if the constant is representable in OtherT. 8662 if (OtherWidth > Value.getActiveBits()) 8663 return; 8664 // Check to see if the constant is equivalent to a negative value 8665 // cast to CommonT. 8666 if (S.Context.getIntWidth(ConstantT) == 8667 S.Context.getIntWidth(CommonT) && 8668 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 8669 return; 8670 // The constant value rests between values that OtherT can represent 8671 // after conversion. Relational comparison still works, but equality 8672 // comparisons will be tautological. 8673 EqualityOnly = true; 8674 } 8675 } 8676 8677 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 8678 8679 if (op == BO_EQ || op == BO_NE) { 8680 IsTrue = op == BO_NE; 8681 } else if (EqualityOnly) { 8682 return; 8683 } else if (RhsConstant) { 8684 if (op == BO_GT || op == BO_GE) 8685 IsTrue = !PositiveConstant; 8686 else // op == BO_LT || op == BO_LE 8687 IsTrue = PositiveConstant; 8688 } else { 8689 if (op == BO_LT || op == BO_LE) 8690 IsTrue = !PositiveConstant; 8691 else // op == BO_GT || op == BO_GE 8692 IsTrue = PositiveConstant; 8693 } 8694 } else { 8695 // Other isKnownToHaveBooleanValue 8696 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 8697 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 8698 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 8699 8700 static const struct LinkedConditions { 8701 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 8702 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 8703 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 8704 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 8705 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 8706 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 8707 8708 } TruthTable = { 8709 // Constant on LHS. | Constant on RHS. | 8710 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 8711 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 8712 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 8713 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 8714 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 8715 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 8716 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 8717 }; 8718 8719 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 8720 8721 enum ConstantValue ConstVal = Zero; 8722 if (Value.isUnsigned() || Value.isNonNegative()) { 8723 if (Value == 0) { 8724 LiteralOrBoolConstant = 8725 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 8726 ConstVal = Zero; 8727 } else if (Value == 1) { 8728 LiteralOrBoolConstant = 8729 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 8730 ConstVal = One; 8731 } else { 8732 LiteralOrBoolConstant = LiteralConstant; 8733 ConstVal = GT_One; 8734 } 8735 } else { 8736 ConstVal = LT_Zero; 8737 } 8738 8739 CompareBoolWithConstantResult CmpRes; 8740 8741 switch (op) { 8742 case BO_LT: 8743 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 8744 break; 8745 case BO_GT: 8746 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 8747 break; 8748 case BO_LE: 8749 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 8750 break; 8751 case BO_GE: 8752 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 8753 break; 8754 case BO_EQ: 8755 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 8756 break; 8757 case BO_NE: 8758 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 8759 break; 8760 default: 8761 CmpRes = Unkwn; 8762 break; 8763 } 8764 8765 if (CmpRes == AFals) { 8766 IsTrue = false; 8767 } else if (CmpRes == ATrue) { 8768 IsTrue = true; 8769 } else { 8770 return; 8771 } 8772 } 8773 8774 // If this is a comparison to an enum constant, include that 8775 // constant in the diagnostic. 8776 const EnumConstantDecl *ED = nullptr; 8777 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 8778 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 8779 8780 SmallString<64> PrettySourceValue; 8781 llvm::raw_svector_ostream OS(PrettySourceValue); 8782 if (ED) 8783 OS << '\'' << *ED << "' (" << Value << ")"; 8784 else 8785 OS << Value; 8786 8787 S.DiagRuntimeBehavior( 8788 E->getOperatorLoc(), E, 8789 S.PDiag(diag::warn_out_of_range_compare) 8790 << OS.str() << LiteralOrBoolConstant 8791 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 8792 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 8793 } 8794 8795 /// Analyze the operands of the given comparison. Implements the 8796 /// fallback case from AnalyzeComparison. 8797 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 8798 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8799 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8800 } 8801 8802 /// \brief Implements -Wsign-compare. 8803 /// 8804 /// \param E the binary operator to check for warnings 8805 void AnalyzeComparison(Sema &S, BinaryOperator *E) { 8806 // The type the comparison is being performed in. 8807 QualType T = E->getLHS()->getType(); 8808 8809 // Only analyze comparison operators where both sides have been converted to 8810 // the same type. 8811 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 8812 return AnalyzeImpConvsInComparison(S, E); 8813 8814 // Don't analyze value-dependent comparisons directly. 8815 if (E->isValueDependent()) 8816 return AnalyzeImpConvsInComparison(S, E); 8817 8818 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 8819 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 8820 8821 bool IsComparisonConstant = false; 8822 8823 // Check whether an integer constant comparison results in a value 8824 // of 'true' or 'false'. 8825 if (T->isIntegralType(S.Context)) { 8826 llvm::APSInt RHSValue; 8827 bool IsRHSIntegralLiteral = 8828 RHS->isIntegerConstantExpr(RHSValue, S.Context); 8829 llvm::APSInt LHSValue; 8830 bool IsLHSIntegralLiteral = 8831 LHS->isIntegerConstantExpr(LHSValue, S.Context); 8832 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 8833 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 8834 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 8835 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 8836 else 8837 IsComparisonConstant = 8838 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 8839 } else if (!T->hasUnsignedIntegerRepresentation()) 8840 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 8841 8842 // We don't do anything special if this isn't an unsigned integral 8843 // comparison: we're only interested in integral comparisons, and 8844 // signed comparisons only happen in cases we don't care to warn about. 8845 // 8846 // We also don't care about value-dependent expressions or expressions 8847 // whose result is a constant. 8848 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 8849 return AnalyzeImpConvsInComparison(S, E); 8850 8851 // Check to see if one of the (unmodified) operands is of different 8852 // signedness. 8853 Expr *signedOperand, *unsignedOperand; 8854 if (LHS->getType()->hasSignedIntegerRepresentation()) { 8855 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 8856 "unsigned comparison between two signed integer expressions?"); 8857 signedOperand = LHS; 8858 unsignedOperand = RHS; 8859 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 8860 signedOperand = RHS; 8861 unsignedOperand = LHS; 8862 } else { 8863 CheckTrivialUnsignedComparison(S, E); 8864 return AnalyzeImpConvsInComparison(S, E); 8865 } 8866 8867 // Otherwise, calculate the effective range of the signed operand. 8868 IntRange signedRange = GetExprRange(S.Context, signedOperand); 8869 8870 // Go ahead and analyze implicit conversions in the operands. Note 8871 // that we skip the implicit conversions on both sides. 8872 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 8873 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 8874 8875 // If the signed range is non-negative, -Wsign-compare won't fire, 8876 // but we should still check for comparisons which are always true 8877 // or false. 8878 if (signedRange.NonNegative) 8879 return CheckTrivialUnsignedComparison(S, E); 8880 8881 // For (in)equality comparisons, if the unsigned operand is a 8882 // constant which cannot collide with a overflowed signed operand, 8883 // then reinterpreting the signed operand as unsigned will not 8884 // change the result of the comparison. 8885 if (E->isEqualityOp()) { 8886 unsigned comparisonWidth = S.Context.getIntWidth(T); 8887 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 8888 8889 // We should never be unable to prove that the unsigned operand is 8890 // non-negative. 8891 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 8892 8893 if (unsignedRange.Width < comparisonWidth) 8894 return; 8895 } 8896 8897 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 8898 S.PDiag(diag::warn_mixed_sign_comparison) 8899 << LHS->getType() << RHS->getType() 8900 << LHS->getSourceRange() << RHS->getSourceRange()); 8901 } 8902 8903 /// Analyzes an attempt to assign the given value to a bitfield. 8904 /// 8905 /// Returns true if there was something fishy about the attempt. 8906 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 8907 SourceLocation InitLoc) { 8908 assert(Bitfield->isBitField()); 8909 if (Bitfield->isInvalidDecl()) 8910 return false; 8911 8912 // White-list bool bitfields. 8913 QualType BitfieldType = Bitfield->getType(); 8914 if (BitfieldType->isBooleanType()) 8915 return false; 8916 8917 if (BitfieldType->isEnumeralType()) { 8918 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 8919 // If the underlying enum type was not explicitly specified as an unsigned 8920 // type and the enum contain only positive values, MSVC++ will cause an 8921 // inconsistency by storing this as a signed type. 8922 if (S.getLangOpts().CPlusPlus11 && 8923 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 8924 BitfieldEnumDecl->getNumPositiveBits() > 0 && 8925 BitfieldEnumDecl->getNumNegativeBits() == 0) { 8926 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 8927 << BitfieldEnumDecl->getNameAsString(); 8928 } 8929 } 8930 8931 if (Bitfield->getType()->isBooleanType()) 8932 return false; 8933 8934 // Ignore value- or type-dependent expressions. 8935 if (Bitfield->getBitWidth()->isValueDependent() || 8936 Bitfield->getBitWidth()->isTypeDependent() || 8937 Init->isValueDependent() || 8938 Init->isTypeDependent()) 8939 return false; 8940 8941 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 8942 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 8943 8944 llvm::APSInt Value; 8945 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 8946 Expr::SE_AllowSideEffects)) { 8947 // The RHS is not constant. If the RHS has an enum type, make sure the 8948 // bitfield is wide enough to hold all the values of the enum without 8949 // truncation. 8950 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 8951 EnumDecl *ED = EnumTy->getDecl(); 8952 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 8953 8954 // Enum types are implicitly signed on Windows, so check if there are any 8955 // negative enumerators to see if the enum was intended to be signed or 8956 // not. 8957 bool SignedEnum = ED->getNumNegativeBits() > 0; 8958 8959 // Check for surprising sign changes when assigning enum values to a 8960 // bitfield of different signedness. If the bitfield is signed and we 8961 // have exactly the right number of bits to store this unsigned enum, 8962 // suggest changing the enum to an unsigned type. This typically happens 8963 // on Windows where unfixed enums always use an underlying type of 'int'. 8964 unsigned DiagID = 0; 8965 if (SignedEnum && !SignedBitfield) { 8966 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 8967 } else if (SignedBitfield && !SignedEnum && 8968 ED->getNumPositiveBits() == FieldWidth) { 8969 DiagID = diag::warn_signed_bitfield_enum_conversion; 8970 } 8971 8972 if (DiagID) { 8973 S.Diag(InitLoc, DiagID) << Bitfield << ED; 8974 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 8975 SourceRange TypeRange = 8976 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 8977 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 8978 << SignedEnum << TypeRange; 8979 } 8980 8981 // Compute the required bitwidth. If the enum has negative values, we need 8982 // one more bit than the normal number of positive bits to represent the 8983 // sign bit. 8984 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 8985 ED->getNumNegativeBits()) 8986 : ED->getNumPositiveBits(); 8987 8988 // Check the bitwidth. 8989 if (BitsNeeded > FieldWidth) { 8990 Expr *WidthExpr = Bitfield->getBitWidth(); 8991 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 8992 << Bitfield << ED; 8993 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 8994 << BitsNeeded << ED << WidthExpr->getSourceRange(); 8995 } 8996 } 8997 8998 return false; 8999 } 9000 9001 unsigned OriginalWidth = Value.getBitWidth(); 9002 9003 if (!Value.isSigned() || Value.isNegative()) 9004 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 9005 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 9006 OriginalWidth = Value.getMinSignedBits(); 9007 9008 if (OriginalWidth <= FieldWidth) 9009 return false; 9010 9011 // Compute the value which the bitfield will contain. 9012 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 9013 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 9014 9015 // Check whether the stored value is equal to the original value. 9016 TruncatedValue = TruncatedValue.extend(OriginalWidth); 9017 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 9018 return false; 9019 9020 // Special-case bitfields of width 1: booleans are naturally 0/1, and 9021 // therefore don't strictly fit into a signed bitfield of width 1. 9022 if (FieldWidth == 1 && Value == 1) 9023 return false; 9024 9025 std::string PrettyValue = Value.toString(10); 9026 std::string PrettyTrunc = TruncatedValue.toString(10); 9027 9028 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 9029 << PrettyValue << PrettyTrunc << OriginalInit->getType() 9030 << Init->getSourceRange(); 9031 9032 return true; 9033 } 9034 9035 /// Analyze the given simple or compound assignment for warning-worthy 9036 /// operations. 9037 void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 9038 // Just recurse on the LHS. 9039 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9040 9041 // We want to recurse on the RHS as normal unless we're assigning to 9042 // a bitfield. 9043 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 9044 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 9045 E->getOperatorLoc())) { 9046 // Recurse, ignoring any implicit conversions on the RHS. 9047 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 9048 E->getOperatorLoc()); 9049 } 9050 } 9051 9052 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9053 } 9054 9055 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9056 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 9057 SourceLocation CContext, unsigned diag, 9058 bool pruneControlFlow = false) { 9059 if (pruneControlFlow) { 9060 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9061 S.PDiag(diag) 9062 << SourceType << T << E->getSourceRange() 9063 << SourceRange(CContext)); 9064 return; 9065 } 9066 S.Diag(E->getExprLoc(), diag) 9067 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 9068 } 9069 9070 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9071 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 9072 unsigned diag, bool pruneControlFlow = false) { 9073 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 9074 } 9075 9076 9077 /// Diagnose an implicit cast from a floating point value to an integer value. 9078 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 9079 9080 SourceLocation CContext) { 9081 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 9082 const bool PruneWarnings = S.inTemplateInstantiation(); 9083 9084 Expr *InnerE = E->IgnoreParenImpCasts(); 9085 // We also want to warn on, e.g., "int i = -1.234" 9086 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 9087 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 9088 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 9089 9090 const bool IsLiteral = 9091 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 9092 9093 llvm::APFloat Value(0.0); 9094 bool IsConstant = 9095 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 9096 if (!IsConstant) { 9097 return DiagnoseImpCast(S, E, T, CContext, 9098 diag::warn_impcast_float_integer, PruneWarnings); 9099 } 9100 9101 bool isExact = false; 9102 9103 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 9104 T->hasUnsignedIntegerRepresentation()); 9105 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 9106 &isExact) == llvm::APFloat::opOK && 9107 isExact) { 9108 if (IsLiteral) return; 9109 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 9110 PruneWarnings); 9111 } 9112 9113 unsigned DiagID = 0; 9114 if (IsLiteral) { 9115 // Warn on floating point literal to integer. 9116 DiagID = diag::warn_impcast_literal_float_to_integer; 9117 } else if (IntegerValue == 0) { 9118 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 9119 return DiagnoseImpCast(S, E, T, CContext, 9120 diag::warn_impcast_float_integer, PruneWarnings); 9121 } 9122 // Warn on non-zero to zero conversion. 9123 DiagID = diag::warn_impcast_float_to_integer_zero; 9124 } else { 9125 if (IntegerValue.isUnsigned()) { 9126 if (!IntegerValue.isMaxValue()) { 9127 return DiagnoseImpCast(S, E, T, CContext, 9128 diag::warn_impcast_float_integer, PruneWarnings); 9129 } 9130 } else { // IntegerValue.isSigned() 9131 if (!IntegerValue.isMaxSignedValue() && 9132 !IntegerValue.isMinSignedValue()) { 9133 return DiagnoseImpCast(S, E, T, CContext, 9134 diag::warn_impcast_float_integer, PruneWarnings); 9135 } 9136 } 9137 // Warn on evaluatable floating point expression to integer conversion. 9138 DiagID = diag::warn_impcast_float_to_integer; 9139 } 9140 9141 // FIXME: Force the precision of the source value down so we don't print 9142 // digits which are usually useless (we don't really care here if we 9143 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 9144 // would automatically print the shortest representation, but it's a bit 9145 // tricky to implement. 9146 SmallString<16> PrettySourceValue; 9147 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 9148 precision = (precision * 59 + 195) / 196; 9149 Value.toString(PrettySourceValue, precision); 9150 9151 SmallString<16> PrettyTargetValue; 9152 if (IsBool) 9153 PrettyTargetValue = Value.isZero() ? "false" : "true"; 9154 else 9155 IntegerValue.toString(PrettyTargetValue); 9156 9157 if (PruneWarnings) { 9158 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9159 S.PDiag(DiagID) 9160 << E->getType() << T.getUnqualifiedType() 9161 << PrettySourceValue << PrettyTargetValue 9162 << E->getSourceRange() << SourceRange(CContext)); 9163 } else { 9164 S.Diag(E->getExprLoc(), DiagID) 9165 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 9166 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 9167 } 9168 } 9169 9170 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 9171 if (!Range.Width) return "0"; 9172 9173 llvm::APSInt ValueInRange = Value; 9174 ValueInRange.setIsSigned(!Range.NonNegative); 9175 ValueInRange = ValueInRange.trunc(Range.Width); 9176 return ValueInRange.toString(10); 9177 } 9178 9179 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 9180 if (!isa<ImplicitCastExpr>(Ex)) 9181 return false; 9182 9183 Expr *InnerE = Ex->IgnoreParenImpCasts(); 9184 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 9185 const Type *Source = 9186 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 9187 if (Target->isDependentType()) 9188 return false; 9189 9190 const BuiltinType *FloatCandidateBT = 9191 dyn_cast<BuiltinType>(ToBool ? Source : Target); 9192 const Type *BoolCandidateType = ToBool ? Target : Source; 9193 9194 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 9195 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 9196 } 9197 9198 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 9199 SourceLocation CC) { 9200 unsigned NumArgs = TheCall->getNumArgs(); 9201 for (unsigned i = 0; i < NumArgs; ++i) { 9202 Expr *CurrA = TheCall->getArg(i); 9203 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 9204 continue; 9205 9206 bool IsSwapped = ((i > 0) && 9207 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 9208 IsSwapped |= ((i < (NumArgs - 1)) && 9209 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 9210 if (IsSwapped) { 9211 // Warn on this floating-point to bool conversion. 9212 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 9213 CurrA->getType(), CC, 9214 diag::warn_impcast_floating_point_to_bool); 9215 } 9216 } 9217 } 9218 9219 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) { 9220 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 9221 E->getExprLoc())) 9222 return; 9223 9224 // Don't warn on functions which have return type nullptr_t. 9225 if (isa<CallExpr>(E)) 9226 return; 9227 9228 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 9229 const Expr::NullPointerConstantKind NullKind = 9230 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 9231 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 9232 return; 9233 9234 // Return if target type is a safe conversion. 9235 if (T->isAnyPointerType() || T->isBlockPointerType() || 9236 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 9237 return; 9238 9239 SourceLocation Loc = E->getSourceRange().getBegin(); 9240 9241 // Venture through the macro stacks to get to the source of macro arguments. 9242 // The new location is a better location than the complete location that was 9243 // passed in. 9244 while (S.SourceMgr.isMacroArgExpansion(Loc)) 9245 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); 9246 9247 while (S.SourceMgr.isMacroArgExpansion(CC)) 9248 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); 9249 9250 // __null is usually wrapped in a macro. Go up a macro if that is the case. 9251 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 9252 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 9253 Loc, S.SourceMgr, S.getLangOpts()); 9254 if (MacroName == "NULL") 9255 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 9256 } 9257 9258 // Only warn if the null and context location are in the same macro expansion. 9259 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 9260 return; 9261 9262 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 9263 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) 9264 << FixItHint::CreateReplacement(Loc, 9265 S.getFixItZeroLiteralForType(T, Loc)); 9266 } 9267 9268 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9269 ObjCArrayLiteral *ArrayLiteral); 9270 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9271 ObjCDictionaryLiteral *DictionaryLiteral); 9272 9273 /// Check a single element within a collection literal against the 9274 /// target element type. 9275 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, 9276 Expr *Element, unsigned ElementKind) { 9277 // Skip a bitcast to 'id' or qualified 'id'. 9278 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 9279 if (ICE->getCastKind() == CK_BitCast && 9280 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 9281 Element = ICE->getSubExpr(); 9282 } 9283 9284 QualType ElementType = Element->getType(); 9285 ExprResult ElementResult(Element); 9286 if (ElementType->getAs<ObjCObjectPointerType>() && 9287 S.CheckSingleAssignmentConstraints(TargetElementType, 9288 ElementResult, 9289 false, false) 9290 != Sema::Compatible) { 9291 S.Diag(Element->getLocStart(), 9292 diag::warn_objc_collection_literal_element) 9293 << ElementType << ElementKind << TargetElementType 9294 << Element->getSourceRange(); 9295 } 9296 9297 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 9298 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 9299 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 9300 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 9301 } 9302 9303 /// Check an Objective-C array literal being converted to the given 9304 /// target type. 9305 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9306 ObjCArrayLiteral *ArrayLiteral) { 9307 if (!S.NSArrayDecl) 9308 return; 9309 9310 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9311 if (!TargetObjCPtr) 9312 return; 9313 9314 if (TargetObjCPtr->isUnspecialized() || 9315 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9316 != S.NSArrayDecl->getCanonicalDecl()) 9317 return; 9318 9319 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9320 if (TypeArgs.size() != 1) 9321 return; 9322 9323 QualType TargetElementType = TypeArgs[0]; 9324 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 9325 checkObjCCollectionLiteralElement(S, TargetElementType, 9326 ArrayLiteral->getElement(I), 9327 0); 9328 } 9329 } 9330 9331 /// Check an Objective-C dictionary literal being converted to the given 9332 /// target type. 9333 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9334 ObjCDictionaryLiteral *DictionaryLiteral) { 9335 if (!S.NSDictionaryDecl) 9336 return; 9337 9338 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9339 if (!TargetObjCPtr) 9340 return; 9341 9342 if (TargetObjCPtr->isUnspecialized() || 9343 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9344 != S.NSDictionaryDecl->getCanonicalDecl()) 9345 return; 9346 9347 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9348 if (TypeArgs.size() != 2) 9349 return; 9350 9351 QualType TargetKeyType = TypeArgs[0]; 9352 QualType TargetObjectType = TypeArgs[1]; 9353 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 9354 auto Element = DictionaryLiteral->getKeyValueElement(I); 9355 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 9356 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 9357 } 9358 } 9359 9360 // Helper function to filter out cases for constant width constant conversion. 9361 // Don't warn on char array initialization or for non-decimal values. 9362 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 9363 SourceLocation CC) { 9364 // If initializing from a constant, and the constant starts with '0', 9365 // then it is a binary, octal, or hexadecimal. Allow these constants 9366 // to fill all the bits, even if there is a sign change. 9367 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 9368 const char FirstLiteralCharacter = 9369 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 9370 if (FirstLiteralCharacter == '0') 9371 return false; 9372 } 9373 9374 // If the CC location points to a '{', and the type is char, then assume 9375 // assume it is an array initialization. 9376 if (CC.isValid() && T->isCharType()) { 9377 const char FirstContextCharacter = 9378 S.getSourceManager().getCharacterData(CC)[0]; 9379 if (FirstContextCharacter == '{') 9380 return false; 9381 } 9382 9383 return true; 9384 } 9385 9386 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 9387 SourceLocation CC, bool *ICContext = nullptr) { 9388 if (E->isTypeDependent() || E->isValueDependent()) return; 9389 9390 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 9391 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 9392 if (Source == Target) return; 9393 if (Target->isDependentType()) return; 9394 9395 // If the conversion context location is invalid don't complain. We also 9396 // don't want to emit a warning if the issue occurs from the expansion of 9397 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 9398 // delay this check as long as possible. Once we detect we are in that 9399 // scenario, we just return. 9400 if (CC.isInvalid()) 9401 return; 9402 9403 // Diagnose implicit casts to bool. 9404 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 9405 if (isa<StringLiteral>(E)) 9406 // Warn on string literal to bool. Checks for string literals in logical 9407 // and expressions, for instance, assert(0 && "error here"), are 9408 // prevented by a check in AnalyzeImplicitConversions(). 9409 return DiagnoseImpCast(S, E, T, CC, 9410 diag::warn_impcast_string_literal_to_bool); 9411 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 9412 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 9413 // This covers the literal expressions that evaluate to Objective-C 9414 // objects. 9415 return DiagnoseImpCast(S, E, T, CC, 9416 diag::warn_impcast_objective_c_literal_to_bool); 9417 } 9418 if (Source->isPointerType() || Source->canDecayToPointerType()) { 9419 // Warn on pointer to bool conversion that is always true. 9420 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 9421 SourceRange(CC)); 9422 } 9423 } 9424 9425 // Check implicit casts from Objective-C collection literals to specialized 9426 // collection types, e.g., NSArray<NSString *> *. 9427 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 9428 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 9429 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 9430 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 9431 9432 // Strip vector types. 9433 if (isa<VectorType>(Source)) { 9434 if (!isa<VectorType>(Target)) { 9435 if (S.SourceMgr.isInSystemMacro(CC)) 9436 return; 9437 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 9438 } 9439 9440 // If the vector cast is cast between two vectors of the same size, it is 9441 // a bitcast, not a conversion. 9442 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 9443 return; 9444 9445 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 9446 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 9447 } 9448 if (auto VecTy = dyn_cast<VectorType>(Target)) 9449 Target = VecTy->getElementType().getTypePtr(); 9450 9451 // Strip complex types. 9452 if (isa<ComplexType>(Source)) { 9453 if (!isa<ComplexType>(Target)) { 9454 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 9455 return; 9456 9457 return DiagnoseImpCast(S, E, T, CC, 9458 S.getLangOpts().CPlusPlus 9459 ? diag::err_impcast_complex_scalar 9460 : diag::warn_impcast_complex_scalar); 9461 } 9462 9463 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 9464 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 9465 } 9466 9467 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 9468 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 9469 9470 // If the source is floating point... 9471 if (SourceBT && SourceBT->isFloatingPoint()) { 9472 // ...and the target is floating point... 9473 if (TargetBT && TargetBT->isFloatingPoint()) { 9474 // ...then warn if we're dropping FP rank. 9475 9476 // Builtin FP kinds are ordered by increasing FP rank. 9477 if (SourceBT->getKind() > TargetBT->getKind()) { 9478 // Don't warn about float constants that are precisely 9479 // representable in the target type. 9480 Expr::EvalResult result; 9481 if (E->EvaluateAsRValue(result, S.Context)) { 9482 // Value might be a float, a float vector, or a float complex. 9483 if (IsSameFloatAfterCast(result.Val, 9484 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 9485 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 9486 return; 9487 } 9488 9489 if (S.SourceMgr.isInSystemMacro(CC)) 9490 return; 9491 9492 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 9493 } 9494 // ... or possibly if we're increasing rank, too 9495 else if (TargetBT->getKind() > SourceBT->getKind()) { 9496 if (S.SourceMgr.isInSystemMacro(CC)) 9497 return; 9498 9499 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 9500 } 9501 return; 9502 } 9503 9504 // If the target is integral, always warn. 9505 if (TargetBT && TargetBT->isInteger()) { 9506 if (S.SourceMgr.isInSystemMacro(CC)) 9507 return; 9508 9509 DiagnoseFloatingImpCast(S, E, T, CC); 9510 } 9511 9512 // Detect the case where a call result is converted from floating-point to 9513 // to bool, and the final argument to the call is converted from bool, to 9514 // discover this typo: 9515 // 9516 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 9517 // 9518 // FIXME: This is an incredibly special case; is there some more general 9519 // way to detect this class of misplaced-parentheses bug? 9520 if (Target->isBooleanType() && isa<CallExpr>(E)) { 9521 // Check last argument of function call to see if it is an 9522 // implicit cast from a type matching the type the result 9523 // is being cast to. 9524 CallExpr *CEx = cast<CallExpr>(E); 9525 if (unsigned NumArgs = CEx->getNumArgs()) { 9526 Expr *LastA = CEx->getArg(NumArgs - 1); 9527 Expr *InnerE = LastA->IgnoreParenImpCasts(); 9528 if (isa<ImplicitCastExpr>(LastA) && 9529 InnerE->getType()->isBooleanType()) { 9530 // Warn on this floating-point to bool conversion 9531 DiagnoseImpCast(S, E, T, CC, 9532 diag::warn_impcast_floating_point_to_bool); 9533 } 9534 } 9535 } 9536 return; 9537 } 9538 9539 DiagnoseNullConversion(S, E, T, CC); 9540 9541 S.DiscardMisalignedMemberAddress(Target, E); 9542 9543 if (!Source->isIntegerType() || !Target->isIntegerType()) 9544 return; 9545 9546 // TODO: remove this early return once the false positives for constant->bool 9547 // in templates, macros, etc, are reduced or removed. 9548 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 9549 return; 9550 9551 IntRange SourceRange = GetExprRange(S.Context, E); 9552 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 9553 9554 if (SourceRange.Width > TargetRange.Width) { 9555 // If the source is a constant, use a default-on diagnostic. 9556 // TODO: this should happen for bitfield stores, too. 9557 llvm::APSInt Value(32); 9558 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 9559 if (S.SourceMgr.isInSystemMacro(CC)) 9560 return; 9561 9562 std::string PrettySourceValue = Value.toString(10); 9563 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9564 9565 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9566 S.PDiag(diag::warn_impcast_integer_precision_constant) 9567 << PrettySourceValue << PrettyTargetValue 9568 << E->getType() << T << E->getSourceRange() 9569 << clang::SourceRange(CC)); 9570 return; 9571 } 9572 9573 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 9574 if (S.SourceMgr.isInSystemMacro(CC)) 9575 return; 9576 9577 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 9578 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 9579 /* pruneControlFlow */ true); 9580 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 9581 } 9582 9583 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 9584 SourceRange.NonNegative && Source->isSignedIntegerType()) { 9585 // Warn when doing a signed to signed conversion, warn if the positive 9586 // source value is exactly the width of the target type, which will 9587 // cause a negative value to be stored. 9588 9589 llvm::APSInt Value; 9590 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 9591 !S.SourceMgr.isInSystemMacro(CC)) { 9592 if (isSameWidthConstantConversion(S, E, T, CC)) { 9593 std::string PrettySourceValue = Value.toString(10); 9594 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9595 9596 S.DiagRuntimeBehavior( 9597 E->getExprLoc(), E, 9598 S.PDiag(diag::warn_impcast_integer_precision_constant) 9599 << PrettySourceValue << PrettyTargetValue << E->getType() << T 9600 << E->getSourceRange() << clang::SourceRange(CC)); 9601 return; 9602 } 9603 } 9604 9605 // Fall through for non-constants to give a sign conversion warning. 9606 } 9607 9608 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 9609 (!TargetRange.NonNegative && SourceRange.NonNegative && 9610 SourceRange.Width == TargetRange.Width)) { 9611 if (S.SourceMgr.isInSystemMacro(CC)) 9612 return; 9613 9614 unsigned DiagID = diag::warn_impcast_integer_sign; 9615 9616 // Traditionally, gcc has warned about this under -Wsign-compare. 9617 // We also want to warn about it in -Wconversion. 9618 // So if -Wconversion is off, use a completely identical diagnostic 9619 // in the sign-compare group. 9620 // The conditional-checking code will 9621 if (ICContext) { 9622 DiagID = diag::warn_impcast_integer_sign_conditional; 9623 *ICContext = true; 9624 } 9625 9626 return DiagnoseImpCast(S, E, T, CC, DiagID); 9627 } 9628 9629 // Diagnose conversions between different enumeration types. 9630 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 9631 // type, to give us better diagnostics. 9632 QualType SourceType = E->getType(); 9633 if (!S.getLangOpts().CPlusPlus) { 9634 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9635 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 9636 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 9637 SourceType = S.Context.getTypeDeclType(Enum); 9638 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 9639 } 9640 } 9641 9642 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 9643 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 9644 if (SourceEnum->getDecl()->hasNameForLinkage() && 9645 TargetEnum->getDecl()->hasNameForLinkage() && 9646 SourceEnum != TargetEnum) { 9647 if (S.SourceMgr.isInSystemMacro(CC)) 9648 return; 9649 9650 return DiagnoseImpCast(S, E, SourceType, T, CC, 9651 diag::warn_impcast_different_enum_types); 9652 } 9653 } 9654 9655 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9656 SourceLocation CC, QualType T); 9657 9658 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 9659 SourceLocation CC, bool &ICContext) { 9660 E = E->IgnoreParenImpCasts(); 9661 9662 if (isa<ConditionalOperator>(E)) 9663 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 9664 9665 AnalyzeImplicitConversions(S, E, CC); 9666 if (E->getType() != T) 9667 return CheckImplicitConversion(S, E, T, CC, &ICContext); 9668 } 9669 9670 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9671 SourceLocation CC, QualType T) { 9672 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 9673 9674 bool Suspicious = false; 9675 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 9676 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 9677 9678 // If -Wconversion would have warned about either of the candidates 9679 // for a signedness conversion to the context type... 9680 if (!Suspicious) return; 9681 9682 // ...but it's currently ignored... 9683 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 9684 return; 9685 9686 // ...then check whether it would have warned about either of the 9687 // candidates for a signedness conversion to the condition type. 9688 if (E->getType() == T) return; 9689 9690 Suspicious = false; 9691 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 9692 E->getType(), CC, &Suspicious); 9693 if (!Suspicious) 9694 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 9695 E->getType(), CC, &Suspicious); 9696 } 9697 9698 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9699 /// Input argument E is a logical expression. 9700 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 9701 if (S.getLangOpts().Bool) 9702 return; 9703 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 9704 } 9705 9706 /// AnalyzeImplicitConversions - Find and report any interesting 9707 /// implicit conversions in the given expression. There are a couple 9708 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 9709 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 9710 QualType T = OrigE->getType(); 9711 Expr *E = OrigE->IgnoreParenImpCasts(); 9712 9713 if (E->isTypeDependent() || E->isValueDependent()) 9714 return; 9715 9716 // For conditional operators, we analyze the arguments as if they 9717 // were being fed directly into the output. 9718 if (isa<ConditionalOperator>(E)) { 9719 ConditionalOperator *CO = cast<ConditionalOperator>(E); 9720 CheckConditionalOperator(S, CO, CC, T); 9721 return; 9722 } 9723 9724 // Check implicit argument conversions for function calls. 9725 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 9726 CheckImplicitArgumentConversions(S, Call, CC); 9727 9728 // Go ahead and check any implicit conversions we might have skipped. 9729 // The non-canonical typecheck is just an optimization; 9730 // CheckImplicitConversion will filter out dead implicit conversions. 9731 if (E->getType() != T) 9732 CheckImplicitConversion(S, E, T, CC); 9733 9734 // Now continue drilling into this expression. 9735 9736 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 9737 // The bound subexpressions in a PseudoObjectExpr are not reachable 9738 // as transitive children. 9739 // FIXME: Use a more uniform representation for this. 9740 for (auto *SE : POE->semantics()) 9741 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 9742 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 9743 } 9744 9745 // Skip past explicit casts. 9746 if (isa<ExplicitCastExpr>(E)) { 9747 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 9748 return AnalyzeImplicitConversions(S, E, CC); 9749 } 9750 9751 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9752 // Do a somewhat different check with comparison operators. 9753 if (BO->isComparisonOp()) 9754 return AnalyzeComparison(S, BO); 9755 9756 // And with simple assignments. 9757 if (BO->getOpcode() == BO_Assign) 9758 return AnalyzeAssignment(S, BO); 9759 } 9760 9761 // These break the otherwise-useful invariant below. Fortunately, 9762 // we don't really need to recurse into them, because any internal 9763 // expressions should have been analyzed already when they were 9764 // built into statements. 9765 if (isa<StmtExpr>(E)) return; 9766 9767 // Don't descend into unevaluated contexts. 9768 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 9769 9770 // Now just recurse over the expression's children. 9771 CC = E->getExprLoc(); 9772 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 9773 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 9774 for (Stmt *SubStmt : E->children()) { 9775 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 9776 if (!ChildExpr) 9777 continue; 9778 9779 if (IsLogicalAndOperator && 9780 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 9781 // Ignore checking string literals that are in logical and operators. 9782 // This is a common pattern for asserts. 9783 continue; 9784 AnalyzeImplicitConversions(S, ChildExpr, CC); 9785 } 9786 9787 if (BO && BO->isLogicalOp()) { 9788 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 9789 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9790 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9791 9792 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 9793 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9794 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9795 } 9796 9797 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 9798 if (U->getOpcode() == UO_LNot) 9799 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 9800 } 9801 9802 } // end anonymous namespace 9803 9804 /// Diagnose integer type and any valid implicit convertion to it. 9805 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 9806 // Taking into account implicit conversions, 9807 // allow any integer. 9808 if (!E->getType()->isIntegerType()) { 9809 S.Diag(E->getLocStart(), 9810 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 9811 return true; 9812 } 9813 // Potentially emit standard warnings for implicit conversions if enabled 9814 // using -Wconversion. 9815 CheckImplicitConversion(S, E, IntT, E->getLocStart()); 9816 return false; 9817 } 9818 9819 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 9820 // Returns true when emitting a warning about taking the address of a reference. 9821 static bool CheckForReference(Sema &SemaRef, const Expr *E, 9822 const PartialDiagnostic &PD) { 9823 E = E->IgnoreParenImpCasts(); 9824 9825 const FunctionDecl *FD = nullptr; 9826 9827 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9828 if (!DRE->getDecl()->getType()->isReferenceType()) 9829 return false; 9830 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9831 if (!M->getMemberDecl()->getType()->isReferenceType()) 9832 return false; 9833 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 9834 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 9835 return false; 9836 FD = Call->getDirectCallee(); 9837 } else { 9838 return false; 9839 } 9840 9841 SemaRef.Diag(E->getExprLoc(), PD); 9842 9843 // If possible, point to location of function. 9844 if (FD) { 9845 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 9846 } 9847 9848 return true; 9849 } 9850 9851 // Returns true if the SourceLocation is expanded from any macro body. 9852 // Returns false if the SourceLocation is invalid, is from not in a macro 9853 // expansion, or is from expanded from a top-level macro argument. 9854 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 9855 if (Loc.isInvalid()) 9856 return false; 9857 9858 while (Loc.isMacroID()) { 9859 if (SM.isMacroBodyExpansion(Loc)) 9860 return true; 9861 Loc = SM.getImmediateMacroCallerLoc(Loc); 9862 } 9863 9864 return false; 9865 } 9866 9867 /// \brief Diagnose pointers that are always non-null. 9868 /// \param E the expression containing the pointer 9869 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 9870 /// compared to a null pointer 9871 /// \param IsEqual True when the comparison is equal to a null pointer 9872 /// \param Range Extra SourceRange to highlight in the diagnostic 9873 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 9874 Expr::NullPointerConstantKind NullKind, 9875 bool IsEqual, SourceRange Range) { 9876 if (!E) 9877 return; 9878 9879 // Don't warn inside macros. 9880 if (E->getExprLoc().isMacroID()) { 9881 const SourceManager &SM = getSourceManager(); 9882 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 9883 IsInAnyMacroBody(SM, Range.getBegin())) 9884 return; 9885 } 9886 E = E->IgnoreImpCasts(); 9887 9888 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 9889 9890 if (isa<CXXThisExpr>(E)) { 9891 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 9892 : diag::warn_this_bool_conversion; 9893 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 9894 return; 9895 } 9896 9897 bool IsAddressOf = false; 9898 9899 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9900 if (UO->getOpcode() != UO_AddrOf) 9901 return; 9902 IsAddressOf = true; 9903 E = UO->getSubExpr(); 9904 } 9905 9906 if (IsAddressOf) { 9907 unsigned DiagID = IsCompare 9908 ? diag::warn_address_of_reference_null_compare 9909 : diag::warn_address_of_reference_bool_conversion; 9910 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 9911 << IsEqual; 9912 if (CheckForReference(*this, E, PD)) { 9913 return; 9914 } 9915 } 9916 9917 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 9918 bool IsParam = isa<NonNullAttr>(NonnullAttr); 9919 std::string Str; 9920 llvm::raw_string_ostream S(Str); 9921 E->printPretty(S, nullptr, getPrintingPolicy()); 9922 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 9923 : diag::warn_cast_nonnull_to_bool; 9924 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 9925 << E->getSourceRange() << Range << IsEqual; 9926 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 9927 }; 9928 9929 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 9930 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 9931 if (auto *Callee = Call->getDirectCallee()) { 9932 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 9933 ComplainAboutNonnullParamOrCall(A); 9934 return; 9935 } 9936 } 9937 } 9938 9939 // Expect to find a single Decl. Skip anything more complicated. 9940 ValueDecl *D = nullptr; 9941 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 9942 D = R->getDecl(); 9943 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9944 D = M->getMemberDecl(); 9945 } 9946 9947 // Weak Decls can be null. 9948 if (!D || D->isWeak()) 9949 return; 9950 9951 // Check for parameter decl with nonnull attribute 9952 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 9953 if (getCurFunction() && 9954 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 9955 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 9956 ComplainAboutNonnullParamOrCall(A); 9957 return; 9958 } 9959 9960 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 9961 auto ParamIter = llvm::find(FD->parameters(), PV); 9962 assert(ParamIter != FD->param_end()); 9963 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 9964 9965 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 9966 if (!NonNull->args_size()) { 9967 ComplainAboutNonnullParamOrCall(NonNull); 9968 return; 9969 } 9970 9971 for (unsigned ArgNo : NonNull->args()) { 9972 if (ArgNo == ParamNo) { 9973 ComplainAboutNonnullParamOrCall(NonNull); 9974 return; 9975 } 9976 } 9977 } 9978 } 9979 } 9980 } 9981 9982 QualType T = D->getType(); 9983 const bool IsArray = T->isArrayType(); 9984 const bool IsFunction = T->isFunctionType(); 9985 9986 // Address of function is used to silence the function warning. 9987 if (IsAddressOf && IsFunction) { 9988 return; 9989 } 9990 9991 // Found nothing. 9992 if (!IsAddressOf && !IsFunction && !IsArray) 9993 return; 9994 9995 // Pretty print the expression for the diagnostic. 9996 std::string Str; 9997 llvm::raw_string_ostream S(Str); 9998 E->printPretty(S, nullptr, getPrintingPolicy()); 9999 10000 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 10001 : diag::warn_impcast_pointer_to_bool; 10002 enum { 10003 AddressOf, 10004 FunctionPointer, 10005 ArrayPointer 10006 } DiagType; 10007 if (IsAddressOf) 10008 DiagType = AddressOf; 10009 else if (IsFunction) 10010 DiagType = FunctionPointer; 10011 else if (IsArray) 10012 DiagType = ArrayPointer; 10013 else 10014 llvm_unreachable("Could not determine diagnostic."); 10015 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 10016 << Range << IsEqual; 10017 10018 if (!IsFunction) 10019 return; 10020 10021 // Suggest '&' to silence the function warning. 10022 Diag(E->getExprLoc(), diag::note_function_warning_silence) 10023 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 10024 10025 // Check to see if '()' fixit should be emitted. 10026 QualType ReturnType; 10027 UnresolvedSet<4> NonTemplateOverloads; 10028 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 10029 if (ReturnType.isNull()) 10030 return; 10031 10032 if (IsCompare) { 10033 // There are two cases here. If there is null constant, the only suggest 10034 // for a pointer return type. If the null is 0, then suggest if the return 10035 // type is a pointer or an integer type. 10036 if (!ReturnType->isPointerType()) { 10037 if (NullKind == Expr::NPCK_ZeroExpression || 10038 NullKind == Expr::NPCK_ZeroLiteral) { 10039 if (!ReturnType->isIntegerType()) 10040 return; 10041 } else { 10042 return; 10043 } 10044 } 10045 } else { // !IsCompare 10046 // For function to bool, only suggest if the function pointer has bool 10047 // return type. 10048 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 10049 return; 10050 } 10051 Diag(E->getExprLoc(), diag::note_function_to_function_call) 10052 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 10053 } 10054 10055 /// Diagnoses "dangerous" implicit conversions within the given 10056 /// expression (which is a full expression). Implements -Wconversion 10057 /// and -Wsign-compare. 10058 /// 10059 /// \param CC the "context" location of the implicit conversion, i.e. 10060 /// the most location of the syntactic entity requiring the implicit 10061 /// conversion 10062 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 10063 // Don't diagnose in unevaluated contexts. 10064 if (isUnevaluatedContext()) 10065 return; 10066 10067 // Don't diagnose for value- or type-dependent expressions. 10068 if (E->isTypeDependent() || E->isValueDependent()) 10069 return; 10070 10071 // Check for array bounds violations in cases where the check isn't triggered 10072 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 10073 // ArraySubscriptExpr is on the RHS of a variable initialization. 10074 CheckArrayAccess(E); 10075 10076 // This is not the right CC for (e.g.) a variable initialization. 10077 AnalyzeImplicitConversions(*this, E, CC); 10078 } 10079 10080 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10081 /// Input argument E is a logical expression. 10082 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 10083 ::CheckBoolLikeConversion(*this, E, CC); 10084 } 10085 10086 /// Diagnose when expression is an integer constant expression and its evaluation 10087 /// results in integer overflow 10088 void Sema::CheckForIntOverflow (Expr *E) { 10089 // Use a work list to deal with nested struct initializers. 10090 SmallVector<Expr *, 2> Exprs(1, E); 10091 10092 do { 10093 Expr *E = Exprs.pop_back_val(); 10094 10095 if (isa<BinaryOperator>(E->IgnoreParenCasts())) { 10096 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 10097 continue; 10098 } 10099 10100 if (auto InitList = dyn_cast<InitListExpr>(E)) 10101 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 10102 10103 if (isa<ObjCBoxedExpr>(E)) 10104 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 10105 } while (!Exprs.empty()); 10106 } 10107 10108 namespace { 10109 /// \brief Visitor for expressions which looks for unsequenced operations on the 10110 /// same object. 10111 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 10112 typedef EvaluatedExprVisitor<SequenceChecker> Base; 10113 10114 /// \brief A tree of sequenced regions within an expression. Two regions are 10115 /// unsequenced if one is an ancestor or a descendent of the other. When we 10116 /// finish processing an expression with sequencing, such as a comma 10117 /// expression, we fold its tree nodes into its parent, since they are 10118 /// unsequenced with respect to nodes we will visit later. 10119 class SequenceTree { 10120 struct Value { 10121 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 10122 unsigned Parent : 31; 10123 unsigned Merged : 1; 10124 }; 10125 SmallVector<Value, 8> Values; 10126 10127 public: 10128 /// \brief A region within an expression which may be sequenced with respect 10129 /// to some other region. 10130 class Seq { 10131 explicit Seq(unsigned N) : Index(N) {} 10132 unsigned Index; 10133 friend class SequenceTree; 10134 public: 10135 Seq() : Index(0) {} 10136 }; 10137 10138 SequenceTree() { Values.push_back(Value(0)); } 10139 Seq root() const { return Seq(0); } 10140 10141 /// \brief Create a new sequence of operations, which is an unsequenced 10142 /// subset of \p Parent. This sequence of operations is sequenced with 10143 /// respect to other children of \p Parent. 10144 Seq allocate(Seq Parent) { 10145 Values.push_back(Value(Parent.Index)); 10146 return Seq(Values.size() - 1); 10147 } 10148 10149 /// \brief Merge a sequence of operations into its parent. 10150 void merge(Seq S) { 10151 Values[S.Index].Merged = true; 10152 } 10153 10154 /// \brief Determine whether two operations are unsequenced. This operation 10155 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 10156 /// should have been merged into its parent as appropriate. 10157 bool isUnsequenced(Seq Cur, Seq Old) { 10158 unsigned C = representative(Cur.Index); 10159 unsigned Target = representative(Old.Index); 10160 while (C >= Target) { 10161 if (C == Target) 10162 return true; 10163 C = Values[C].Parent; 10164 } 10165 return false; 10166 } 10167 10168 private: 10169 /// \brief Pick a representative for a sequence. 10170 unsigned representative(unsigned K) { 10171 if (Values[K].Merged) 10172 // Perform path compression as we go. 10173 return Values[K].Parent = representative(Values[K].Parent); 10174 return K; 10175 } 10176 }; 10177 10178 /// An object for which we can track unsequenced uses. 10179 typedef NamedDecl *Object; 10180 10181 /// Different flavors of object usage which we track. We only track the 10182 /// least-sequenced usage of each kind. 10183 enum UsageKind { 10184 /// A read of an object. Multiple unsequenced reads are OK. 10185 UK_Use, 10186 /// A modification of an object which is sequenced before the value 10187 /// computation of the expression, such as ++n in C++. 10188 UK_ModAsValue, 10189 /// A modification of an object which is not sequenced before the value 10190 /// computation of the expression, such as n++. 10191 UK_ModAsSideEffect, 10192 10193 UK_Count = UK_ModAsSideEffect + 1 10194 }; 10195 10196 struct Usage { 10197 Usage() : Use(nullptr), Seq() {} 10198 Expr *Use; 10199 SequenceTree::Seq Seq; 10200 }; 10201 10202 struct UsageInfo { 10203 UsageInfo() : Diagnosed(false) {} 10204 Usage Uses[UK_Count]; 10205 /// Have we issued a diagnostic for this variable already? 10206 bool Diagnosed; 10207 }; 10208 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 10209 10210 Sema &SemaRef; 10211 /// Sequenced regions within the expression. 10212 SequenceTree Tree; 10213 /// Declaration modifications and references which we have seen. 10214 UsageInfoMap UsageMap; 10215 /// The region we are currently within. 10216 SequenceTree::Seq Region; 10217 /// Filled in with declarations which were modified as a side-effect 10218 /// (that is, post-increment operations). 10219 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 10220 /// Expressions to check later. We defer checking these to reduce 10221 /// stack usage. 10222 SmallVectorImpl<Expr *> &WorkList; 10223 10224 /// RAII object wrapping the visitation of a sequenced subexpression of an 10225 /// expression. At the end of this process, the side-effects of the evaluation 10226 /// become sequenced with respect to the value computation of the result, so 10227 /// we downgrade any UK_ModAsSideEffect within the evaluation to 10228 /// UK_ModAsValue. 10229 struct SequencedSubexpression { 10230 SequencedSubexpression(SequenceChecker &Self) 10231 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 10232 Self.ModAsSideEffect = &ModAsSideEffect; 10233 } 10234 ~SequencedSubexpression() { 10235 for (auto &M : llvm::reverse(ModAsSideEffect)) { 10236 UsageInfo &U = Self.UsageMap[M.first]; 10237 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 10238 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 10239 SideEffectUsage = M.second; 10240 } 10241 Self.ModAsSideEffect = OldModAsSideEffect; 10242 } 10243 10244 SequenceChecker &Self; 10245 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 10246 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 10247 }; 10248 10249 /// RAII object wrapping the visitation of a subexpression which we might 10250 /// choose to evaluate as a constant. If any subexpression is evaluated and 10251 /// found to be non-constant, this allows us to suppress the evaluation of 10252 /// the outer expression. 10253 class EvaluationTracker { 10254 public: 10255 EvaluationTracker(SequenceChecker &Self) 10256 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 10257 Self.EvalTracker = this; 10258 } 10259 ~EvaluationTracker() { 10260 Self.EvalTracker = Prev; 10261 if (Prev) 10262 Prev->EvalOK &= EvalOK; 10263 } 10264 10265 bool evaluate(const Expr *E, bool &Result) { 10266 if (!EvalOK || E->isValueDependent()) 10267 return false; 10268 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 10269 return EvalOK; 10270 } 10271 10272 private: 10273 SequenceChecker &Self; 10274 EvaluationTracker *Prev; 10275 bool EvalOK; 10276 } *EvalTracker; 10277 10278 /// \brief Find the object which is produced by the specified expression, 10279 /// if any. 10280 Object getObject(Expr *E, bool Mod) const { 10281 E = E->IgnoreParenCasts(); 10282 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10283 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 10284 return getObject(UO->getSubExpr(), Mod); 10285 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10286 if (BO->getOpcode() == BO_Comma) 10287 return getObject(BO->getRHS(), Mod); 10288 if (Mod && BO->isAssignmentOp()) 10289 return getObject(BO->getLHS(), Mod); 10290 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10291 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 10292 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 10293 return ME->getMemberDecl(); 10294 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10295 // FIXME: If this is a reference, map through to its value. 10296 return DRE->getDecl(); 10297 return nullptr; 10298 } 10299 10300 /// \brief Note that an object was modified or used by an expression. 10301 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 10302 Usage &U = UI.Uses[UK]; 10303 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 10304 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 10305 ModAsSideEffect->push_back(std::make_pair(O, U)); 10306 U.Use = Ref; 10307 U.Seq = Region; 10308 } 10309 } 10310 /// \brief Check whether a modification or use conflicts with a prior usage. 10311 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 10312 bool IsModMod) { 10313 if (UI.Diagnosed) 10314 return; 10315 10316 const Usage &U = UI.Uses[OtherKind]; 10317 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 10318 return; 10319 10320 Expr *Mod = U.Use; 10321 Expr *ModOrUse = Ref; 10322 if (OtherKind == UK_Use) 10323 std::swap(Mod, ModOrUse); 10324 10325 SemaRef.Diag(Mod->getExprLoc(), 10326 IsModMod ? diag::warn_unsequenced_mod_mod 10327 : diag::warn_unsequenced_mod_use) 10328 << O << SourceRange(ModOrUse->getExprLoc()); 10329 UI.Diagnosed = true; 10330 } 10331 10332 void notePreUse(Object O, Expr *Use) { 10333 UsageInfo &U = UsageMap[O]; 10334 // Uses conflict with other modifications. 10335 checkUsage(O, U, Use, UK_ModAsValue, false); 10336 } 10337 void notePostUse(Object O, Expr *Use) { 10338 UsageInfo &U = UsageMap[O]; 10339 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 10340 addUsage(U, O, Use, UK_Use); 10341 } 10342 10343 void notePreMod(Object O, Expr *Mod) { 10344 UsageInfo &U = UsageMap[O]; 10345 // Modifications conflict with other modifications and with uses. 10346 checkUsage(O, U, Mod, UK_ModAsValue, true); 10347 checkUsage(O, U, Mod, UK_Use, false); 10348 } 10349 void notePostMod(Object O, Expr *Use, UsageKind UK) { 10350 UsageInfo &U = UsageMap[O]; 10351 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 10352 addUsage(U, O, Use, UK); 10353 } 10354 10355 public: 10356 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 10357 : Base(S.Context), SemaRef(S), Region(Tree.root()), 10358 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 10359 Visit(E); 10360 } 10361 10362 void VisitStmt(Stmt *S) { 10363 // Skip all statements which aren't expressions for now. 10364 } 10365 10366 void VisitExpr(Expr *E) { 10367 // By default, just recurse to evaluated subexpressions. 10368 Base::VisitStmt(E); 10369 } 10370 10371 void VisitCastExpr(CastExpr *E) { 10372 Object O = Object(); 10373 if (E->getCastKind() == CK_LValueToRValue) 10374 O = getObject(E->getSubExpr(), false); 10375 10376 if (O) 10377 notePreUse(O, E); 10378 VisitExpr(E); 10379 if (O) 10380 notePostUse(O, E); 10381 } 10382 10383 void VisitBinComma(BinaryOperator *BO) { 10384 // C++11 [expr.comma]p1: 10385 // Every value computation and side effect associated with the left 10386 // expression is sequenced before every value computation and side 10387 // effect associated with the right expression. 10388 SequenceTree::Seq LHS = Tree.allocate(Region); 10389 SequenceTree::Seq RHS = Tree.allocate(Region); 10390 SequenceTree::Seq OldRegion = Region; 10391 10392 { 10393 SequencedSubexpression SeqLHS(*this); 10394 Region = LHS; 10395 Visit(BO->getLHS()); 10396 } 10397 10398 Region = RHS; 10399 Visit(BO->getRHS()); 10400 10401 Region = OldRegion; 10402 10403 // Forget that LHS and RHS are sequenced. They are both unsequenced 10404 // with respect to other stuff. 10405 Tree.merge(LHS); 10406 Tree.merge(RHS); 10407 } 10408 10409 void VisitBinAssign(BinaryOperator *BO) { 10410 // The modification is sequenced after the value computation of the LHS 10411 // and RHS, so check it before inspecting the operands and update the 10412 // map afterwards. 10413 Object O = getObject(BO->getLHS(), true); 10414 if (!O) 10415 return VisitExpr(BO); 10416 10417 notePreMod(O, BO); 10418 10419 // C++11 [expr.ass]p7: 10420 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 10421 // only once. 10422 // 10423 // Therefore, for a compound assignment operator, O is considered used 10424 // everywhere except within the evaluation of E1 itself. 10425 if (isa<CompoundAssignOperator>(BO)) 10426 notePreUse(O, BO); 10427 10428 Visit(BO->getLHS()); 10429 10430 if (isa<CompoundAssignOperator>(BO)) 10431 notePostUse(O, BO); 10432 10433 Visit(BO->getRHS()); 10434 10435 // C++11 [expr.ass]p1: 10436 // the assignment is sequenced [...] before the value computation of the 10437 // assignment expression. 10438 // C11 6.5.16/3 has no such rule. 10439 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10440 : UK_ModAsSideEffect); 10441 } 10442 10443 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 10444 VisitBinAssign(CAO); 10445 } 10446 10447 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10448 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10449 void VisitUnaryPreIncDec(UnaryOperator *UO) { 10450 Object O = getObject(UO->getSubExpr(), true); 10451 if (!O) 10452 return VisitExpr(UO); 10453 10454 notePreMod(O, UO); 10455 Visit(UO->getSubExpr()); 10456 // C++11 [expr.pre.incr]p1: 10457 // the expression ++x is equivalent to x+=1 10458 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10459 : UK_ModAsSideEffect); 10460 } 10461 10462 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10463 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10464 void VisitUnaryPostIncDec(UnaryOperator *UO) { 10465 Object O = getObject(UO->getSubExpr(), true); 10466 if (!O) 10467 return VisitExpr(UO); 10468 10469 notePreMod(O, UO); 10470 Visit(UO->getSubExpr()); 10471 notePostMod(O, UO, UK_ModAsSideEffect); 10472 } 10473 10474 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 10475 void VisitBinLOr(BinaryOperator *BO) { 10476 // The side-effects of the LHS of an '&&' are sequenced before the 10477 // value computation of the RHS, and hence before the value computation 10478 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 10479 // as if they were unconditionally sequenced. 10480 EvaluationTracker Eval(*this); 10481 { 10482 SequencedSubexpression Sequenced(*this); 10483 Visit(BO->getLHS()); 10484 } 10485 10486 bool Result; 10487 if (Eval.evaluate(BO->getLHS(), Result)) { 10488 if (!Result) 10489 Visit(BO->getRHS()); 10490 } else { 10491 // Check for unsequenced operations in the RHS, treating it as an 10492 // entirely separate evaluation. 10493 // 10494 // FIXME: If there are operations in the RHS which are unsequenced 10495 // with respect to operations outside the RHS, and those operations 10496 // are unconditionally evaluated, diagnose them. 10497 WorkList.push_back(BO->getRHS()); 10498 } 10499 } 10500 void VisitBinLAnd(BinaryOperator *BO) { 10501 EvaluationTracker Eval(*this); 10502 { 10503 SequencedSubexpression Sequenced(*this); 10504 Visit(BO->getLHS()); 10505 } 10506 10507 bool Result; 10508 if (Eval.evaluate(BO->getLHS(), Result)) { 10509 if (Result) 10510 Visit(BO->getRHS()); 10511 } else { 10512 WorkList.push_back(BO->getRHS()); 10513 } 10514 } 10515 10516 // Only visit the condition, unless we can be sure which subexpression will 10517 // be chosen. 10518 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 10519 EvaluationTracker Eval(*this); 10520 { 10521 SequencedSubexpression Sequenced(*this); 10522 Visit(CO->getCond()); 10523 } 10524 10525 bool Result; 10526 if (Eval.evaluate(CO->getCond(), Result)) 10527 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 10528 else { 10529 WorkList.push_back(CO->getTrueExpr()); 10530 WorkList.push_back(CO->getFalseExpr()); 10531 } 10532 } 10533 10534 void VisitCallExpr(CallExpr *CE) { 10535 // C++11 [intro.execution]p15: 10536 // When calling a function [...], every value computation and side effect 10537 // associated with any argument expression, or with the postfix expression 10538 // designating the called function, is sequenced before execution of every 10539 // expression or statement in the body of the function [and thus before 10540 // the value computation of its result]. 10541 SequencedSubexpression Sequenced(*this); 10542 Base::VisitCallExpr(CE); 10543 10544 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 10545 } 10546 10547 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 10548 // This is a call, so all subexpressions are sequenced before the result. 10549 SequencedSubexpression Sequenced(*this); 10550 10551 if (!CCE->isListInitialization()) 10552 return VisitExpr(CCE); 10553 10554 // In C++11, list initializations are sequenced. 10555 SmallVector<SequenceTree::Seq, 32> Elts; 10556 SequenceTree::Seq Parent = Region; 10557 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 10558 E = CCE->arg_end(); 10559 I != E; ++I) { 10560 Region = Tree.allocate(Parent); 10561 Elts.push_back(Region); 10562 Visit(*I); 10563 } 10564 10565 // Forget that the initializers are sequenced. 10566 Region = Parent; 10567 for (unsigned I = 0; I < Elts.size(); ++I) 10568 Tree.merge(Elts[I]); 10569 } 10570 10571 void VisitInitListExpr(InitListExpr *ILE) { 10572 if (!SemaRef.getLangOpts().CPlusPlus11) 10573 return VisitExpr(ILE); 10574 10575 // In C++11, list initializations are sequenced. 10576 SmallVector<SequenceTree::Seq, 32> Elts; 10577 SequenceTree::Seq Parent = Region; 10578 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 10579 Expr *E = ILE->getInit(I); 10580 if (!E) continue; 10581 Region = Tree.allocate(Parent); 10582 Elts.push_back(Region); 10583 Visit(E); 10584 } 10585 10586 // Forget that the initializers are sequenced. 10587 Region = Parent; 10588 for (unsigned I = 0; I < Elts.size(); ++I) 10589 Tree.merge(Elts[I]); 10590 } 10591 }; 10592 } // end anonymous namespace 10593 10594 void Sema::CheckUnsequencedOperations(Expr *E) { 10595 SmallVector<Expr *, 8> WorkList; 10596 WorkList.push_back(E); 10597 while (!WorkList.empty()) { 10598 Expr *Item = WorkList.pop_back_val(); 10599 SequenceChecker(*this, Item, WorkList); 10600 } 10601 } 10602 10603 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 10604 bool IsConstexpr) { 10605 CheckImplicitConversions(E, CheckLoc); 10606 if (!E->isInstantiationDependent()) 10607 CheckUnsequencedOperations(E); 10608 if (!IsConstexpr && !E->isValueDependent()) 10609 CheckForIntOverflow(E); 10610 DiagnoseMisalignedMembers(); 10611 } 10612 10613 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 10614 FieldDecl *BitField, 10615 Expr *Init) { 10616 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 10617 } 10618 10619 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 10620 SourceLocation Loc) { 10621 if (!PType->isVariablyModifiedType()) 10622 return; 10623 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 10624 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 10625 return; 10626 } 10627 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 10628 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 10629 return; 10630 } 10631 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 10632 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 10633 return; 10634 } 10635 10636 const ArrayType *AT = S.Context.getAsArrayType(PType); 10637 if (!AT) 10638 return; 10639 10640 if (AT->getSizeModifier() != ArrayType::Star) { 10641 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 10642 return; 10643 } 10644 10645 S.Diag(Loc, diag::err_array_star_in_function_definition); 10646 } 10647 10648 /// CheckParmsForFunctionDef - Check that the parameters of the given 10649 /// function are appropriate for the definition of a function. This 10650 /// takes care of any checks that cannot be performed on the 10651 /// declaration itself, e.g., that the types of each of the function 10652 /// parameters are complete. 10653 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 10654 bool CheckParameterNames) { 10655 bool HasInvalidParm = false; 10656 for (ParmVarDecl *Param : Parameters) { 10657 // C99 6.7.5.3p4: the parameters in a parameter type list in a 10658 // function declarator that is part of a function definition of 10659 // that function shall not have incomplete type. 10660 // 10661 // This is also C++ [dcl.fct]p6. 10662 if (!Param->isInvalidDecl() && 10663 RequireCompleteType(Param->getLocation(), Param->getType(), 10664 diag::err_typecheck_decl_incomplete_type)) { 10665 Param->setInvalidDecl(); 10666 HasInvalidParm = true; 10667 } 10668 10669 // C99 6.9.1p5: If the declarator includes a parameter type list, the 10670 // declaration of each parameter shall include an identifier. 10671 if (CheckParameterNames && 10672 Param->getIdentifier() == nullptr && 10673 !Param->isImplicit() && 10674 !getLangOpts().CPlusPlus) 10675 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10676 10677 // C99 6.7.5.3p12: 10678 // If the function declarator is not part of a definition of that 10679 // function, parameters may have incomplete type and may use the [*] 10680 // notation in their sequences of declarator specifiers to specify 10681 // variable length array types. 10682 QualType PType = Param->getOriginalType(); 10683 // FIXME: This diagnostic should point the '[*]' if source-location 10684 // information is added for it. 10685 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 10686 10687 // MSVC destroys objects passed by value in the callee. Therefore a 10688 // function definition which takes such a parameter must be able to call the 10689 // object's destructor. However, we don't perform any direct access check 10690 // on the dtor. 10691 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 10692 .getCXXABI() 10693 .areArgsDestroyedLeftToRightInCallee()) { 10694 if (!Param->isInvalidDecl()) { 10695 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 10696 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 10697 if (!ClassDecl->isInvalidDecl() && 10698 !ClassDecl->hasIrrelevantDestructor() && 10699 !ClassDecl->isDependentContext()) { 10700 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10701 MarkFunctionReferenced(Param->getLocation(), Destructor); 10702 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 10703 } 10704 } 10705 } 10706 } 10707 10708 // Parameters with the pass_object_size attribute only need to be marked 10709 // constant at function definitions. Because we lack information about 10710 // whether we're on a declaration or definition when we're instantiating the 10711 // attribute, we need to check for constness here. 10712 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 10713 if (!Param->getType().isConstQualified()) 10714 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 10715 << Attr->getSpelling() << 1; 10716 } 10717 10718 return HasInvalidParm; 10719 } 10720 10721 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 10722 /// or MemberExpr. 10723 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 10724 ASTContext &Context) { 10725 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 10726 return Context.getDeclAlign(DRE->getDecl()); 10727 10728 if (const auto *ME = dyn_cast<MemberExpr>(E)) 10729 return Context.getDeclAlign(ME->getMemberDecl()); 10730 10731 return TypeAlign; 10732 } 10733 10734 /// CheckCastAlign - Implements -Wcast-align, which warns when a 10735 /// pointer cast increases the alignment requirements. 10736 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 10737 // This is actually a lot of work to potentially be doing on every 10738 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 10739 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 10740 return; 10741 10742 // Ignore dependent types. 10743 if (T->isDependentType() || Op->getType()->isDependentType()) 10744 return; 10745 10746 // Require that the destination be a pointer type. 10747 const PointerType *DestPtr = T->getAs<PointerType>(); 10748 if (!DestPtr) return; 10749 10750 // If the destination has alignment 1, we're done. 10751 QualType DestPointee = DestPtr->getPointeeType(); 10752 if (DestPointee->isIncompleteType()) return; 10753 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 10754 if (DestAlign.isOne()) return; 10755 10756 // Require that the source be a pointer type. 10757 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 10758 if (!SrcPtr) return; 10759 QualType SrcPointee = SrcPtr->getPointeeType(); 10760 10761 // Whitelist casts from cv void*. We already implicitly 10762 // whitelisted casts to cv void*, since they have alignment 1. 10763 // Also whitelist casts involving incomplete types, which implicitly 10764 // includes 'void'. 10765 if (SrcPointee->isIncompleteType()) return; 10766 10767 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 10768 10769 if (auto *CE = dyn_cast<CastExpr>(Op)) { 10770 if (CE->getCastKind() == CK_ArrayToPointerDecay) 10771 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 10772 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 10773 if (UO->getOpcode() == UO_AddrOf) 10774 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 10775 } 10776 10777 if (SrcAlign >= DestAlign) return; 10778 10779 Diag(TRange.getBegin(), diag::warn_cast_align) 10780 << Op->getType() << T 10781 << static_cast<unsigned>(SrcAlign.getQuantity()) 10782 << static_cast<unsigned>(DestAlign.getQuantity()) 10783 << TRange << Op->getSourceRange(); 10784 } 10785 10786 /// \brief Check whether this array fits the idiom of a size-one tail padded 10787 /// array member of a struct. 10788 /// 10789 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 10790 /// commonly used to emulate flexible arrays in C89 code. 10791 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 10792 const NamedDecl *ND) { 10793 if (Size != 1 || !ND) return false; 10794 10795 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 10796 if (!FD) return false; 10797 10798 // Don't consider sizes resulting from macro expansions or template argument 10799 // substitution to form C89 tail-padded arrays. 10800 10801 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 10802 while (TInfo) { 10803 TypeLoc TL = TInfo->getTypeLoc(); 10804 // Look through typedefs. 10805 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 10806 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 10807 TInfo = TDL->getTypeSourceInfo(); 10808 continue; 10809 } 10810 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 10811 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 10812 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 10813 return false; 10814 } 10815 break; 10816 } 10817 10818 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 10819 if (!RD) return false; 10820 if (RD->isUnion()) return false; 10821 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10822 if (!CRD->isStandardLayout()) return false; 10823 } 10824 10825 // See if this is the last field decl in the record. 10826 const Decl *D = FD; 10827 while ((D = D->getNextDeclInContext())) 10828 if (isa<FieldDecl>(D)) 10829 return false; 10830 return true; 10831 } 10832 10833 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 10834 const ArraySubscriptExpr *ASE, 10835 bool AllowOnePastEnd, bool IndexNegated) { 10836 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 10837 if (IndexExpr->isValueDependent()) 10838 return; 10839 10840 const Type *EffectiveType = 10841 BaseExpr->getType()->getPointeeOrArrayElementType(); 10842 BaseExpr = BaseExpr->IgnoreParenCasts(); 10843 const ConstantArrayType *ArrayTy = 10844 Context.getAsConstantArrayType(BaseExpr->getType()); 10845 if (!ArrayTy) 10846 return; 10847 10848 llvm::APSInt index; 10849 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 10850 return; 10851 if (IndexNegated) 10852 index = -index; 10853 10854 const NamedDecl *ND = nullptr; 10855 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10856 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10857 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10858 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10859 10860 if (index.isUnsigned() || !index.isNegative()) { 10861 llvm::APInt size = ArrayTy->getSize(); 10862 if (!size.isStrictlyPositive()) 10863 return; 10864 10865 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 10866 if (BaseType != EffectiveType) { 10867 // Make sure we're comparing apples to apples when comparing index to size 10868 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 10869 uint64_t array_typesize = Context.getTypeSize(BaseType); 10870 // Handle ptrarith_typesize being zero, such as when casting to void* 10871 if (!ptrarith_typesize) ptrarith_typesize = 1; 10872 if (ptrarith_typesize != array_typesize) { 10873 // There's a cast to a different size type involved 10874 uint64_t ratio = array_typesize / ptrarith_typesize; 10875 // TODO: Be smarter about handling cases where array_typesize is not a 10876 // multiple of ptrarith_typesize 10877 if (ptrarith_typesize * ratio == array_typesize) 10878 size *= llvm::APInt(size.getBitWidth(), ratio); 10879 } 10880 } 10881 10882 if (size.getBitWidth() > index.getBitWidth()) 10883 index = index.zext(size.getBitWidth()); 10884 else if (size.getBitWidth() < index.getBitWidth()) 10885 size = size.zext(index.getBitWidth()); 10886 10887 // For array subscripting the index must be less than size, but for pointer 10888 // arithmetic also allow the index (offset) to be equal to size since 10889 // computing the next address after the end of the array is legal and 10890 // commonly done e.g. in C++ iterators and range-based for loops. 10891 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 10892 return; 10893 10894 // Also don't warn for arrays of size 1 which are members of some 10895 // structure. These are often used to approximate flexible arrays in C89 10896 // code. 10897 if (IsTailPaddedMemberArray(*this, size, ND)) 10898 return; 10899 10900 // Suppress the warning if the subscript expression (as identified by the 10901 // ']' location) and the index expression are both from macro expansions 10902 // within a system header. 10903 if (ASE) { 10904 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 10905 ASE->getRBracketLoc()); 10906 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 10907 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 10908 IndexExpr->getLocStart()); 10909 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 10910 return; 10911 } 10912 } 10913 10914 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 10915 if (ASE) 10916 DiagID = diag::warn_array_index_exceeds_bounds; 10917 10918 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10919 PDiag(DiagID) << index.toString(10, true) 10920 << size.toString(10, true) 10921 << (unsigned)size.getLimitedValue(~0U) 10922 << IndexExpr->getSourceRange()); 10923 } else { 10924 unsigned DiagID = diag::warn_array_index_precedes_bounds; 10925 if (!ASE) { 10926 DiagID = diag::warn_ptr_arith_precedes_bounds; 10927 if (index.isNegative()) index = -index; 10928 } 10929 10930 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10931 PDiag(DiagID) << index.toString(10, true) 10932 << IndexExpr->getSourceRange()); 10933 } 10934 10935 if (!ND) { 10936 // Try harder to find a NamedDecl to point at in the note. 10937 while (const ArraySubscriptExpr *ASE = 10938 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 10939 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 10940 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10941 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10942 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10943 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10944 } 10945 10946 if (ND) 10947 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 10948 PDiag(diag::note_array_index_out_of_bounds) 10949 << ND->getDeclName()); 10950 } 10951 10952 void Sema::CheckArrayAccess(const Expr *expr) { 10953 int AllowOnePastEnd = 0; 10954 while (expr) { 10955 expr = expr->IgnoreParenImpCasts(); 10956 switch (expr->getStmtClass()) { 10957 case Stmt::ArraySubscriptExprClass: { 10958 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 10959 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 10960 AllowOnePastEnd > 0); 10961 return; 10962 } 10963 case Stmt::OMPArraySectionExprClass: { 10964 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 10965 if (ASE->getLowerBound()) 10966 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 10967 /*ASE=*/nullptr, AllowOnePastEnd > 0); 10968 return; 10969 } 10970 case Stmt::UnaryOperatorClass: { 10971 // Only unwrap the * and & unary operators 10972 const UnaryOperator *UO = cast<UnaryOperator>(expr); 10973 expr = UO->getSubExpr(); 10974 switch (UO->getOpcode()) { 10975 case UO_AddrOf: 10976 AllowOnePastEnd++; 10977 break; 10978 case UO_Deref: 10979 AllowOnePastEnd--; 10980 break; 10981 default: 10982 return; 10983 } 10984 break; 10985 } 10986 case Stmt::ConditionalOperatorClass: { 10987 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 10988 if (const Expr *lhs = cond->getLHS()) 10989 CheckArrayAccess(lhs); 10990 if (const Expr *rhs = cond->getRHS()) 10991 CheckArrayAccess(rhs); 10992 return; 10993 } 10994 case Stmt::CXXOperatorCallExprClass: { 10995 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 10996 for (const auto *Arg : OCE->arguments()) 10997 CheckArrayAccess(Arg); 10998 return; 10999 } 11000 default: 11001 return; 11002 } 11003 } 11004 } 11005 11006 //===--- CHECK: Objective-C retain cycles ----------------------------------// 11007 11008 namespace { 11009 struct RetainCycleOwner { 11010 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 11011 VarDecl *Variable; 11012 SourceRange Range; 11013 SourceLocation Loc; 11014 bool Indirect; 11015 11016 void setLocsFrom(Expr *e) { 11017 Loc = e->getExprLoc(); 11018 Range = e->getSourceRange(); 11019 } 11020 }; 11021 } // end anonymous namespace 11022 11023 /// Consider whether capturing the given variable can possibly lead to 11024 /// a retain cycle. 11025 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 11026 // In ARC, it's captured strongly iff the variable has __strong 11027 // lifetime. In MRR, it's captured strongly if the variable is 11028 // __block and has an appropriate type. 11029 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11030 return false; 11031 11032 owner.Variable = var; 11033 if (ref) 11034 owner.setLocsFrom(ref); 11035 return true; 11036 } 11037 11038 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 11039 while (true) { 11040 e = e->IgnoreParens(); 11041 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 11042 switch (cast->getCastKind()) { 11043 case CK_BitCast: 11044 case CK_LValueBitCast: 11045 case CK_LValueToRValue: 11046 case CK_ARCReclaimReturnedObject: 11047 e = cast->getSubExpr(); 11048 continue; 11049 11050 default: 11051 return false; 11052 } 11053 } 11054 11055 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 11056 ObjCIvarDecl *ivar = ref->getDecl(); 11057 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11058 return false; 11059 11060 // Try to find a retain cycle in the base. 11061 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 11062 return false; 11063 11064 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 11065 owner.Indirect = true; 11066 return true; 11067 } 11068 11069 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 11070 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 11071 if (!var) return false; 11072 return considerVariable(var, ref, owner); 11073 } 11074 11075 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 11076 if (member->isArrow()) return false; 11077 11078 // Don't count this as an indirect ownership. 11079 e = member->getBase(); 11080 continue; 11081 } 11082 11083 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 11084 // Only pay attention to pseudo-objects on property references. 11085 ObjCPropertyRefExpr *pre 11086 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 11087 ->IgnoreParens()); 11088 if (!pre) return false; 11089 if (pre->isImplicitProperty()) return false; 11090 ObjCPropertyDecl *property = pre->getExplicitProperty(); 11091 if (!property->isRetaining() && 11092 !(property->getPropertyIvarDecl() && 11093 property->getPropertyIvarDecl()->getType() 11094 .getObjCLifetime() == Qualifiers::OCL_Strong)) 11095 return false; 11096 11097 owner.Indirect = true; 11098 if (pre->isSuperReceiver()) { 11099 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 11100 if (!owner.Variable) 11101 return false; 11102 owner.Loc = pre->getLocation(); 11103 owner.Range = pre->getSourceRange(); 11104 return true; 11105 } 11106 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 11107 ->getSourceExpr()); 11108 continue; 11109 } 11110 11111 // Array ivars? 11112 11113 return false; 11114 } 11115 } 11116 11117 namespace { 11118 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 11119 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 11120 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 11121 Context(Context), Variable(variable), Capturer(nullptr), 11122 VarWillBeReased(false) {} 11123 ASTContext &Context; 11124 VarDecl *Variable; 11125 Expr *Capturer; 11126 bool VarWillBeReased; 11127 11128 void VisitDeclRefExpr(DeclRefExpr *ref) { 11129 if (ref->getDecl() == Variable && !Capturer) 11130 Capturer = ref; 11131 } 11132 11133 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 11134 if (Capturer) return; 11135 Visit(ref->getBase()); 11136 if (Capturer && ref->isFreeIvar()) 11137 Capturer = ref; 11138 } 11139 11140 void VisitBlockExpr(BlockExpr *block) { 11141 // Look inside nested blocks 11142 if (block->getBlockDecl()->capturesVariable(Variable)) 11143 Visit(block->getBlockDecl()->getBody()); 11144 } 11145 11146 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 11147 if (Capturer) return; 11148 if (OVE->getSourceExpr()) 11149 Visit(OVE->getSourceExpr()); 11150 } 11151 void VisitBinaryOperator(BinaryOperator *BinOp) { 11152 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 11153 return; 11154 Expr *LHS = BinOp->getLHS(); 11155 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 11156 if (DRE->getDecl() != Variable) 11157 return; 11158 if (Expr *RHS = BinOp->getRHS()) { 11159 RHS = RHS->IgnoreParenCasts(); 11160 llvm::APSInt Value; 11161 VarWillBeReased = 11162 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 11163 } 11164 } 11165 } 11166 }; 11167 } // end anonymous namespace 11168 11169 /// Check whether the given argument is a block which captures a 11170 /// variable. 11171 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 11172 assert(owner.Variable && owner.Loc.isValid()); 11173 11174 e = e->IgnoreParenCasts(); 11175 11176 // Look through [^{...} copy] and Block_copy(^{...}). 11177 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 11178 Selector Cmd = ME->getSelector(); 11179 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 11180 e = ME->getInstanceReceiver(); 11181 if (!e) 11182 return nullptr; 11183 e = e->IgnoreParenCasts(); 11184 } 11185 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 11186 if (CE->getNumArgs() == 1) { 11187 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 11188 if (Fn) { 11189 const IdentifierInfo *FnI = Fn->getIdentifier(); 11190 if (FnI && FnI->isStr("_Block_copy")) { 11191 e = CE->getArg(0)->IgnoreParenCasts(); 11192 } 11193 } 11194 } 11195 } 11196 11197 BlockExpr *block = dyn_cast<BlockExpr>(e); 11198 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 11199 return nullptr; 11200 11201 FindCaptureVisitor visitor(S.Context, owner.Variable); 11202 visitor.Visit(block->getBlockDecl()->getBody()); 11203 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 11204 } 11205 11206 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 11207 RetainCycleOwner &owner) { 11208 assert(capturer); 11209 assert(owner.Variable && owner.Loc.isValid()); 11210 11211 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 11212 << owner.Variable << capturer->getSourceRange(); 11213 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 11214 << owner.Indirect << owner.Range; 11215 } 11216 11217 /// Check for a keyword selector that starts with the word 'add' or 11218 /// 'set'. 11219 static bool isSetterLikeSelector(Selector sel) { 11220 if (sel.isUnarySelector()) return false; 11221 11222 StringRef str = sel.getNameForSlot(0); 11223 while (!str.empty() && str.front() == '_') str = str.substr(1); 11224 if (str.startswith("set")) 11225 str = str.substr(3); 11226 else if (str.startswith("add")) { 11227 // Specially whitelist 'addOperationWithBlock:'. 11228 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 11229 return false; 11230 str = str.substr(3); 11231 } 11232 else 11233 return false; 11234 11235 if (str.empty()) return true; 11236 return !isLowercase(str.front()); 11237 } 11238 11239 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 11240 ObjCMessageExpr *Message) { 11241 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 11242 Message->getReceiverInterface(), 11243 NSAPI::ClassId_NSMutableArray); 11244 if (!IsMutableArray) { 11245 return None; 11246 } 11247 11248 Selector Sel = Message->getSelector(); 11249 11250 Optional<NSAPI::NSArrayMethodKind> MKOpt = 11251 S.NSAPIObj->getNSArrayMethodKind(Sel); 11252 if (!MKOpt) { 11253 return None; 11254 } 11255 11256 NSAPI::NSArrayMethodKind MK = *MKOpt; 11257 11258 switch (MK) { 11259 case NSAPI::NSMutableArr_addObject: 11260 case NSAPI::NSMutableArr_insertObjectAtIndex: 11261 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 11262 return 0; 11263 case NSAPI::NSMutableArr_replaceObjectAtIndex: 11264 return 1; 11265 11266 default: 11267 return None; 11268 } 11269 11270 return None; 11271 } 11272 11273 static 11274 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 11275 ObjCMessageExpr *Message) { 11276 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 11277 Message->getReceiverInterface(), 11278 NSAPI::ClassId_NSMutableDictionary); 11279 if (!IsMutableDictionary) { 11280 return None; 11281 } 11282 11283 Selector Sel = Message->getSelector(); 11284 11285 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 11286 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 11287 if (!MKOpt) { 11288 return None; 11289 } 11290 11291 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 11292 11293 switch (MK) { 11294 case NSAPI::NSMutableDict_setObjectForKey: 11295 case NSAPI::NSMutableDict_setValueForKey: 11296 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 11297 return 0; 11298 11299 default: 11300 return None; 11301 } 11302 11303 return None; 11304 } 11305 11306 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 11307 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 11308 Message->getReceiverInterface(), 11309 NSAPI::ClassId_NSMutableSet); 11310 11311 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 11312 Message->getReceiverInterface(), 11313 NSAPI::ClassId_NSMutableOrderedSet); 11314 if (!IsMutableSet && !IsMutableOrderedSet) { 11315 return None; 11316 } 11317 11318 Selector Sel = Message->getSelector(); 11319 11320 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 11321 if (!MKOpt) { 11322 return None; 11323 } 11324 11325 NSAPI::NSSetMethodKind MK = *MKOpt; 11326 11327 switch (MK) { 11328 case NSAPI::NSMutableSet_addObject: 11329 case NSAPI::NSOrderedSet_setObjectAtIndex: 11330 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 11331 case NSAPI::NSOrderedSet_insertObjectAtIndex: 11332 return 0; 11333 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 11334 return 1; 11335 } 11336 11337 return None; 11338 } 11339 11340 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 11341 if (!Message->isInstanceMessage()) { 11342 return; 11343 } 11344 11345 Optional<int> ArgOpt; 11346 11347 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 11348 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 11349 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 11350 return; 11351 } 11352 11353 int ArgIndex = *ArgOpt; 11354 11355 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 11356 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 11357 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 11358 } 11359 11360 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 11361 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11362 if (ArgRE->isObjCSelfExpr()) { 11363 Diag(Message->getSourceRange().getBegin(), 11364 diag::warn_objc_circular_container) 11365 << ArgRE->getDecl()->getName() << StringRef("super"); 11366 } 11367 } 11368 } else { 11369 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 11370 11371 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 11372 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 11373 } 11374 11375 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 11376 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11377 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 11378 ValueDecl *Decl = ReceiverRE->getDecl(); 11379 Diag(Message->getSourceRange().getBegin(), 11380 diag::warn_objc_circular_container) 11381 << Decl->getName() << Decl->getName(); 11382 if (!ArgRE->isObjCSelfExpr()) { 11383 Diag(Decl->getLocation(), 11384 diag::note_objc_circular_container_declared_here) 11385 << Decl->getName(); 11386 } 11387 } 11388 } 11389 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 11390 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 11391 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 11392 ObjCIvarDecl *Decl = IvarRE->getDecl(); 11393 Diag(Message->getSourceRange().getBegin(), 11394 diag::warn_objc_circular_container) 11395 << Decl->getName() << Decl->getName(); 11396 Diag(Decl->getLocation(), 11397 diag::note_objc_circular_container_declared_here) 11398 << Decl->getName(); 11399 } 11400 } 11401 } 11402 } 11403 } 11404 11405 /// Check a message send to see if it's likely to cause a retain cycle. 11406 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 11407 // Only check instance methods whose selector looks like a setter. 11408 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 11409 return; 11410 11411 // Try to find a variable that the receiver is strongly owned by. 11412 RetainCycleOwner owner; 11413 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 11414 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 11415 return; 11416 } else { 11417 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 11418 owner.Variable = getCurMethodDecl()->getSelfDecl(); 11419 owner.Loc = msg->getSuperLoc(); 11420 owner.Range = msg->getSuperLoc(); 11421 } 11422 11423 // Check whether the receiver is captured by any of the arguments. 11424 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 11425 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 11426 return diagnoseRetainCycle(*this, capturer, owner); 11427 } 11428 11429 /// Check a property assign to see if it's likely to cause a retain cycle. 11430 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 11431 RetainCycleOwner owner; 11432 if (!findRetainCycleOwner(*this, receiver, owner)) 11433 return; 11434 11435 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 11436 diagnoseRetainCycle(*this, capturer, owner); 11437 } 11438 11439 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 11440 RetainCycleOwner Owner; 11441 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 11442 return; 11443 11444 // Because we don't have an expression for the variable, we have to set the 11445 // location explicitly here. 11446 Owner.Loc = Var->getLocation(); 11447 Owner.Range = Var->getSourceRange(); 11448 11449 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 11450 diagnoseRetainCycle(*this, Capturer, Owner); 11451 } 11452 11453 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 11454 Expr *RHS, bool isProperty) { 11455 // Check if RHS is an Objective-C object literal, which also can get 11456 // immediately zapped in a weak reference. Note that we explicitly 11457 // allow ObjCStringLiterals, since those are designed to never really die. 11458 RHS = RHS->IgnoreParenImpCasts(); 11459 11460 // This enum needs to match with the 'select' in 11461 // warn_objc_arc_literal_assign (off-by-1). 11462 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 11463 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 11464 return false; 11465 11466 S.Diag(Loc, diag::warn_arc_literal_assign) 11467 << (unsigned) Kind 11468 << (isProperty ? 0 : 1) 11469 << RHS->getSourceRange(); 11470 11471 return true; 11472 } 11473 11474 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 11475 Qualifiers::ObjCLifetime LT, 11476 Expr *RHS, bool isProperty) { 11477 // Strip off any implicit cast added to get to the one ARC-specific. 11478 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11479 if (cast->getCastKind() == CK_ARCConsumeObject) { 11480 S.Diag(Loc, diag::warn_arc_retained_assign) 11481 << (LT == Qualifiers::OCL_ExplicitNone) 11482 << (isProperty ? 0 : 1) 11483 << RHS->getSourceRange(); 11484 return true; 11485 } 11486 RHS = cast->getSubExpr(); 11487 } 11488 11489 if (LT == Qualifiers::OCL_Weak && 11490 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 11491 return true; 11492 11493 return false; 11494 } 11495 11496 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 11497 QualType LHS, Expr *RHS) { 11498 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 11499 11500 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 11501 return false; 11502 11503 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 11504 return true; 11505 11506 return false; 11507 } 11508 11509 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 11510 Expr *LHS, Expr *RHS) { 11511 QualType LHSType; 11512 // PropertyRef on LHS type need be directly obtained from 11513 // its declaration as it has a PseudoType. 11514 ObjCPropertyRefExpr *PRE 11515 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 11516 if (PRE && !PRE->isImplicitProperty()) { 11517 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11518 if (PD) 11519 LHSType = PD->getType(); 11520 } 11521 11522 if (LHSType.isNull()) 11523 LHSType = LHS->getType(); 11524 11525 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 11526 11527 if (LT == Qualifiers::OCL_Weak) { 11528 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 11529 getCurFunction()->markSafeWeakUse(LHS); 11530 } 11531 11532 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 11533 return; 11534 11535 // FIXME. Check for other life times. 11536 if (LT != Qualifiers::OCL_None) 11537 return; 11538 11539 if (PRE) { 11540 if (PRE->isImplicitProperty()) 11541 return; 11542 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11543 if (!PD) 11544 return; 11545 11546 unsigned Attributes = PD->getPropertyAttributes(); 11547 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 11548 // when 'assign' attribute was not explicitly specified 11549 // by user, ignore it and rely on property type itself 11550 // for lifetime info. 11551 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 11552 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 11553 LHSType->isObjCRetainableType()) 11554 return; 11555 11556 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11557 if (cast->getCastKind() == CK_ARCConsumeObject) { 11558 Diag(Loc, diag::warn_arc_retained_property_assign) 11559 << RHS->getSourceRange(); 11560 return; 11561 } 11562 RHS = cast->getSubExpr(); 11563 } 11564 } 11565 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 11566 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 11567 return; 11568 } 11569 } 11570 } 11571 11572 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 11573 11574 namespace { 11575 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 11576 SourceLocation StmtLoc, 11577 const NullStmt *Body) { 11578 // Do not warn if the body is a macro that expands to nothing, e.g: 11579 // 11580 // #define CALL(x) 11581 // if (condition) 11582 // CALL(0); 11583 // 11584 if (Body->hasLeadingEmptyMacro()) 11585 return false; 11586 11587 // Get line numbers of statement and body. 11588 bool StmtLineInvalid; 11589 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 11590 &StmtLineInvalid); 11591 if (StmtLineInvalid) 11592 return false; 11593 11594 bool BodyLineInvalid; 11595 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 11596 &BodyLineInvalid); 11597 if (BodyLineInvalid) 11598 return false; 11599 11600 // Warn if null statement and body are on the same line. 11601 if (StmtLine != BodyLine) 11602 return false; 11603 11604 return true; 11605 } 11606 } // end anonymous namespace 11607 11608 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 11609 const Stmt *Body, 11610 unsigned DiagID) { 11611 // Since this is a syntactic check, don't emit diagnostic for template 11612 // instantiations, this just adds noise. 11613 if (CurrentInstantiationScope) 11614 return; 11615 11616 // The body should be a null statement. 11617 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11618 if (!NBody) 11619 return; 11620 11621 // Do the usual checks. 11622 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11623 return; 11624 11625 Diag(NBody->getSemiLoc(), DiagID); 11626 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11627 } 11628 11629 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 11630 const Stmt *PossibleBody) { 11631 assert(!CurrentInstantiationScope); // Ensured by caller 11632 11633 SourceLocation StmtLoc; 11634 const Stmt *Body; 11635 unsigned DiagID; 11636 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 11637 StmtLoc = FS->getRParenLoc(); 11638 Body = FS->getBody(); 11639 DiagID = diag::warn_empty_for_body; 11640 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 11641 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 11642 Body = WS->getBody(); 11643 DiagID = diag::warn_empty_while_body; 11644 } else 11645 return; // Neither `for' nor `while'. 11646 11647 // The body should be a null statement. 11648 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11649 if (!NBody) 11650 return; 11651 11652 // Skip expensive checks if diagnostic is disabled. 11653 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 11654 return; 11655 11656 // Do the usual checks. 11657 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11658 return; 11659 11660 // `for(...);' and `while(...);' are popular idioms, so in order to keep 11661 // noise level low, emit diagnostics only if for/while is followed by a 11662 // CompoundStmt, e.g.: 11663 // for (int i = 0; i < n; i++); 11664 // { 11665 // a(i); 11666 // } 11667 // or if for/while is followed by a statement with more indentation 11668 // than for/while itself: 11669 // for (int i = 0; i < n; i++); 11670 // a(i); 11671 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 11672 if (!ProbableTypo) { 11673 bool BodyColInvalid; 11674 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 11675 PossibleBody->getLocStart(), 11676 &BodyColInvalid); 11677 if (BodyColInvalid) 11678 return; 11679 11680 bool StmtColInvalid; 11681 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 11682 S->getLocStart(), 11683 &StmtColInvalid); 11684 if (StmtColInvalid) 11685 return; 11686 11687 if (BodyCol > StmtCol) 11688 ProbableTypo = true; 11689 } 11690 11691 if (ProbableTypo) { 11692 Diag(NBody->getSemiLoc(), DiagID); 11693 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11694 } 11695 } 11696 11697 //===--- CHECK: Warn on self move with std::move. -------------------------===// 11698 11699 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 11700 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 11701 SourceLocation OpLoc) { 11702 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 11703 return; 11704 11705 if (inTemplateInstantiation()) 11706 return; 11707 11708 // Strip parens and casts away. 11709 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11710 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11711 11712 // Check for a call expression 11713 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 11714 if (!CE || CE->getNumArgs() != 1) 11715 return; 11716 11717 // Check for a call to std::move 11718 const FunctionDecl *FD = CE->getDirectCallee(); 11719 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() || 11720 !FD->getIdentifier()->isStr("move")) 11721 return; 11722 11723 // Get argument from std::move 11724 RHSExpr = CE->getArg(0); 11725 11726 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11727 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11728 11729 // Two DeclRefExpr's, check that the decls are the same. 11730 if (LHSDeclRef && RHSDeclRef) { 11731 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11732 return; 11733 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11734 RHSDeclRef->getDecl()->getCanonicalDecl()) 11735 return; 11736 11737 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11738 << LHSExpr->getSourceRange() 11739 << RHSExpr->getSourceRange(); 11740 return; 11741 } 11742 11743 // Member variables require a different approach to check for self moves. 11744 // MemberExpr's are the same if every nested MemberExpr refers to the same 11745 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 11746 // the base Expr's are CXXThisExpr's. 11747 const Expr *LHSBase = LHSExpr; 11748 const Expr *RHSBase = RHSExpr; 11749 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 11750 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 11751 if (!LHSME || !RHSME) 11752 return; 11753 11754 while (LHSME && RHSME) { 11755 if (LHSME->getMemberDecl()->getCanonicalDecl() != 11756 RHSME->getMemberDecl()->getCanonicalDecl()) 11757 return; 11758 11759 LHSBase = LHSME->getBase(); 11760 RHSBase = RHSME->getBase(); 11761 LHSME = dyn_cast<MemberExpr>(LHSBase); 11762 RHSME = dyn_cast<MemberExpr>(RHSBase); 11763 } 11764 11765 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 11766 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 11767 if (LHSDeclRef && RHSDeclRef) { 11768 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11769 return; 11770 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11771 RHSDeclRef->getDecl()->getCanonicalDecl()) 11772 return; 11773 11774 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11775 << LHSExpr->getSourceRange() 11776 << RHSExpr->getSourceRange(); 11777 return; 11778 } 11779 11780 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 11781 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11782 << LHSExpr->getSourceRange() 11783 << RHSExpr->getSourceRange(); 11784 } 11785 11786 //===--- Layout compatibility ----------------------------------------------// 11787 11788 namespace { 11789 11790 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 11791 11792 /// \brief Check if two enumeration types are layout-compatible. 11793 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 11794 // C++11 [dcl.enum] p8: 11795 // Two enumeration types are layout-compatible if they have the same 11796 // underlying type. 11797 return ED1->isComplete() && ED2->isComplete() && 11798 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 11799 } 11800 11801 /// \brief Check if two fields are layout-compatible. 11802 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 11803 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 11804 return false; 11805 11806 if (Field1->isBitField() != Field2->isBitField()) 11807 return false; 11808 11809 if (Field1->isBitField()) { 11810 // Make sure that the bit-fields are the same length. 11811 unsigned Bits1 = Field1->getBitWidthValue(C); 11812 unsigned Bits2 = Field2->getBitWidthValue(C); 11813 11814 if (Bits1 != Bits2) 11815 return false; 11816 } 11817 11818 return true; 11819 } 11820 11821 /// \brief Check if two standard-layout structs are layout-compatible. 11822 /// (C++11 [class.mem] p17) 11823 bool isLayoutCompatibleStruct(ASTContext &C, 11824 RecordDecl *RD1, 11825 RecordDecl *RD2) { 11826 // If both records are C++ classes, check that base classes match. 11827 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 11828 // If one of records is a CXXRecordDecl we are in C++ mode, 11829 // thus the other one is a CXXRecordDecl, too. 11830 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 11831 // Check number of base classes. 11832 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 11833 return false; 11834 11835 // Check the base classes. 11836 for (CXXRecordDecl::base_class_const_iterator 11837 Base1 = D1CXX->bases_begin(), 11838 BaseEnd1 = D1CXX->bases_end(), 11839 Base2 = D2CXX->bases_begin(); 11840 Base1 != BaseEnd1; 11841 ++Base1, ++Base2) { 11842 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 11843 return false; 11844 } 11845 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 11846 // If only RD2 is a C++ class, it should have zero base classes. 11847 if (D2CXX->getNumBases() > 0) 11848 return false; 11849 } 11850 11851 // Check the fields. 11852 RecordDecl::field_iterator Field2 = RD2->field_begin(), 11853 Field2End = RD2->field_end(), 11854 Field1 = RD1->field_begin(), 11855 Field1End = RD1->field_end(); 11856 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 11857 if (!isLayoutCompatible(C, *Field1, *Field2)) 11858 return false; 11859 } 11860 if (Field1 != Field1End || Field2 != Field2End) 11861 return false; 11862 11863 return true; 11864 } 11865 11866 /// \brief Check if two standard-layout unions are layout-compatible. 11867 /// (C++11 [class.mem] p18) 11868 bool isLayoutCompatibleUnion(ASTContext &C, 11869 RecordDecl *RD1, 11870 RecordDecl *RD2) { 11871 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 11872 for (auto *Field2 : RD2->fields()) 11873 UnmatchedFields.insert(Field2); 11874 11875 for (auto *Field1 : RD1->fields()) { 11876 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 11877 I = UnmatchedFields.begin(), 11878 E = UnmatchedFields.end(); 11879 11880 for ( ; I != E; ++I) { 11881 if (isLayoutCompatible(C, Field1, *I)) { 11882 bool Result = UnmatchedFields.erase(*I); 11883 (void) Result; 11884 assert(Result); 11885 break; 11886 } 11887 } 11888 if (I == E) 11889 return false; 11890 } 11891 11892 return UnmatchedFields.empty(); 11893 } 11894 11895 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 11896 if (RD1->isUnion() != RD2->isUnion()) 11897 return false; 11898 11899 if (RD1->isUnion()) 11900 return isLayoutCompatibleUnion(C, RD1, RD2); 11901 else 11902 return isLayoutCompatibleStruct(C, RD1, RD2); 11903 } 11904 11905 /// \brief Check if two types are layout-compatible in C++11 sense. 11906 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 11907 if (T1.isNull() || T2.isNull()) 11908 return false; 11909 11910 // C++11 [basic.types] p11: 11911 // If two types T1 and T2 are the same type, then T1 and T2 are 11912 // layout-compatible types. 11913 if (C.hasSameType(T1, T2)) 11914 return true; 11915 11916 T1 = T1.getCanonicalType().getUnqualifiedType(); 11917 T2 = T2.getCanonicalType().getUnqualifiedType(); 11918 11919 const Type::TypeClass TC1 = T1->getTypeClass(); 11920 const Type::TypeClass TC2 = T2->getTypeClass(); 11921 11922 if (TC1 != TC2) 11923 return false; 11924 11925 if (TC1 == Type::Enum) { 11926 return isLayoutCompatible(C, 11927 cast<EnumType>(T1)->getDecl(), 11928 cast<EnumType>(T2)->getDecl()); 11929 } else if (TC1 == Type::Record) { 11930 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 11931 return false; 11932 11933 return isLayoutCompatible(C, 11934 cast<RecordType>(T1)->getDecl(), 11935 cast<RecordType>(T2)->getDecl()); 11936 } 11937 11938 return false; 11939 } 11940 } // end anonymous namespace 11941 11942 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 11943 11944 namespace { 11945 /// \brief Given a type tag expression find the type tag itself. 11946 /// 11947 /// \param TypeExpr Type tag expression, as it appears in user's code. 11948 /// 11949 /// \param VD Declaration of an identifier that appears in a type tag. 11950 /// 11951 /// \param MagicValue Type tag magic value. 11952 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 11953 const ValueDecl **VD, uint64_t *MagicValue) { 11954 while(true) { 11955 if (!TypeExpr) 11956 return false; 11957 11958 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 11959 11960 switch (TypeExpr->getStmtClass()) { 11961 case Stmt::UnaryOperatorClass: { 11962 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 11963 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 11964 TypeExpr = UO->getSubExpr(); 11965 continue; 11966 } 11967 return false; 11968 } 11969 11970 case Stmt::DeclRefExprClass: { 11971 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 11972 *VD = DRE->getDecl(); 11973 return true; 11974 } 11975 11976 case Stmt::IntegerLiteralClass: { 11977 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 11978 llvm::APInt MagicValueAPInt = IL->getValue(); 11979 if (MagicValueAPInt.getActiveBits() <= 64) { 11980 *MagicValue = MagicValueAPInt.getZExtValue(); 11981 return true; 11982 } else 11983 return false; 11984 } 11985 11986 case Stmt::BinaryConditionalOperatorClass: 11987 case Stmt::ConditionalOperatorClass: { 11988 const AbstractConditionalOperator *ACO = 11989 cast<AbstractConditionalOperator>(TypeExpr); 11990 bool Result; 11991 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 11992 if (Result) 11993 TypeExpr = ACO->getTrueExpr(); 11994 else 11995 TypeExpr = ACO->getFalseExpr(); 11996 continue; 11997 } 11998 return false; 11999 } 12000 12001 case Stmt::BinaryOperatorClass: { 12002 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 12003 if (BO->getOpcode() == BO_Comma) { 12004 TypeExpr = BO->getRHS(); 12005 continue; 12006 } 12007 return false; 12008 } 12009 12010 default: 12011 return false; 12012 } 12013 } 12014 } 12015 12016 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 12017 /// 12018 /// \param TypeExpr Expression that specifies a type tag. 12019 /// 12020 /// \param MagicValues Registered magic values. 12021 /// 12022 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 12023 /// kind. 12024 /// 12025 /// \param TypeInfo Information about the corresponding C type. 12026 /// 12027 /// \returns true if the corresponding C type was found. 12028 bool GetMatchingCType( 12029 const IdentifierInfo *ArgumentKind, 12030 const Expr *TypeExpr, const ASTContext &Ctx, 12031 const llvm::DenseMap<Sema::TypeTagMagicValue, 12032 Sema::TypeTagData> *MagicValues, 12033 bool &FoundWrongKind, 12034 Sema::TypeTagData &TypeInfo) { 12035 FoundWrongKind = false; 12036 12037 // Variable declaration that has type_tag_for_datatype attribute. 12038 const ValueDecl *VD = nullptr; 12039 12040 uint64_t MagicValue; 12041 12042 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 12043 return false; 12044 12045 if (VD) { 12046 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 12047 if (I->getArgumentKind() != ArgumentKind) { 12048 FoundWrongKind = true; 12049 return false; 12050 } 12051 TypeInfo.Type = I->getMatchingCType(); 12052 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 12053 TypeInfo.MustBeNull = I->getMustBeNull(); 12054 return true; 12055 } 12056 return false; 12057 } 12058 12059 if (!MagicValues) 12060 return false; 12061 12062 llvm::DenseMap<Sema::TypeTagMagicValue, 12063 Sema::TypeTagData>::const_iterator I = 12064 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 12065 if (I == MagicValues->end()) 12066 return false; 12067 12068 TypeInfo = I->second; 12069 return true; 12070 } 12071 } // end anonymous namespace 12072 12073 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 12074 uint64_t MagicValue, QualType Type, 12075 bool LayoutCompatible, 12076 bool MustBeNull) { 12077 if (!TypeTagForDatatypeMagicValues) 12078 TypeTagForDatatypeMagicValues.reset( 12079 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 12080 12081 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 12082 (*TypeTagForDatatypeMagicValues)[Magic] = 12083 TypeTagData(Type, LayoutCompatible, MustBeNull); 12084 } 12085 12086 namespace { 12087 bool IsSameCharType(QualType T1, QualType T2) { 12088 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 12089 if (!BT1) 12090 return false; 12091 12092 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 12093 if (!BT2) 12094 return false; 12095 12096 BuiltinType::Kind T1Kind = BT1->getKind(); 12097 BuiltinType::Kind T2Kind = BT2->getKind(); 12098 12099 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 12100 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 12101 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 12102 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 12103 } 12104 } // end anonymous namespace 12105 12106 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 12107 const Expr * const *ExprArgs) { 12108 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 12109 bool IsPointerAttr = Attr->getIsPointer(); 12110 12111 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 12112 bool FoundWrongKind; 12113 TypeTagData TypeInfo; 12114 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 12115 TypeTagForDatatypeMagicValues.get(), 12116 FoundWrongKind, TypeInfo)) { 12117 if (FoundWrongKind) 12118 Diag(TypeTagExpr->getExprLoc(), 12119 diag::warn_type_tag_for_datatype_wrong_kind) 12120 << TypeTagExpr->getSourceRange(); 12121 return; 12122 } 12123 12124 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 12125 if (IsPointerAttr) { 12126 // Skip implicit cast of pointer to `void *' (as a function argument). 12127 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 12128 if (ICE->getType()->isVoidPointerType() && 12129 ICE->getCastKind() == CK_BitCast) 12130 ArgumentExpr = ICE->getSubExpr(); 12131 } 12132 QualType ArgumentType = ArgumentExpr->getType(); 12133 12134 // Passing a `void*' pointer shouldn't trigger a warning. 12135 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 12136 return; 12137 12138 if (TypeInfo.MustBeNull) { 12139 // Type tag with matching void type requires a null pointer. 12140 if (!ArgumentExpr->isNullPointerConstant(Context, 12141 Expr::NPC_ValueDependentIsNotNull)) { 12142 Diag(ArgumentExpr->getExprLoc(), 12143 diag::warn_type_safety_null_pointer_required) 12144 << ArgumentKind->getName() 12145 << ArgumentExpr->getSourceRange() 12146 << TypeTagExpr->getSourceRange(); 12147 } 12148 return; 12149 } 12150 12151 QualType RequiredType = TypeInfo.Type; 12152 if (IsPointerAttr) 12153 RequiredType = Context.getPointerType(RequiredType); 12154 12155 bool mismatch = false; 12156 if (!TypeInfo.LayoutCompatible) { 12157 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 12158 12159 // C++11 [basic.fundamental] p1: 12160 // Plain char, signed char, and unsigned char are three distinct types. 12161 // 12162 // But we treat plain `char' as equivalent to `signed char' or `unsigned 12163 // char' depending on the current char signedness mode. 12164 if (mismatch) 12165 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 12166 RequiredType->getPointeeType())) || 12167 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 12168 mismatch = false; 12169 } else 12170 if (IsPointerAttr) 12171 mismatch = !isLayoutCompatible(Context, 12172 ArgumentType->getPointeeType(), 12173 RequiredType->getPointeeType()); 12174 else 12175 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 12176 12177 if (mismatch) 12178 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 12179 << ArgumentType << ArgumentKind 12180 << TypeInfo.LayoutCompatible << RequiredType 12181 << ArgumentExpr->getSourceRange() 12182 << TypeTagExpr->getSourceRange(); 12183 } 12184 12185 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 12186 CharUnits Alignment) { 12187 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 12188 } 12189 12190 void Sema::DiagnoseMisalignedMembers() { 12191 for (MisalignedMember &m : MisalignedMembers) { 12192 const NamedDecl *ND = m.RD; 12193 if (ND->getName().empty()) { 12194 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 12195 ND = TD; 12196 } 12197 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 12198 << m.MD << ND << m.E->getSourceRange(); 12199 } 12200 MisalignedMembers.clear(); 12201 } 12202 12203 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 12204 E = E->IgnoreParens(); 12205 if (!T->isPointerType() && !T->isIntegerType()) 12206 return; 12207 if (isa<UnaryOperator>(E) && 12208 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 12209 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 12210 if (isa<MemberExpr>(Op)) { 12211 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 12212 MisalignedMember(Op)); 12213 if (MA != MisalignedMembers.end() && 12214 (T->isIntegerType() || 12215 (T->isPointerType() && 12216 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment))) 12217 MisalignedMembers.erase(MA); 12218 } 12219 } 12220 } 12221 12222 void Sema::RefersToMemberWithReducedAlignment( 12223 Expr *E, 12224 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 12225 Action) { 12226 const auto *ME = dyn_cast<MemberExpr>(E); 12227 if (!ME) 12228 return; 12229 12230 // No need to check expressions with an __unaligned-qualified type. 12231 if (E->getType().getQualifiers().hasUnaligned()) 12232 return; 12233 12234 // For a chain of MemberExpr like "a.b.c.d" this list 12235 // will keep FieldDecl's like [d, c, b]. 12236 SmallVector<FieldDecl *, 4> ReverseMemberChain; 12237 const MemberExpr *TopME = nullptr; 12238 bool AnyIsPacked = false; 12239 do { 12240 QualType BaseType = ME->getBase()->getType(); 12241 if (ME->isArrow()) 12242 BaseType = BaseType->getPointeeType(); 12243 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 12244 if (RD->isInvalidDecl()) 12245 return; 12246 12247 ValueDecl *MD = ME->getMemberDecl(); 12248 auto *FD = dyn_cast<FieldDecl>(MD); 12249 // We do not care about non-data members. 12250 if (!FD || FD->isInvalidDecl()) 12251 return; 12252 12253 AnyIsPacked = 12254 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 12255 ReverseMemberChain.push_back(FD); 12256 12257 TopME = ME; 12258 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 12259 } while (ME); 12260 assert(TopME && "We did not compute a topmost MemberExpr!"); 12261 12262 // Not the scope of this diagnostic. 12263 if (!AnyIsPacked) 12264 return; 12265 12266 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 12267 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 12268 // TODO: The innermost base of the member expression may be too complicated. 12269 // For now, just disregard these cases. This is left for future 12270 // improvement. 12271 if (!DRE && !isa<CXXThisExpr>(TopBase)) 12272 return; 12273 12274 // Alignment expected by the whole expression. 12275 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 12276 12277 // No need to do anything else with this case. 12278 if (ExpectedAlignment.isOne()) 12279 return; 12280 12281 // Synthesize offset of the whole access. 12282 CharUnits Offset; 12283 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 12284 I++) { 12285 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 12286 } 12287 12288 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 12289 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 12290 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 12291 12292 // The base expression of the innermost MemberExpr may give 12293 // stronger guarantees than the class containing the member. 12294 if (DRE && !TopME->isArrow()) { 12295 const ValueDecl *VD = DRE->getDecl(); 12296 if (!VD->getType()->isReferenceType()) 12297 CompleteObjectAlignment = 12298 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 12299 } 12300 12301 // Check if the synthesized offset fulfills the alignment. 12302 if (Offset % ExpectedAlignment != 0 || 12303 // It may fulfill the offset it but the effective alignment may still be 12304 // lower than the expected expression alignment. 12305 CompleteObjectAlignment < ExpectedAlignment) { 12306 // If this happens, we want to determine a sensible culprit of this. 12307 // Intuitively, watching the chain of member expressions from right to 12308 // left, we start with the required alignment (as required by the field 12309 // type) but some packed attribute in that chain has reduced the alignment. 12310 // It may happen that another packed structure increases it again. But if 12311 // we are here such increase has not been enough. So pointing the first 12312 // FieldDecl that either is packed or else its RecordDecl is, 12313 // seems reasonable. 12314 FieldDecl *FD = nullptr; 12315 CharUnits Alignment; 12316 for (FieldDecl *FDI : ReverseMemberChain) { 12317 if (FDI->hasAttr<PackedAttr>() || 12318 FDI->getParent()->hasAttr<PackedAttr>()) { 12319 FD = FDI; 12320 Alignment = std::min( 12321 Context.getTypeAlignInChars(FD->getType()), 12322 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 12323 break; 12324 } 12325 } 12326 assert(FD && "We did not find a packed FieldDecl!"); 12327 Action(E, FD->getParent(), FD, Alignment); 12328 } 12329 } 12330 12331 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 12332 using namespace std::placeholders; 12333 RefersToMemberWithReducedAlignment( 12334 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 12335 _2, _3, _4)); 12336 } 12337 12338