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 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 103 // We need at least one argument. 104 if (TheCall->getNumArgs() < 1) { 105 S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 106 << 0 << 1 << TheCall->getNumArgs() 107 << TheCall->getCallee()->getSourceRange(); 108 return true; 109 } 110 111 // All arguments should be wide string literals. 112 for (Expr *Arg : TheCall->arguments()) { 113 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 114 if (!Literal || !Literal->isWide()) { 115 S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str) 116 << Arg->getSourceRange(); 117 return true; 118 } 119 } 120 121 return false; 122 } 123 124 /// Check that the argument to __builtin_addressof is a glvalue, and set the 125 /// result type to the corresponding pointer type. 126 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 127 if (checkArgCount(S, TheCall, 1)) 128 return true; 129 130 ExprResult Arg(TheCall->getArg(0)); 131 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 132 if (ResultType.isNull()) 133 return true; 134 135 TheCall->setArg(0, Arg.get()); 136 TheCall->setType(ResultType); 137 return false; 138 } 139 140 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 141 if (checkArgCount(S, TheCall, 3)) 142 return true; 143 144 // First two arguments should be integers. 145 for (unsigned I = 0; I < 2; ++I) { 146 Expr *Arg = TheCall->getArg(I); 147 QualType Ty = Arg->getType(); 148 if (!Ty->isIntegerType()) { 149 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int) 150 << Ty << Arg->getSourceRange(); 151 return true; 152 } 153 } 154 155 // Third argument should be a pointer to a non-const integer. 156 // IRGen correctly handles volatile, restrict, and address spaces, and 157 // the other qualifiers aren't possible. 158 { 159 Expr *Arg = TheCall->getArg(2); 160 QualType Ty = Arg->getType(); 161 const auto *PtrTy = Ty->getAs<PointerType>(); 162 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 163 !PtrTy->getPointeeType().isConstQualified())) { 164 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int) 165 << Ty << Arg->getSourceRange(); 166 return true; 167 } 168 } 169 170 return false; 171 } 172 173 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 174 CallExpr *TheCall, unsigned SizeIdx, 175 unsigned DstSizeIdx) { 176 if (TheCall->getNumArgs() <= SizeIdx || 177 TheCall->getNumArgs() <= DstSizeIdx) 178 return; 179 180 const Expr *SizeArg = TheCall->getArg(SizeIdx); 181 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 182 183 llvm::APSInt Size, DstSize; 184 185 // find out if both sizes are known at compile time 186 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 187 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 188 return; 189 190 if (Size.ule(DstSize)) 191 return; 192 193 // confirmed overflow so generate the diagnostic. 194 IdentifierInfo *FnName = FDecl->getIdentifier(); 195 SourceLocation SL = TheCall->getLocStart(); 196 SourceRange SR = TheCall->getSourceRange(); 197 198 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; 199 } 200 201 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 202 if (checkArgCount(S, BuiltinCall, 2)) 203 return true; 204 205 SourceLocation BuiltinLoc = BuiltinCall->getLocStart(); 206 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 207 Expr *Call = BuiltinCall->getArg(0); 208 Expr *Chain = BuiltinCall->getArg(1); 209 210 if (Call->getStmtClass() != Stmt::CallExprClass) { 211 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 212 << Call->getSourceRange(); 213 return true; 214 } 215 216 auto CE = cast<CallExpr>(Call); 217 if (CE->getCallee()->getType()->isBlockPointerType()) { 218 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 219 << Call->getSourceRange(); 220 return true; 221 } 222 223 const Decl *TargetDecl = CE->getCalleeDecl(); 224 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 225 if (FD->getBuiltinID()) { 226 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 227 << Call->getSourceRange(); 228 return true; 229 } 230 231 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 232 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 233 << Call->getSourceRange(); 234 return true; 235 } 236 237 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 238 if (ChainResult.isInvalid()) 239 return true; 240 if (!ChainResult.get()->getType()->isPointerType()) { 241 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 242 << Chain->getSourceRange(); 243 return true; 244 } 245 246 QualType ReturnTy = CE->getCallReturnType(S.Context); 247 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 248 QualType BuiltinTy = S.Context.getFunctionType( 249 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 250 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 251 252 Builtin = 253 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 254 255 BuiltinCall->setType(CE->getType()); 256 BuiltinCall->setValueKind(CE->getValueKind()); 257 BuiltinCall->setObjectKind(CE->getObjectKind()); 258 BuiltinCall->setCallee(Builtin); 259 BuiltinCall->setArg(1, ChainResult.get()); 260 261 return false; 262 } 263 264 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 265 Scope::ScopeFlags NeededScopeFlags, 266 unsigned DiagID) { 267 // Scopes aren't available during instantiation. Fortunately, builtin 268 // functions cannot be template args so they cannot be formed through template 269 // instantiation. Therefore checking once during the parse is sufficient. 270 if (SemaRef.inTemplateInstantiation()) 271 return false; 272 273 Scope *S = SemaRef.getCurScope(); 274 while (S && !S->isSEHExceptScope()) 275 S = S->getParent(); 276 if (!S || !(S->getFlags() & NeededScopeFlags)) { 277 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 278 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 279 << DRE->getDecl()->getIdentifier(); 280 return true; 281 } 282 283 return false; 284 } 285 286 static inline bool isBlockPointer(Expr *Arg) { 287 return Arg->getType()->isBlockPointerType(); 288 } 289 290 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 291 /// void*, which is a requirement of device side enqueue. 292 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 293 const BlockPointerType *BPT = 294 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 295 ArrayRef<QualType> Params = 296 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 297 unsigned ArgCounter = 0; 298 bool IllegalParams = false; 299 // Iterate through the block parameters until either one is found that is not 300 // a local void*, or the block is valid. 301 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 302 I != E; ++I, ++ArgCounter) { 303 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 304 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 305 LangAS::opencl_local) { 306 // Get the location of the error. If a block literal has been passed 307 // (BlockExpr) then we can point straight to the offending argument, 308 // else we just point to the variable reference. 309 SourceLocation ErrorLoc; 310 if (isa<BlockExpr>(BlockArg)) { 311 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 312 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart(); 313 } else if (isa<DeclRefExpr>(BlockArg)) { 314 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart(); 315 } 316 S.Diag(ErrorLoc, 317 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 318 IllegalParams = true; 319 } 320 } 321 322 return IllegalParams; 323 } 324 325 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 326 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 327 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension) 328 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 329 return true; 330 } 331 return false; 332 } 333 334 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 335 if (checkArgCount(S, TheCall, 2)) 336 return true; 337 338 if (checkOpenCLSubgroupExt(S, TheCall)) 339 return true; 340 341 // First argument is an ndrange_t type. 342 Expr *NDRangeArg = TheCall->getArg(0); 343 if (NDRangeArg->getType().getAsString() != "ndrange_t") { 344 S.Diag(NDRangeArg->getLocStart(), 345 diag::err_opencl_builtin_expected_type) 346 << TheCall->getDirectCallee() << "'ndrange_t'"; 347 return true; 348 } 349 350 Expr *BlockArg = TheCall->getArg(1); 351 if (!isBlockPointer(BlockArg)) { 352 S.Diag(BlockArg->getLocStart(), 353 diag::err_opencl_builtin_expected_type) 354 << TheCall->getDirectCallee() << "block"; 355 return true; 356 } 357 return checkOpenCLBlockArgs(S, BlockArg); 358 } 359 360 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 361 /// get_kernel_work_group_size 362 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 363 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 364 if (checkArgCount(S, TheCall, 1)) 365 return true; 366 367 Expr *BlockArg = TheCall->getArg(0); 368 if (!isBlockPointer(BlockArg)) { 369 S.Diag(BlockArg->getLocStart(), 370 diag::err_opencl_builtin_expected_type) 371 << TheCall->getDirectCallee() << "block"; 372 return true; 373 } 374 return checkOpenCLBlockArgs(S, BlockArg); 375 } 376 377 /// Diagnose integer type and any valid implicit conversion to it. 378 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 379 const QualType &IntType); 380 381 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 382 unsigned Start, unsigned End) { 383 bool IllegalParams = false; 384 for (unsigned I = Start; I <= End; ++I) 385 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 386 S.Context.getSizeType()); 387 return IllegalParams; 388 } 389 390 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 391 /// 'local void*' parameter of passed block. 392 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 393 Expr *BlockArg, 394 unsigned NumNonVarArgs) { 395 const BlockPointerType *BPT = 396 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 397 unsigned NumBlockParams = 398 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 399 unsigned TotalNumArgs = TheCall->getNumArgs(); 400 401 // For each argument passed to the block, a corresponding uint needs to 402 // be passed to describe the size of the local memory. 403 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 404 S.Diag(TheCall->getLocStart(), 405 diag::err_opencl_enqueue_kernel_local_size_args); 406 return true; 407 } 408 409 // Check that the sizes of the local memory are specified by integers. 410 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 411 TotalNumArgs - 1); 412 } 413 414 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 415 /// overload formats specified in Table 6.13.17.1. 416 /// int enqueue_kernel(queue_t queue, 417 /// kernel_enqueue_flags_t flags, 418 /// const ndrange_t ndrange, 419 /// void (^block)(void)) 420 /// int enqueue_kernel(queue_t queue, 421 /// kernel_enqueue_flags_t flags, 422 /// const ndrange_t ndrange, 423 /// uint num_events_in_wait_list, 424 /// clk_event_t *event_wait_list, 425 /// clk_event_t *event_ret, 426 /// void (^block)(void)) 427 /// int enqueue_kernel(queue_t queue, 428 /// kernel_enqueue_flags_t flags, 429 /// const ndrange_t ndrange, 430 /// void (^block)(local void*, ...), 431 /// uint size0, ...) 432 /// int enqueue_kernel(queue_t queue, 433 /// kernel_enqueue_flags_t flags, 434 /// const ndrange_t ndrange, 435 /// uint num_events_in_wait_list, 436 /// clk_event_t *event_wait_list, 437 /// clk_event_t *event_ret, 438 /// void (^block)(local void*, ...), 439 /// uint size0, ...) 440 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 441 unsigned NumArgs = TheCall->getNumArgs(); 442 443 if (NumArgs < 4) { 444 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args); 445 return true; 446 } 447 448 Expr *Arg0 = TheCall->getArg(0); 449 Expr *Arg1 = TheCall->getArg(1); 450 Expr *Arg2 = TheCall->getArg(2); 451 Expr *Arg3 = TheCall->getArg(3); 452 453 // First argument always needs to be a queue_t type. 454 if (!Arg0->getType()->isQueueT()) { 455 S.Diag(TheCall->getArg(0)->getLocStart(), 456 diag::err_opencl_builtin_expected_type) 457 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 458 return true; 459 } 460 461 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 462 if (!Arg1->getType()->isIntegerType()) { 463 S.Diag(TheCall->getArg(1)->getLocStart(), 464 diag::err_opencl_builtin_expected_type) 465 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 466 return true; 467 } 468 469 // Third argument is always an ndrange_t type. 470 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 471 S.Diag(TheCall->getArg(2)->getLocStart(), 472 diag::err_opencl_builtin_expected_type) 473 << TheCall->getDirectCallee() << "'ndrange_t'"; 474 return true; 475 } 476 477 // With four arguments, there is only one form that the function could be 478 // called in: no events and no variable arguments. 479 if (NumArgs == 4) { 480 // check that the last argument is the right block type. 481 if (!isBlockPointer(Arg3)) { 482 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type) 483 << TheCall->getDirectCallee() << "block"; 484 return true; 485 } 486 // we have a block type, check the prototype 487 const BlockPointerType *BPT = 488 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 489 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 490 S.Diag(Arg3->getLocStart(), 491 diag::err_opencl_enqueue_kernel_blocks_no_args); 492 return true; 493 } 494 return false; 495 } 496 // we can have block + varargs. 497 if (isBlockPointer(Arg3)) 498 return (checkOpenCLBlockArgs(S, Arg3) || 499 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 500 // last two cases with either exactly 7 args or 7 args and varargs. 501 if (NumArgs >= 7) { 502 // check common block argument. 503 Expr *Arg6 = TheCall->getArg(6); 504 if (!isBlockPointer(Arg6)) { 505 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type) 506 << TheCall->getDirectCallee() << "block"; 507 return true; 508 } 509 if (checkOpenCLBlockArgs(S, Arg6)) 510 return true; 511 512 // Forth argument has to be any integer type. 513 if (!Arg3->getType()->isIntegerType()) { 514 S.Diag(TheCall->getArg(3)->getLocStart(), 515 diag::err_opencl_builtin_expected_type) 516 << TheCall->getDirectCallee() << "integer"; 517 return true; 518 } 519 // check remaining common arguments. 520 Expr *Arg4 = TheCall->getArg(4); 521 Expr *Arg5 = TheCall->getArg(5); 522 523 // Fifth argument is always passed as a pointer to clk_event_t. 524 if (!Arg4->isNullPointerConstant(S.Context, 525 Expr::NPC_ValueDependentIsNotNull) && 526 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 527 S.Diag(TheCall->getArg(4)->getLocStart(), 528 diag::err_opencl_builtin_expected_type) 529 << TheCall->getDirectCallee() 530 << S.Context.getPointerType(S.Context.OCLClkEventTy); 531 return true; 532 } 533 534 // Sixth argument is always passed as a pointer to clk_event_t. 535 if (!Arg5->isNullPointerConstant(S.Context, 536 Expr::NPC_ValueDependentIsNotNull) && 537 !(Arg5->getType()->isPointerType() && 538 Arg5->getType()->getPointeeType()->isClkEventT())) { 539 S.Diag(TheCall->getArg(5)->getLocStart(), 540 diag::err_opencl_builtin_expected_type) 541 << TheCall->getDirectCallee() 542 << S.Context.getPointerType(S.Context.OCLClkEventTy); 543 return true; 544 } 545 546 if (NumArgs == 7) 547 return false; 548 549 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 550 } 551 552 // None of the specific case has been detected, give generic error 553 S.Diag(TheCall->getLocStart(), 554 diag::err_opencl_enqueue_kernel_incorrect_args); 555 return true; 556 } 557 558 /// Returns OpenCL access qual. 559 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 560 return D->getAttr<OpenCLAccessAttr>(); 561 } 562 563 /// Returns true if pipe element type is different from the pointer. 564 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 565 const Expr *Arg0 = Call->getArg(0); 566 // First argument type should always be pipe. 567 if (!Arg0->getType()->isPipeType()) { 568 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 569 << Call->getDirectCallee() << Arg0->getSourceRange(); 570 return true; 571 } 572 OpenCLAccessAttr *AccessQual = 573 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 574 // Validates the access qualifier is compatible with the call. 575 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 576 // read_only and write_only, and assumed to be read_only if no qualifier is 577 // specified. 578 switch (Call->getDirectCallee()->getBuiltinID()) { 579 case Builtin::BIread_pipe: 580 case Builtin::BIreserve_read_pipe: 581 case Builtin::BIcommit_read_pipe: 582 case Builtin::BIwork_group_reserve_read_pipe: 583 case Builtin::BIsub_group_reserve_read_pipe: 584 case Builtin::BIwork_group_commit_read_pipe: 585 case Builtin::BIsub_group_commit_read_pipe: 586 if (!(!AccessQual || AccessQual->isReadOnly())) { 587 S.Diag(Arg0->getLocStart(), 588 diag::err_opencl_builtin_pipe_invalid_access_modifier) 589 << "read_only" << Arg0->getSourceRange(); 590 return true; 591 } 592 break; 593 case Builtin::BIwrite_pipe: 594 case Builtin::BIreserve_write_pipe: 595 case Builtin::BIcommit_write_pipe: 596 case Builtin::BIwork_group_reserve_write_pipe: 597 case Builtin::BIsub_group_reserve_write_pipe: 598 case Builtin::BIwork_group_commit_write_pipe: 599 case Builtin::BIsub_group_commit_write_pipe: 600 if (!(AccessQual && AccessQual->isWriteOnly())) { 601 S.Diag(Arg0->getLocStart(), 602 diag::err_opencl_builtin_pipe_invalid_access_modifier) 603 << "write_only" << Arg0->getSourceRange(); 604 return true; 605 } 606 break; 607 default: 608 break; 609 } 610 return false; 611 } 612 613 /// Returns true if pipe element type is different from the pointer. 614 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 615 const Expr *Arg0 = Call->getArg(0); 616 const Expr *ArgIdx = Call->getArg(Idx); 617 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 618 const QualType EltTy = PipeTy->getElementType(); 619 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 620 // The Idx argument should be a pointer and the type of the pointer and 621 // the type of pipe element should also be the same. 622 if (!ArgTy || 623 !S.Context.hasSameType( 624 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 625 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 626 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 627 << ArgIdx->getType() << ArgIdx->getSourceRange(); 628 return true; 629 } 630 return false; 631 } 632 633 // \brief Performs semantic analysis for the read/write_pipe call. 634 // \param S Reference to the semantic analyzer. 635 // \param Call A pointer to the builtin call. 636 // \return True if a semantic error has been found, false otherwise. 637 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 638 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 639 // functions have two forms. 640 switch (Call->getNumArgs()) { 641 case 2: { 642 if (checkOpenCLPipeArg(S, Call)) 643 return true; 644 // The call with 2 arguments should be 645 // read/write_pipe(pipe T, T*). 646 // Check packet type T. 647 if (checkOpenCLPipePacketType(S, Call, 1)) 648 return true; 649 } break; 650 651 case 4: { 652 if (checkOpenCLPipeArg(S, Call)) 653 return true; 654 // The call with 4 arguments should be 655 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 656 // Check reserve_id_t. 657 if (!Call->getArg(1)->getType()->isReserveIDT()) { 658 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 659 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 660 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 661 return true; 662 } 663 664 // Check the index. 665 const Expr *Arg2 = Call->getArg(2); 666 if (!Arg2->getType()->isIntegerType() && 667 !Arg2->getType()->isUnsignedIntegerType()) { 668 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 669 << Call->getDirectCallee() << S.Context.UnsignedIntTy 670 << Arg2->getType() << Arg2->getSourceRange(); 671 return true; 672 } 673 674 // Check packet type T. 675 if (checkOpenCLPipePacketType(S, Call, 3)) 676 return true; 677 } break; 678 default: 679 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) 680 << Call->getDirectCallee() << Call->getSourceRange(); 681 return true; 682 } 683 684 return false; 685 } 686 687 // \brief Performs a semantic analysis on the {work_group_/sub_group_ 688 // /_}reserve_{read/write}_pipe 689 // \param S Reference to the semantic analyzer. 690 // \param Call The call to the builtin function to be analyzed. 691 // \return True if a semantic error was found, false otherwise. 692 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 693 if (checkArgCount(S, Call, 2)) 694 return true; 695 696 if (checkOpenCLPipeArg(S, Call)) 697 return true; 698 699 // Check the reserve size. 700 if (!Call->getArg(1)->getType()->isIntegerType() && 701 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 702 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 703 << Call->getDirectCallee() << S.Context.UnsignedIntTy 704 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 705 return true; 706 } 707 708 // Since return type of reserve_read/write_pipe built-in function is 709 // reserve_id_t, which is not defined in the builtin def file , we used int 710 // as return type and need to override the return type of these functions. 711 Call->setType(S.Context.OCLReserveIDTy); 712 713 return false; 714 } 715 716 // \brief Performs a semantic analysis on {work_group_/sub_group_ 717 // /_}commit_{read/write}_pipe 718 // \param S Reference to the semantic analyzer. 719 // \param Call The call to the builtin function to be analyzed. 720 // \return True if a semantic error was found, false otherwise. 721 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 722 if (checkArgCount(S, Call, 2)) 723 return true; 724 725 if (checkOpenCLPipeArg(S, Call)) 726 return true; 727 728 // Check reserve_id_t. 729 if (!Call->getArg(1)->getType()->isReserveIDT()) { 730 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 731 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 732 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 733 return true; 734 } 735 736 return false; 737 } 738 739 // \brief Performs a semantic analysis on the call to built-in Pipe 740 // Query Functions. 741 // \param S Reference to the semantic analyzer. 742 // \param Call The call to the builtin function to be analyzed. 743 // \return True if a semantic error was found, false otherwise. 744 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 745 if (checkArgCount(S, Call, 1)) 746 return true; 747 748 if (!Call->getArg(0)->getType()->isPipeType()) { 749 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 750 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 751 return true; 752 } 753 754 return false; 755 } 756 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions. 757 // \brief Performs semantic analysis for the to_global/local/private call. 758 // \param S Reference to the semantic analyzer. 759 // \param BuiltinID ID of the builtin function. 760 // \param Call A pointer to the builtin call. 761 // \return True if a semantic error has been found, false otherwise. 762 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 763 CallExpr *Call) { 764 if (Call->getNumArgs() != 1) { 765 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 766 << Call->getDirectCallee() << Call->getSourceRange(); 767 return true; 768 } 769 770 auto RT = Call->getArg(0)->getType(); 771 if (!RT->isPointerType() || RT->getPointeeType() 772 .getAddressSpace() == LangAS::opencl_constant) { 773 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 774 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 775 return true; 776 } 777 778 RT = RT->getPointeeType(); 779 auto Qual = RT.getQualifiers(); 780 switch (BuiltinID) { 781 case Builtin::BIto_global: 782 Qual.setAddressSpace(LangAS::opencl_global); 783 break; 784 case Builtin::BIto_local: 785 Qual.setAddressSpace(LangAS::opencl_local); 786 break; 787 default: 788 Qual.removeAddressSpace(); 789 } 790 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 791 RT.getUnqualifiedType(), Qual))); 792 793 return false; 794 } 795 796 ExprResult 797 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 798 CallExpr *TheCall) { 799 ExprResult TheCallResult(TheCall); 800 801 // Find out if any arguments are required to be integer constant expressions. 802 unsigned ICEArguments = 0; 803 ASTContext::GetBuiltinTypeError Error; 804 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 805 if (Error != ASTContext::GE_None) 806 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 807 808 // If any arguments are required to be ICE's, check and diagnose. 809 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 810 // Skip arguments not required to be ICE's. 811 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 812 813 llvm::APSInt Result; 814 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 815 return true; 816 ICEArguments &= ~(1 << ArgNo); 817 } 818 819 switch (BuiltinID) { 820 case Builtin::BI__builtin___CFStringMakeConstantString: 821 assert(TheCall->getNumArgs() == 1 && 822 "Wrong # arguments to builtin CFStringMakeConstantString"); 823 if (CheckObjCString(TheCall->getArg(0))) 824 return ExprError(); 825 break; 826 case Builtin::BI__builtin_ms_va_start: 827 case Builtin::BI__builtin_stdarg_start: 828 case Builtin::BI__builtin_va_start: 829 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 830 return ExprError(); 831 break; 832 case Builtin::BI__va_start: { 833 switch (Context.getTargetInfo().getTriple().getArch()) { 834 case llvm::Triple::arm: 835 case llvm::Triple::thumb: 836 if (SemaBuiltinVAStartARM(TheCall)) 837 return ExprError(); 838 break; 839 default: 840 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 841 return ExprError(); 842 break; 843 } 844 break; 845 } 846 case Builtin::BI__builtin_isgreater: 847 case Builtin::BI__builtin_isgreaterequal: 848 case Builtin::BI__builtin_isless: 849 case Builtin::BI__builtin_islessequal: 850 case Builtin::BI__builtin_islessgreater: 851 case Builtin::BI__builtin_isunordered: 852 if (SemaBuiltinUnorderedCompare(TheCall)) 853 return ExprError(); 854 break; 855 case Builtin::BI__builtin_fpclassify: 856 if (SemaBuiltinFPClassification(TheCall, 6)) 857 return ExprError(); 858 break; 859 case Builtin::BI__builtin_isfinite: 860 case Builtin::BI__builtin_isinf: 861 case Builtin::BI__builtin_isinf_sign: 862 case Builtin::BI__builtin_isnan: 863 case Builtin::BI__builtin_isnormal: 864 if (SemaBuiltinFPClassification(TheCall, 1)) 865 return ExprError(); 866 break; 867 case Builtin::BI__builtin_shufflevector: 868 return SemaBuiltinShuffleVector(TheCall); 869 // TheCall will be freed by the smart pointer here, but that's fine, since 870 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 871 case Builtin::BI__builtin_prefetch: 872 if (SemaBuiltinPrefetch(TheCall)) 873 return ExprError(); 874 break; 875 case Builtin::BI__builtin_alloca_with_align: 876 if (SemaBuiltinAllocaWithAlign(TheCall)) 877 return ExprError(); 878 break; 879 case Builtin::BI__assume: 880 case Builtin::BI__builtin_assume: 881 if (SemaBuiltinAssume(TheCall)) 882 return ExprError(); 883 break; 884 case Builtin::BI__builtin_assume_aligned: 885 if (SemaBuiltinAssumeAligned(TheCall)) 886 return ExprError(); 887 break; 888 case Builtin::BI__builtin_object_size: 889 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 890 return ExprError(); 891 break; 892 case Builtin::BI__builtin_longjmp: 893 if (SemaBuiltinLongjmp(TheCall)) 894 return ExprError(); 895 break; 896 case Builtin::BI__builtin_setjmp: 897 if (SemaBuiltinSetjmp(TheCall)) 898 return ExprError(); 899 break; 900 case Builtin::BI_setjmp: 901 case Builtin::BI_setjmpex: 902 if (checkArgCount(*this, TheCall, 1)) 903 return true; 904 break; 905 906 case Builtin::BI__builtin_classify_type: 907 if (checkArgCount(*this, TheCall, 1)) return true; 908 TheCall->setType(Context.IntTy); 909 break; 910 case Builtin::BI__builtin_constant_p: 911 if (checkArgCount(*this, TheCall, 1)) return true; 912 TheCall->setType(Context.IntTy); 913 break; 914 case Builtin::BI__sync_fetch_and_add: 915 case Builtin::BI__sync_fetch_and_add_1: 916 case Builtin::BI__sync_fetch_and_add_2: 917 case Builtin::BI__sync_fetch_and_add_4: 918 case Builtin::BI__sync_fetch_and_add_8: 919 case Builtin::BI__sync_fetch_and_add_16: 920 case Builtin::BI__sync_fetch_and_sub: 921 case Builtin::BI__sync_fetch_and_sub_1: 922 case Builtin::BI__sync_fetch_and_sub_2: 923 case Builtin::BI__sync_fetch_and_sub_4: 924 case Builtin::BI__sync_fetch_and_sub_8: 925 case Builtin::BI__sync_fetch_and_sub_16: 926 case Builtin::BI__sync_fetch_and_or: 927 case Builtin::BI__sync_fetch_and_or_1: 928 case Builtin::BI__sync_fetch_and_or_2: 929 case Builtin::BI__sync_fetch_and_or_4: 930 case Builtin::BI__sync_fetch_and_or_8: 931 case Builtin::BI__sync_fetch_and_or_16: 932 case Builtin::BI__sync_fetch_and_and: 933 case Builtin::BI__sync_fetch_and_and_1: 934 case Builtin::BI__sync_fetch_and_and_2: 935 case Builtin::BI__sync_fetch_and_and_4: 936 case Builtin::BI__sync_fetch_and_and_8: 937 case Builtin::BI__sync_fetch_and_and_16: 938 case Builtin::BI__sync_fetch_and_xor: 939 case Builtin::BI__sync_fetch_and_xor_1: 940 case Builtin::BI__sync_fetch_and_xor_2: 941 case Builtin::BI__sync_fetch_and_xor_4: 942 case Builtin::BI__sync_fetch_and_xor_8: 943 case Builtin::BI__sync_fetch_and_xor_16: 944 case Builtin::BI__sync_fetch_and_nand: 945 case Builtin::BI__sync_fetch_and_nand_1: 946 case Builtin::BI__sync_fetch_and_nand_2: 947 case Builtin::BI__sync_fetch_and_nand_4: 948 case Builtin::BI__sync_fetch_and_nand_8: 949 case Builtin::BI__sync_fetch_and_nand_16: 950 case Builtin::BI__sync_add_and_fetch: 951 case Builtin::BI__sync_add_and_fetch_1: 952 case Builtin::BI__sync_add_and_fetch_2: 953 case Builtin::BI__sync_add_and_fetch_4: 954 case Builtin::BI__sync_add_and_fetch_8: 955 case Builtin::BI__sync_add_and_fetch_16: 956 case Builtin::BI__sync_sub_and_fetch: 957 case Builtin::BI__sync_sub_and_fetch_1: 958 case Builtin::BI__sync_sub_and_fetch_2: 959 case Builtin::BI__sync_sub_and_fetch_4: 960 case Builtin::BI__sync_sub_and_fetch_8: 961 case Builtin::BI__sync_sub_and_fetch_16: 962 case Builtin::BI__sync_and_and_fetch: 963 case Builtin::BI__sync_and_and_fetch_1: 964 case Builtin::BI__sync_and_and_fetch_2: 965 case Builtin::BI__sync_and_and_fetch_4: 966 case Builtin::BI__sync_and_and_fetch_8: 967 case Builtin::BI__sync_and_and_fetch_16: 968 case Builtin::BI__sync_or_and_fetch: 969 case Builtin::BI__sync_or_and_fetch_1: 970 case Builtin::BI__sync_or_and_fetch_2: 971 case Builtin::BI__sync_or_and_fetch_4: 972 case Builtin::BI__sync_or_and_fetch_8: 973 case Builtin::BI__sync_or_and_fetch_16: 974 case Builtin::BI__sync_xor_and_fetch: 975 case Builtin::BI__sync_xor_and_fetch_1: 976 case Builtin::BI__sync_xor_and_fetch_2: 977 case Builtin::BI__sync_xor_and_fetch_4: 978 case Builtin::BI__sync_xor_and_fetch_8: 979 case Builtin::BI__sync_xor_and_fetch_16: 980 case Builtin::BI__sync_nand_and_fetch: 981 case Builtin::BI__sync_nand_and_fetch_1: 982 case Builtin::BI__sync_nand_and_fetch_2: 983 case Builtin::BI__sync_nand_and_fetch_4: 984 case Builtin::BI__sync_nand_and_fetch_8: 985 case Builtin::BI__sync_nand_and_fetch_16: 986 case Builtin::BI__sync_val_compare_and_swap: 987 case Builtin::BI__sync_val_compare_and_swap_1: 988 case Builtin::BI__sync_val_compare_and_swap_2: 989 case Builtin::BI__sync_val_compare_and_swap_4: 990 case Builtin::BI__sync_val_compare_and_swap_8: 991 case Builtin::BI__sync_val_compare_and_swap_16: 992 case Builtin::BI__sync_bool_compare_and_swap: 993 case Builtin::BI__sync_bool_compare_and_swap_1: 994 case Builtin::BI__sync_bool_compare_and_swap_2: 995 case Builtin::BI__sync_bool_compare_and_swap_4: 996 case Builtin::BI__sync_bool_compare_and_swap_8: 997 case Builtin::BI__sync_bool_compare_and_swap_16: 998 case Builtin::BI__sync_lock_test_and_set: 999 case Builtin::BI__sync_lock_test_and_set_1: 1000 case Builtin::BI__sync_lock_test_and_set_2: 1001 case Builtin::BI__sync_lock_test_and_set_4: 1002 case Builtin::BI__sync_lock_test_and_set_8: 1003 case Builtin::BI__sync_lock_test_and_set_16: 1004 case Builtin::BI__sync_lock_release: 1005 case Builtin::BI__sync_lock_release_1: 1006 case Builtin::BI__sync_lock_release_2: 1007 case Builtin::BI__sync_lock_release_4: 1008 case Builtin::BI__sync_lock_release_8: 1009 case Builtin::BI__sync_lock_release_16: 1010 case Builtin::BI__sync_swap: 1011 case Builtin::BI__sync_swap_1: 1012 case Builtin::BI__sync_swap_2: 1013 case Builtin::BI__sync_swap_4: 1014 case Builtin::BI__sync_swap_8: 1015 case Builtin::BI__sync_swap_16: 1016 return SemaBuiltinAtomicOverloaded(TheCallResult); 1017 case Builtin::BI__builtin_nontemporal_load: 1018 case Builtin::BI__builtin_nontemporal_store: 1019 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1020 #define BUILTIN(ID, TYPE, ATTRS) 1021 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1022 case Builtin::BI##ID: \ 1023 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1024 #include "clang/Basic/Builtins.def" 1025 case Builtin::BI__annotation: 1026 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1027 return ExprError(); 1028 break; 1029 case Builtin::BI__builtin_annotation: 1030 if (SemaBuiltinAnnotation(*this, TheCall)) 1031 return ExprError(); 1032 break; 1033 case Builtin::BI__builtin_addressof: 1034 if (SemaBuiltinAddressof(*this, TheCall)) 1035 return ExprError(); 1036 break; 1037 case Builtin::BI__builtin_add_overflow: 1038 case Builtin::BI__builtin_sub_overflow: 1039 case Builtin::BI__builtin_mul_overflow: 1040 if (SemaBuiltinOverflow(*this, TheCall)) 1041 return ExprError(); 1042 break; 1043 case Builtin::BI__builtin_operator_new: 1044 case Builtin::BI__builtin_operator_delete: 1045 if (!getLangOpts().CPlusPlus) { 1046 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 1047 << (BuiltinID == Builtin::BI__builtin_operator_new 1048 ? "__builtin_operator_new" 1049 : "__builtin_operator_delete") 1050 << "C++"; 1051 return ExprError(); 1052 } 1053 // CodeGen assumes it can find the global new and delete to call, 1054 // so ensure that they are declared. 1055 DeclareGlobalNewDelete(); 1056 break; 1057 1058 // check secure string manipulation functions where overflows 1059 // are detectable at compile time 1060 case Builtin::BI__builtin___memcpy_chk: 1061 case Builtin::BI__builtin___memmove_chk: 1062 case Builtin::BI__builtin___memset_chk: 1063 case Builtin::BI__builtin___strlcat_chk: 1064 case Builtin::BI__builtin___strlcpy_chk: 1065 case Builtin::BI__builtin___strncat_chk: 1066 case Builtin::BI__builtin___strncpy_chk: 1067 case Builtin::BI__builtin___stpncpy_chk: 1068 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 1069 break; 1070 case Builtin::BI__builtin___memccpy_chk: 1071 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 1072 break; 1073 case Builtin::BI__builtin___snprintf_chk: 1074 case Builtin::BI__builtin___vsnprintf_chk: 1075 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 1076 break; 1077 case Builtin::BI__builtin_call_with_static_chain: 1078 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1079 return ExprError(); 1080 break; 1081 case Builtin::BI__exception_code: 1082 case Builtin::BI_exception_code: 1083 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1084 diag::err_seh___except_block)) 1085 return ExprError(); 1086 break; 1087 case Builtin::BI__exception_info: 1088 case Builtin::BI_exception_info: 1089 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1090 diag::err_seh___except_filter)) 1091 return ExprError(); 1092 break; 1093 case Builtin::BI__GetExceptionInfo: 1094 if (checkArgCount(*this, TheCall, 1)) 1095 return ExprError(); 1096 1097 if (CheckCXXThrowOperand( 1098 TheCall->getLocStart(), 1099 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1100 TheCall)) 1101 return ExprError(); 1102 1103 TheCall->setType(Context.VoidPtrTy); 1104 break; 1105 // OpenCL v2.0, s6.13.16 - Pipe functions 1106 case Builtin::BIread_pipe: 1107 case Builtin::BIwrite_pipe: 1108 // Since those two functions are declared with var args, we need a semantic 1109 // check for the argument. 1110 if (SemaBuiltinRWPipe(*this, TheCall)) 1111 return ExprError(); 1112 TheCall->setType(Context.IntTy); 1113 break; 1114 case Builtin::BIreserve_read_pipe: 1115 case Builtin::BIreserve_write_pipe: 1116 case Builtin::BIwork_group_reserve_read_pipe: 1117 case Builtin::BIwork_group_reserve_write_pipe: 1118 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1119 return ExprError(); 1120 break; 1121 case Builtin::BIsub_group_reserve_read_pipe: 1122 case Builtin::BIsub_group_reserve_write_pipe: 1123 if (checkOpenCLSubgroupExt(*this, TheCall) || 1124 SemaBuiltinReserveRWPipe(*this, TheCall)) 1125 return ExprError(); 1126 break; 1127 case Builtin::BIcommit_read_pipe: 1128 case Builtin::BIcommit_write_pipe: 1129 case Builtin::BIwork_group_commit_read_pipe: 1130 case Builtin::BIwork_group_commit_write_pipe: 1131 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1132 return ExprError(); 1133 break; 1134 case Builtin::BIsub_group_commit_read_pipe: 1135 case Builtin::BIsub_group_commit_write_pipe: 1136 if (checkOpenCLSubgroupExt(*this, TheCall) || 1137 SemaBuiltinCommitRWPipe(*this, TheCall)) 1138 return ExprError(); 1139 break; 1140 case Builtin::BIget_pipe_num_packets: 1141 case Builtin::BIget_pipe_max_packets: 1142 if (SemaBuiltinPipePackets(*this, TheCall)) 1143 return ExprError(); 1144 TheCall->setType(Context.UnsignedIntTy); 1145 break; 1146 case Builtin::BIto_global: 1147 case Builtin::BIto_local: 1148 case Builtin::BIto_private: 1149 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1150 return ExprError(); 1151 break; 1152 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1153 case Builtin::BIenqueue_kernel: 1154 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1155 return ExprError(); 1156 break; 1157 case Builtin::BIget_kernel_work_group_size: 1158 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1159 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1160 return ExprError(); 1161 break; 1162 break; 1163 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1164 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1165 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1166 return ExprError(); 1167 break; 1168 case Builtin::BI__builtin_os_log_format: 1169 case Builtin::BI__builtin_os_log_format_buffer_size: 1170 if (SemaBuiltinOSLogFormat(TheCall)) { 1171 return ExprError(); 1172 } 1173 break; 1174 } 1175 1176 // Since the target specific builtins for each arch overlap, only check those 1177 // of the arch we are compiling for. 1178 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1179 switch (Context.getTargetInfo().getTriple().getArch()) { 1180 case llvm::Triple::arm: 1181 case llvm::Triple::armeb: 1182 case llvm::Triple::thumb: 1183 case llvm::Triple::thumbeb: 1184 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1185 return ExprError(); 1186 break; 1187 case llvm::Triple::aarch64: 1188 case llvm::Triple::aarch64_be: 1189 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1190 return ExprError(); 1191 break; 1192 case llvm::Triple::mips: 1193 case llvm::Triple::mipsel: 1194 case llvm::Triple::mips64: 1195 case llvm::Triple::mips64el: 1196 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1197 return ExprError(); 1198 break; 1199 case llvm::Triple::systemz: 1200 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1201 return ExprError(); 1202 break; 1203 case llvm::Triple::x86: 1204 case llvm::Triple::x86_64: 1205 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1206 return ExprError(); 1207 break; 1208 case llvm::Triple::ppc: 1209 case llvm::Triple::ppc64: 1210 case llvm::Triple::ppc64le: 1211 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1212 return ExprError(); 1213 break; 1214 default: 1215 break; 1216 } 1217 } 1218 1219 return TheCallResult; 1220 } 1221 1222 // Get the valid immediate range for the specified NEON type code. 1223 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1224 NeonTypeFlags Type(t); 1225 int IsQuad = ForceQuad ? true : Type.isQuad(); 1226 switch (Type.getEltType()) { 1227 case NeonTypeFlags::Int8: 1228 case NeonTypeFlags::Poly8: 1229 return shift ? 7 : (8 << IsQuad) - 1; 1230 case NeonTypeFlags::Int16: 1231 case NeonTypeFlags::Poly16: 1232 return shift ? 15 : (4 << IsQuad) - 1; 1233 case NeonTypeFlags::Int32: 1234 return shift ? 31 : (2 << IsQuad) - 1; 1235 case NeonTypeFlags::Int64: 1236 case NeonTypeFlags::Poly64: 1237 return shift ? 63 : (1 << IsQuad) - 1; 1238 case NeonTypeFlags::Poly128: 1239 return shift ? 127 : (1 << IsQuad) - 1; 1240 case NeonTypeFlags::Float16: 1241 assert(!shift && "cannot shift float types!"); 1242 return (4 << IsQuad) - 1; 1243 case NeonTypeFlags::Float32: 1244 assert(!shift && "cannot shift float types!"); 1245 return (2 << IsQuad) - 1; 1246 case NeonTypeFlags::Float64: 1247 assert(!shift && "cannot shift float types!"); 1248 return (1 << IsQuad) - 1; 1249 } 1250 llvm_unreachable("Invalid NeonTypeFlag!"); 1251 } 1252 1253 /// getNeonEltType - Return the QualType corresponding to the elements of 1254 /// the vector type specified by the NeonTypeFlags. This is used to check 1255 /// the pointer arguments for Neon load/store intrinsics. 1256 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1257 bool IsPolyUnsigned, bool IsInt64Long) { 1258 switch (Flags.getEltType()) { 1259 case NeonTypeFlags::Int8: 1260 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1261 case NeonTypeFlags::Int16: 1262 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1263 case NeonTypeFlags::Int32: 1264 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1265 case NeonTypeFlags::Int64: 1266 if (IsInt64Long) 1267 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1268 else 1269 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1270 : Context.LongLongTy; 1271 case NeonTypeFlags::Poly8: 1272 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1273 case NeonTypeFlags::Poly16: 1274 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1275 case NeonTypeFlags::Poly64: 1276 if (IsInt64Long) 1277 return Context.UnsignedLongTy; 1278 else 1279 return Context.UnsignedLongLongTy; 1280 case NeonTypeFlags::Poly128: 1281 break; 1282 case NeonTypeFlags::Float16: 1283 return Context.HalfTy; 1284 case NeonTypeFlags::Float32: 1285 return Context.FloatTy; 1286 case NeonTypeFlags::Float64: 1287 return Context.DoubleTy; 1288 } 1289 llvm_unreachable("Invalid NeonTypeFlag!"); 1290 } 1291 1292 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1293 llvm::APSInt Result; 1294 uint64_t mask = 0; 1295 unsigned TV = 0; 1296 int PtrArgNum = -1; 1297 bool HasConstPtr = false; 1298 switch (BuiltinID) { 1299 #define GET_NEON_OVERLOAD_CHECK 1300 #include "clang/Basic/arm_neon.inc" 1301 #undef GET_NEON_OVERLOAD_CHECK 1302 } 1303 1304 // For NEON intrinsics which are overloaded on vector element type, validate 1305 // the immediate which specifies which variant to emit. 1306 unsigned ImmArg = TheCall->getNumArgs()-1; 1307 if (mask) { 1308 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1309 return true; 1310 1311 TV = Result.getLimitedValue(64); 1312 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1313 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1314 << TheCall->getArg(ImmArg)->getSourceRange(); 1315 } 1316 1317 if (PtrArgNum >= 0) { 1318 // Check that pointer arguments have the specified type. 1319 Expr *Arg = TheCall->getArg(PtrArgNum); 1320 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1321 Arg = ICE->getSubExpr(); 1322 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1323 QualType RHSTy = RHS.get()->getType(); 1324 1325 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1326 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1327 Arch == llvm::Triple::aarch64_be; 1328 bool IsInt64Long = 1329 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1330 QualType EltTy = 1331 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1332 if (HasConstPtr) 1333 EltTy = EltTy.withConst(); 1334 QualType LHSTy = Context.getPointerType(EltTy); 1335 AssignConvertType ConvTy; 1336 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1337 if (RHS.isInvalid()) 1338 return true; 1339 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1340 RHS.get(), AA_Assigning)) 1341 return true; 1342 } 1343 1344 // For NEON intrinsics which take an immediate value as part of the 1345 // instruction, range check them here. 1346 unsigned i = 0, l = 0, u = 0; 1347 switch (BuiltinID) { 1348 default: 1349 return false; 1350 #define GET_NEON_IMMEDIATE_CHECK 1351 #include "clang/Basic/arm_neon.inc" 1352 #undef GET_NEON_IMMEDIATE_CHECK 1353 } 1354 1355 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1356 } 1357 1358 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1359 unsigned MaxWidth) { 1360 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1361 BuiltinID == ARM::BI__builtin_arm_ldaex || 1362 BuiltinID == ARM::BI__builtin_arm_strex || 1363 BuiltinID == ARM::BI__builtin_arm_stlex || 1364 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1365 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1366 BuiltinID == AArch64::BI__builtin_arm_strex || 1367 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1368 "unexpected ARM builtin"); 1369 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1370 BuiltinID == ARM::BI__builtin_arm_ldaex || 1371 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1372 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1373 1374 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1375 1376 // Ensure that we have the proper number of arguments. 1377 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1378 return true; 1379 1380 // Inspect the pointer argument of the atomic builtin. This should always be 1381 // a pointer type, whose element is an integral scalar or pointer type. 1382 // Because it is a pointer type, we don't have to worry about any implicit 1383 // casts here. 1384 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1385 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1386 if (PointerArgRes.isInvalid()) 1387 return true; 1388 PointerArg = PointerArgRes.get(); 1389 1390 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1391 if (!pointerType) { 1392 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1393 << PointerArg->getType() << PointerArg->getSourceRange(); 1394 return true; 1395 } 1396 1397 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1398 // task is to insert the appropriate casts into the AST. First work out just 1399 // what the appropriate type is. 1400 QualType ValType = pointerType->getPointeeType(); 1401 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1402 if (IsLdrex) 1403 AddrType.addConst(); 1404 1405 // Issue a warning if the cast is dodgy. 1406 CastKind CastNeeded = CK_NoOp; 1407 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1408 CastNeeded = CK_BitCast; 1409 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1410 << PointerArg->getType() 1411 << Context.getPointerType(AddrType) 1412 << AA_Passing << PointerArg->getSourceRange(); 1413 } 1414 1415 // Finally, do the cast and replace the argument with the corrected version. 1416 AddrType = Context.getPointerType(AddrType); 1417 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1418 if (PointerArgRes.isInvalid()) 1419 return true; 1420 PointerArg = PointerArgRes.get(); 1421 1422 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1423 1424 // In general, we allow ints, floats and pointers to be loaded and stored. 1425 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1426 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1427 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1428 << PointerArg->getType() << PointerArg->getSourceRange(); 1429 return true; 1430 } 1431 1432 // But ARM doesn't have instructions to deal with 128-bit versions. 1433 if (Context.getTypeSize(ValType) > MaxWidth) { 1434 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1435 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1436 << PointerArg->getType() << PointerArg->getSourceRange(); 1437 return true; 1438 } 1439 1440 switch (ValType.getObjCLifetime()) { 1441 case Qualifiers::OCL_None: 1442 case Qualifiers::OCL_ExplicitNone: 1443 // okay 1444 break; 1445 1446 case Qualifiers::OCL_Weak: 1447 case Qualifiers::OCL_Strong: 1448 case Qualifiers::OCL_Autoreleasing: 1449 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1450 << ValType << PointerArg->getSourceRange(); 1451 return true; 1452 } 1453 1454 if (IsLdrex) { 1455 TheCall->setType(ValType); 1456 return false; 1457 } 1458 1459 // Initialize the argument to be stored. 1460 ExprResult ValArg = TheCall->getArg(0); 1461 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1462 Context, ValType, /*consume*/ false); 1463 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1464 if (ValArg.isInvalid()) 1465 return true; 1466 TheCall->setArg(0, ValArg.get()); 1467 1468 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1469 // but the custom checker bypasses all default analysis. 1470 TheCall->setType(Context.IntTy); 1471 return false; 1472 } 1473 1474 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1475 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1476 BuiltinID == ARM::BI__builtin_arm_ldaex || 1477 BuiltinID == ARM::BI__builtin_arm_strex || 1478 BuiltinID == ARM::BI__builtin_arm_stlex) { 1479 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1480 } 1481 1482 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1483 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1484 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1485 } 1486 1487 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1488 BuiltinID == ARM::BI__builtin_arm_wsr64) 1489 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1490 1491 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1492 BuiltinID == ARM::BI__builtin_arm_rsrp || 1493 BuiltinID == ARM::BI__builtin_arm_wsr || 1494 BuiltinID == ARM::BI__builtin_arm_wsrp) 1495 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1496 1497 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1498 return true; 1499 1500 // For intrinsics which take an immediate value as part of the instruction, 1501 // range check them here. 1502 unsigned i = 0, l = 0, u = 0; 1503 switch (BuiltinID) { 1504 default: return false; 1505 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 1506 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 1507 case ARM::BI__builtin_arm_vcvtr_f: 1508 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 1509 case ARM::BI__builtin_arm_dmb: 1510 case ARM::BI__builtin_arm_dsb: 1511 case ARM::BI__builtin_arm_isb: 1512 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break; 1513 } 1514 1515 // FIXME: VFP Intrinsics should error if VFP not present. 1516 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1517 } 1518 1519 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1520 CallExpr *TheCall) { 1521 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1522 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1523 BuiltinID == AArch64::BI__builtin_arm_strex || 1524 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1525 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1526 } 1527 1528 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1529 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1530 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1531 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1532 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1533 } 1534 1535 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1536 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1537 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1538 1539 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1540 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1541 BuiltinID == AArch64::BI__builtin_arm_wsr || 1542 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1543 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1544 1545 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1546 return true; 1547 1548 // For intrinsics which take an immediate value as part of the instruction, 1549 // range check them here. 1550 unsigned i = 0, l = 0, u = 0; 1551 switch (BuiltinID) { 1552 default: return false; 1553 case AArch64::BI__builtin_arm_dmb: 1554 case AArch64::BI__builtin_arm_dsb: 1555 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1556 } 1557 1558 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1559 } 1560 1561 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1562 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1563 // ordering for DSP is unspecified. MSA is ordered by the data format used 1564 // by the underlying instruction i.e., df/m, df/n and then by size. 1565 // 1566 // FIXME: The size tests here should instead be tablegen'd along with the 1567 // definitions from include/clang/Basic/BuiltinsMips.def. 1568 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1569 // be too. 1570 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1571 unsigned i = 0, l = 0, u = 0, m = 0; 1572 switch (BuiltinID) { 1573 default: return false; 1574 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1575 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1576 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1577 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1578 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1579 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1580 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1581 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1582 // df/m field. 1583 // These intrinsics take an unsigned 3 bit immediate. 1584 case Mips::BI__builtin_msa_bclri_b: 1585 case Mips::BI__builtin_msa_bnegi_b: 1586 case Mips::BI__builtin_msa_bseti_b: 1587 case Mips::BI__builtin_msa_sat_s_b: 1588 case Mips::BI__builtin_msa_sat_u_b: 1589 case Mips::BI__builtin_msa_slli_b: 1590 case Mips::BI__builtin_msa_srai_b: 1591 case Mips::BI__builtin_msa_srari_b: 1592 case Mips::BI__builtin_msa_srli_b: 1593 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1594 case Mips::BI__builtin_msa_binsli_b: 1595 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1596 // These intrinsics take an unsigned 4 bit immediate. 1597 case Mips::BI__builtin_msa_bclri_h: 1598 case Mips::BI__builtin_msa_bnegi_h: 1599 case Mips::BI__builtin_msa_bseti_h: 1600 case Mips::BI__builtin_msa_sat_s_h: 1601 case Mips::BI__builtin_msa_sat_u_h: 1602 case Mips::BI__builtin_msa_slli_h: 1603 case Mips::BI__builtin_msa_srai_h: 1604 case Mips::BI__builtin_msa_srari_h: 1605 case Mips::BI__builtin_msa_srli_h: 1606 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1607 case Mips::BI__builtin_msa_binsli_h: 1608 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 1609 // These intrinsics take an unsigned 5 bit immedate. 1610 // The first block of intrinsics actually have an unsigned 5 bit field, 1611 // not a df/n field. 1612 case Mips::BI__builtin_msa_clei_u_b: 1613 case Mips::BI__builtin_msa_clei_u_h: 1614 case Mips::BI__builtin_msa_clei_u_w: 1615 case Mips::BI__builtin_msa_clei_u_d: 1616 case Mips::BI__builtin_msa_clti_u_b: 1617 case Mips::BI__builtin_msa_clti_u_h: 1618 case Mips::BI__builtin_msa_clti_u_w: 1619 case Mips::BI__builtin_msa_clti_u_d: 1620 case Mips::BI__builtin_msa_maxi_u_b: 1621 case Mips::BI__builtin_msa_maxi_u_h: 1622 case Mips::BI__builtin_msa_maxi_u_w: 1623 case Mips::BI__builtin_msa_maxi_u_d: 1624 case Mips::BI__builtin_msa_mini_u_b: 1625 case Mips::BI__builtin_msa_mini_u_h: 1626 case Mips::BI__builtin_msa_mini_u_w: 1627 case Mips::BI__builtin_msa_mini_u_d: 1628 case Mips::BI__builtin_msa_addvi_b: 1629 case Mips::BI__builtin_msa_addvi_h: 1630 case Mips::BI__builtin_msa_addvi_w: 1631 case Mips::BI__builtin_msa_addvi_d: 1632 case Mips::BI__builtin_msa_bclri_w: 1633 case Mips::BI__builtin_msa_bnegi_w: 1634 case Mips::BI__builtin_msa_bseti_w: 1635 case Mips::BI__builtin_msa_sat_s_w: 1636 case Mips::BI__builtin_msa_sat_u_w: 1637 case Mips::BI__builtin_msa_slli_w: 1638 case Mips::BI__builtin_msa_srai_w: 1639 case Mips::BI__builtin_msa_srari_w: 1640 case Mips::BI__builtin_msa_srli_w: 1641 case Mips::BI__builtin_msa_srlri_w: 1642 case Mips::BI__builtin_msa_subvi_b: 1643 case Mips::BI__builtin_msa_subvi_h: 1644 case Mips::BI__builtin_msa_subvi_w: 1645 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 1646 case Mips::BI__builtin_msa_binsli_w: 1647 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 1648 // These intrinsics take an unsigned 6 bit immediate. 1649 case Mips::BI__builtin_msa_bclri_d: 1650 case Mips::BI__builtin_msa_bnegi_d: 1651 case Mips::BI__builtin_msa_bseti_d: 1652 case Mips::BI__builtin_msa_sat_s_d: 1653 case Mips::BI__builtin_msa_sat_u_d: 1654 case Mips::BI__builtin_msa_slli_d: 1655 case Mips::BI__builtin_msa_srai_d: 1656 case Mips::BI__builtin_msa_srari_d: 1657 case Mips::BI__builtin_msa_srli_d: 1658 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 1659 case Mips::BI__builtin_msa_binsli_d: 1660 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 1661 // These intrinsics take a signed 5 bit immediate. 1662 case Mips::BI__builtin_msa_ceqi_b: 1663 case Mips::BI__builtin_msa_ceqi_h: 1664 case Mips::BI__builtin_msa_ceqi_w: 1665 case Mips::BI__builtin_msa_ceqi_d: 1666 case Mips::BI__builtin_msa_clti_s_b: 1667 case Mips::BI__builtin_msa_clti_s_h: 1668 case Mips::BI__builtin_msa_clti_s_w: 1669 case Mips::BI__builtin_msa_clti_s_d: 1670 case Mips::BI__builtin_msa_clei_s_b: 1671 case Mips::BI__builtin_msa_clei_s_h: 1672 case Mips::BI__builtin_msa_clei_s_w: 1673 case Mips::BI__builtin_msa_clei_s_d: 1674 case Mips::BI__builtin_msa_maxi_s_b: 1675 case Mips::BI__builtin_msa_maxi_s_h: 1676 case Mips::BI__builtin_msa_maxi_s_w: 1677 case Mips::BI__builtin_msa_maxi_s_d: 1678 case Mips::BI__builtin_msa_mini_s_b: 1679 case Mips::BI__builtin_msa_mini_s_h: 1680 case Mips::BI__builtin_msa_mini_s_w: 1681 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 1682 // These intrinsics take an unsigned 8 bit immediate. 1683 case Mips::BI__builtin_msa_andi_b: 1684 case Mips::BI__builtin_msa_nori_b: 1685 case Mips::BI__builtin_msa_ori_b: 1686 case Mips::BI__builtin_msa_shf_b: 1687 case Mips::BI__builtin_msa_shf_h: 1688 case Mips::BI__builtin_msa_shf_w: 1689 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 1690 case Mips::BI__builtin_msa_bseli_b: 1691 case Mips::BI__builtin_msa_bmnzi_b: 1692 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 1693 // df/n format 1694 // These intrinsics take an unsigned 4 bit immediate. 1695 case Mips::BI__builtin_msa_copy_s_b: 1696 case Mips::BI__builtin_msa_copy_u_b: 1697 case Mips::BI__builtin_msa_insve_b: 1698 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 1699 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 1700 // These intrinsics take an unsigned 3 bit immediate. 1701 case Mips::BI__builtin_msa_copy_s_h: 1702 case Mips::BI__builtin_msa_copy_u_h: 1703 case Mips::BI__builtin_msa_insve_h: 1704 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 1705 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 1706 // These intrinsics take an unsigned 2 bit immediate. 1707 case Mips::BI__builtin_msa_copy_s_w: 1708 case Mips::BI__builtin_msa_copy_u_w: 1709 case Mips::BI__builtin_msa_insve_w: 1710 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 1711 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 1712 // These intrinsics take an unsigned 1 bit immediate. 1713 case Mips::BI__builtin_msa_copy_s_d: 1714 case Mips::BI__builtin_msa_copy_u_d: 1715 case Mips::BI__builtin_msa_insve_d: 1716 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 1717 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 1718 // Memory offsets and immediate loads. 1719 // These intrinsics take a signed 10 bit immediate. 1720 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 1721 case Mips::BI__builtin_msa_ldi_h: 1722 case Mips::BI__builtin_msa_ldi_w: 1723 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 1724 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 1725 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 1726 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 1727 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 1728 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 1729 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 1730 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 1731 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 1732 } 1733 1734 if (!m) 1735 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1736 1737 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 1738 SemaBuiltinConstantArgMultiple(TheCall, i, m); 1739 } 1740 1741 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1742 unsigned i = 0, l = 0, u = 0; 1743 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 1744 BuiltinID == PPC::BI__builtin_divdeu || 1745 BuiltinID == PPC::BI__builtin_bpermd; 1746 bool IsTarget64Bit = Context.getTargetInfo() 1747 .getTypeWidth(Context 1748 .getTargetInfo() 1749 .getIntPtrType()) == 64; 1750 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 1751 BuiltinID == PPC::BI__builtin_divweu || 1752 BuiltinID == PPC::BI__builtin_divde || 1753 BuiltinID == PPC::BI__builtin_divdeu; 1754 1755 if (Is64BitBltin && !IsTarget64Bit) 1756 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 1757 << TheCall->getSourceRange(); 1758 1759 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 1760 (BuiltinID == PPC::BI__builtin_bpermd && 1761 !Context.getTargetInfo().hasFeature("bpermd"))) 1762 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 1763 << TheCall->getSourceRange(); 1764 1765 switch (BuiltinID) { 1766 default: return false; 1767 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 1768 case PPC::BI__builtin_altivec_crypto_vshasigmad: 1769 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1770 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1771 case PPC::BI__builtin_tbegin: 1772 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 1773 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 1774 case PPC::BI__builtin_tabortwc: 1775 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 1776 case PPC::BI__builtin_tabortwci: 1777 case PPC::BI__builtin_tabortdci: 1778 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 1779 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 1780 case PPC::BI__builtin_vsx_xxpermdi: 1781 case PPC::BI__builtin_vsx_xxsldwi: 1782 return SemaBuiltinVSX(TheCall); 1783 } 1784 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1785 } 1786 1787 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 1788 CallExpr *TheCall) { 1789 if (BuiltinID == SystemZ::BI__builtin_tabort) { 1790 Expr *Arg = TheCall->getArg(0); 1791 llvm::APSInt AbortCode(32); 1792 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 1793 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 1794 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 1795 << Arg->getSourceRange(); 1796 } 1797 1798 // For intrinsics which take an immediate value as part of the instruction, 1799 // range check them here. 1800 unsigned i = 0, l = 0, u = 0; 1801 switch (BuiltinID) { 1802 default: return false; 1803 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 1804 case SystemZ::BI__builtin_s390_verimb: 1805 case SystemZ::BI__builtin_s390_verimh: 1806 case SystemZ::BI__builtin_s390_verimf: 1807 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 1808 case SystemZ::BI__builtin_s390_vfaeb: 1809 case SystemZ::BI__builtin_s390_vfaeh: 1810 case SystemZ::BI__builtin_s390_vfaef: 1811 case SystemZ::BI__builtin_s390_vfaebs: 1812 case SystemZ::BI__builtin_s390_vfaehs: 1813 case SystemZ::BI__builtin_s390_vfaefs: 1814 case SystemZ::BI__builtin_s390_vfaezb: 1815 case SystemZ::BI__builtin_s390_vfaezh: 1816 case SystemZ::BI__builtin_s390_vfaezf: 1817 case SystemZ::BI__builtin_s390_vfaezbs: 1818 case SystemZ::BI__builtin_s390_vfaezhs: 1819 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 1820 case SystemZ::BI__builtin_s390_vfisb: 1821 case SystemZ::BI__builtin_s390_vfidb: 1822 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 1823 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1824 case SystemZ::BI__builtin_s390_vftcisb: 1825 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 1826 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 1827 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 1828 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 1829 case SystemZ::BI__builtin_s390_vstrcb: 1830 case SystemZ::BI__builtin_s390_vstrch: 1831 case SystemZ::BI__builtin_s390_vstrcf: 1832 case SystemZ::BI__builtin_s390_vstrczb: 1833 case SystemZ::BI__builtin_s390_vstrczh: 1834 case SystemZ::BI__builtin_s390_vstrczf: 1835 case SystemZ::BI__builtin_s390_vstrcbs: 1836 case SystemZ::BI__builtin_s390_vstrchs: 1837 case SystemZ::BI__builtin_s390_vstrcfs: 1838 case SystemZ::BI__builtin_s390_vstrczbs: 1839 case SystemZ::BI__builtin_s390_vstrczhs: 1840 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 1841 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 1842 case SystemZ::BI__builtin_s390_vfminsb: 1843 case SystemZ::BI__builtin_s390_vfmaxsb: 1844 case SystemZ::BI__builtin_s390_vfmindb: 1845 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 1846 } 1847 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1848 } 1849 1850 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 1851 /// This checks that the target supports __builtin_cpu_supports and 1852 /// that the string argument is constant and valid. 1853 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 1854 Expr *Arg = TheCall->getArg(0); 1855 1856 // Check if the argument is a string literal. 1857 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1858 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1859 << Arg->getSourceRange(); 1860 1861 // Check the contents of the string. 1862 StringRef Feature = 1863 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1864 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 1865 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 1866 << Arg->getSourceRange(); 1867 return false; 1868 } 1869 1870 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 1871 /// This checks that the target supports __builtin_cpu_is and 1872 /// that the string argument is constant and valid. 1873 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 1874 Expr *Arg = TheCall->getArg(0); 1875 1876 // Check if the argument is a string literal. 1877 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1878 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1879 << Arg->getSourceRange(); 1880 1881 // Check the contents of the string. 1882 StringRef Feature = 1883 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1884 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 1885 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is) 1886 << Arg->getSourceRange(); 1887 return false; 1888 } 1889 1890 // Check if the rounding mode is legal. 1891 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 1892 // Indicates if this instruction has rounding control or just SAE. 1893 bool HasRC = false; 1894 1895 unsigned ArgNum = 0; 1896 switch (BuiltinID) { 1897 default: 1898 return false; 1899 case X86::BI__builtin_ia32_vcvttsd2si32: 1900 case X86::BI__builtin_ia32_vcvttsd2si64: 1901 case X86::BI__builtin_ia32_vcvttsd2usi32: 1902 case X86::BI__builtin_ia32_vcvttsd2usi64: 1903 case X86::BI__builtin_ia32_vcvttss2si32: 1904 case X86::BI__builtin_ia32_vcvttss2si64: 1905 case X86::BI__builtin_ia32_vcvttss2usi32: 1906 case X86::BI__builtin_ia32_vcvttss2usi64: 1907 ArgNum = 1; 1908 break; 1909 case X86::BI__builtin_ia32_cvtps2pd512_mask: 1910 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 1911 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 1912 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 1913 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 1914 case X86::BI__builtin_ia32_cvttps2dq512_mask: 1915 case X86::BI__builtin_ia32_cvttps2qq512_mask: 1916 case X86::BI__builtin_ia32_cvttps2udq512_mask: 1917 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 1918 case X86::BI__builtin_ia32_exp2pd_mask: 1919 case X86::BI__builtin_ia32_exp2ps_mask: 1920 case X86::BI__builtin_ia32_getexppd512_mask: 1921 case X86::BI__builtin_ia32_getexpps512_mask: 1922 case X86::BI__builtin_ia32_rcp28pd_mask: 1923 case X86::BI__builtin_ia32_rcp28ps_mask: 1924 case X86::BI__builtin_ia32_rsqrt28pd_mask: 1925 case X86::BI__builtin_ia32_rsqrt28ps_mask: 1926 case X86::BI__builtin_ia32_vcomisd: 1927 case X86::BI__builtin_ia32_vcomiss: 1928 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 1929 ArgNum = 3; 1930 break; 1931 case X86::BI__builtin_ia32_cmppd512_mask: 1932 case X86::BI__builtin_ia32_cmpps512_mask: 1933 case X86::BI__builtin_ia32_cmpsd_mask: 1934 case X86::BI__builtin_ia32_cmpss_mask: 1935 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 1936 case X86::BI__builtin_ia32_getexpsd128_round_mask: 1937 case X86::BI__builtin_ia32_getexpss128_round_mask: 1938 case X86::BI__builtin_ia32_maxpd512_mask: 1939 case X86::BI__builtin_ia32_maxps512_mask: 1940 case X86::BI__builtin_ia32_maxsd_round_mask: 1941 case X86::BI__builtin_ia32_maxss_round_mask: 1942 case X86::BI__builtin_ia32_minpd512_mask: 1943 case X86::BI__builtin_ia32_minps512_mask: 1944 case X86::BI__builtin_ia32_minsd_round_mask: 1945 case X86::BI__builtin_ia32_minss_round_mask: 1946 case X86::BI__builtin_ia32_rcp28sd_round_mask: 1947 case X86::BI__builtin_ia32_rcp28ss_round_mask: 1948 case X86::BI__builtin_ia32_reducepd512_mask: 1949 case X86::BI__builtin_ia32_reduceps512_mask: 1950 case X86::BI__builtin_ia32_rndscalepd_mask: 1951 case X86::BI__builtin_ia32_rndscaleps_mask: 1952 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 1953 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 1954 ArgNum = 4; 1955 break; 1956 case X86::BI__builtin_ia32_fixupimmpd512_mask: 1957 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 1958 case X86::BI__builtin_ia32_fixupimmps512_mask: 1959 case X86::BI__builtin_ia32_fixupimmps512_maskz: 1960 case X86::BI__builtin_ia32_fixupimmsd_mask: 1961 case X86::BI__builtin_ia32_fixupimmsd_maskz: 1962 case X86::BI__builtin_ia32_fixupimmss_mask: 1963 case X86::BI__builtin_ia32_fixupimmss_maskz: 1964 case X86::BI__builtin_ia32_rangepd512_mask: 1965 case X86::BI__builtin_ia32_rangeps512_mask: 1966 case X86::BI__builtin_ia32_rangesd128_round_mask: 1967 case X86::BI__builtin_ia32_rangess128_round_mask: 1968 case X86::BI__builtin_ia32_reducesd_mask: 1969 case X86::BI__builtin_ia32_reducess_mask: 1970 case X86::BI__builtin_ia32_rndscalesd_round_mask: 1971 case X86::BI__builtin_ia32_rndscaless_round_mask: 1972 ArgNum = 5; 1973 break; 1974 case X86::BI__builtin_ia32_vcvtsd2si64: 1975 case X86::BI__builtin_ia32_vcvtsd2si32: 1976 case X86::BI__builtin_ia32_vcvtsd2usi32: 1977 case X86::BI__builtin_ia32_vcvtsd2usi64: 1978 case X86::BI__builtin_ia32_vcvtss2si32: 1979 case X86::BI__builtin_ia32_vcvtss2si64: 1980 case X86::BI__builtin_ia32_vcvtss2usi32: 1981 case X86::BI__builtin_ia32_vcvtss2usi64: 1982 ArgNum = 1; 1983 HasRC = true; 1984 break; 1985 case X86::BI__builtin_ia32_cvtsi2sd64: 1986 case X86::BI__builtin_ia32_cvtsi2ss32: 1987 case X86::BI__builtin_ia32_cvtsi2ss64: 1988 case X86::BI__builtin_ia32_cvtusi2sd64: 1989 case X86::BI__builtin_ia32_cvtusi2ss32: 1990 case X86::BI__builtin_ia32_cvtusi2ss64: 1991 ArgNum = 2; 1992 HasRC = true; 1993 break; 1994 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 1995 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 1996 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 1997 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 1998 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 1999 case X86::BI__builtin_ia32_cvtps2qq512_mask: 2000 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 2001 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 2002 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 2003 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 2004 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 2005 case X86::BI__builtin_ia32_sqrtpd512_mask: 2006 case X86::BI__builtin_ia32_sqrtps512_mask: 2007 ArgNum = 3; 2008 HasRC = true; 2009 break; 2010 case X86::BI__builtin_ia32_addpd512_mask: 2011 case X86::BI__builtin_ia32_addps512_mask: 2012 case X86::BI__builtin_ia32_divpd512_mask: 2013 case X86::BI__builtin_ia32_divps512_mask: 2014 case X86::BI__builtin_ia32_mulpd512_mask: 2015 case X86::BI__builtin_ia32_mulps512_mask: 2016 case X86::BI__builtin_ia32_subpd512_mask: 2017 case X86::BI__builtin_ia32_subps512_mask: 2018 case X86::BI__builtin_ia32_addss_round_mask: 2019 case X86::BI__builtin_ia32_addsd_round_mask: 2020 case X86::BI__builtin_ia32_divss_round_mask: 2021 case X86::BI__builtin_ia32_divsd_round_mask: 2022 case X86::BI__builtin_ia32_mulss_round_mask: 2023 case X86::BI__builtin_ia32_mulsd_round_mask: 2024 case X86::BI__builtin_ia32_subss_round_mask: 2025 case X86::BI__builtin_ia32_subsd_round_mask: 2026 case X86::BI__builtin_ia32_scalefpd512_mask: 2027 case X86::BI__builtin_ia32_scalefps512_mask: 2028 case X86::BI__builtin_ia32_scalefsd_round_mask: 2029 case X86::BI__builtin_ia32_scalefss_round_mask: 2030 case X86::BI__builtin_ia32_getmantpd512_mask: 2031 case X86::BI__builtin_ia32_getmantps512_mask: 2032 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 2033 case X86::BI__builtin_ia32_sqrtsd_round_mask: 2034 case X86::BI__builtin_ia32_sqrtss_round_mask: 2035 case X86::BI__builtin_ia32_vfmaddpd512_mask: 2036 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 2037 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 2038 case X86::BI__builtin_ia32_vfmaddps512_mask: 2039 case X86::BI__builtin_ia32_vfmaddps512_mask3: 2040 case X86::BI__builtin_ia32_vfmaddps512_maskz: 2041 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 2042 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 2043 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 2044 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 2045 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 2046 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 2047 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 2048 case X86::BI__builtin_ia32_vfmsubps512_mask3: 2049 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 2050 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 2051 case X86::BI__builtin_ia32_vfnmaddpd512_mask: 2052 case X86::BI__builtin_ia32_vfnmaddps512_mask: 2053 case X86::BI__builtin_ia32_vfnmsubpd512_mask: 2054 case X86::BI__builtin_ia32_vfnmsubpd512_mask3: 2055 case X86::BI__builtin_ia32_vfnmsubps512_mask: 2056 case X86::BI__builtin_ia32_vfnmsubps512_mask3: 2057 case X86::BI__builtin_ia32_vfmaddsd3_mask: 2058 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 2059 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 2060 case X86::BI__builtin_ia32_vfmaddss3_mask: 2061 case X86::BI__builtin_ia32_vfmaddss3_maskz: 2062 case X86::BI__builtin_ia32_vfmaddss3_mask3: 2063 ArgNum = 4; 2064 HasRC = true; 2065 break; 2066 case X86::BI__builtin_ia32_getmantsd_round_mask: 2067 case X86::BI__builtin_ia32_getmantss_round_mask: 2068 ArgNum = 5; 2069 HasRC = true; 2070 break; 2071 } 2072 2073 llvm::APSInt Result; 2074 2075 // We can't check the value of a dependent argument. 2076 Expr *Arg = TheCall->getArg(ArgNum); 2077 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2078 return false; 2079 2080 // Check constant-ness first. 2081 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2082 return true; 2083 2084 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 2085 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 2086 // combined with ROUND_NO_EXC. 2087 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 2088 Result == 8/*ROUND_NO_EXC*/ || 2089 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 2090 return false; 2091 2092 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 2093 << Arg->getSourceRange(); 2094 } 2095 2096 // Check if the gather/scatter scale is legal. 2097 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 2098 CallExpr *TheCall) { 2099 unsigned ArgNum = 0; 2100 switch (BuiltinID) { 2101 default: 2102 return false; 2103 case X86::BI__builtin_ia32_gatherpfdpd: 2104 case X86::BI__builtin_ia32_gatherpfdps: 2105 case X86::BI__builtin_ia32_gatherpfqpd: 2106 case X86::BI__builtin_ia32_gatherpfqps: 2107 case X86::BI__builtin_ia32_scatterpfdpd: 2108 case X86::BI__builtin_ia32_scatterpfdps: 2109 case X86::BI__builtin_ia32_scatterpfqpd: 2110 case X86::BI__builtin_ia32_scatterpfqps: 2111 ArgNum = 3; 2112 break; 2113 case X86::BI__builtin_ia32_gatherd_pd: 2114 case X86::BI__builtin_ia32_gatherd_pd256: 2115 case X86::BI__builtin_ia32_gatherq_pd: 2116 case X86::BI__builtin_ia32_gatherq_pd256: 2117 case X86::BI__builtin_ia32_gatherd_ps: 2118 case X86::BI__builtin_ia32_gatherd_ps256: 2119 case X86::BI__builtin_ia32_gatherq_ps: 2120 case X86::BI__builtin_ia32_gatherq_ps256: 2121 case X86::BI__builtin_ia32_gatherd_q: 2122 case X86::BI__builtin_ia32_gatherd_q256: 2123 case X86::BI__builtin_ia32_gatherq_q: 2124 case X86::BI__builtin_ia32_gatherq_q256: 2125 case X86::BI__builtin_ia32_gatherd_d: 2126 case X86::BI__builtin_ia32_gatherd_d256: 2127 case X86::BI__builtin_ia32_gatherq_d: 2128 case X86::BI__builtin_ia32_gatherq_d256: 2129 case X86::BI__builtin_ia32_gather3div2df: 2130 case X86::BI__builtin_ia32_gather3div2di: 2131 case X86::BI__builtin_ia32_gather3div4df: 2132 case X86::BI__builtin_ia32_gather3div4di: 2133 case X86::BI__builtin_ia32_gather3div4sf: 2134 case X86::BI__builtin_ia32_gather3div4si: 2135 case X86::BI__builtin_ia32_gather3div8sf: 2136 case X86::BI__builtin_ia32_gather3div8si: 2137 case X86::BI__builtin_ia32_gather3siv2df: 2138 case X86::BI__builtin_ia32_gather3siv2di: 2139 case X86::BI__builtin_ia32_gather3siv4df: 2140 case X86::BI__builtin_ia32_gather3siv4di: 2141 case X86::BI__builtin_ia32_gather3siv4sf: 2142 case X86::BI__builtin_ia32_gather3siv4si: 2143 case X86::BI__builtin_ia32_gather3siv8sf: 2144 case X86::BI__builtin_ia32_gather3siv8si: 2145 case X86::BI__builtin_ia32_gathersiv8df: 2146 case X86::BI__builtin_ia32_gathersiv16sf: 2147 case X86::BI__builtin_ia32_gatherdiv8df: 2148 case X86::BI__builtin_ia32_gatherdiv16sf: 2149 case X86::BI__builtin_ia32_gathersiv8di: 2150 case X86::BI__builtin_ia32_gathersiv16si: 2151 case X86::BI__builtin_ia32_gatherdiv8di: 2152 case X86::BI__builtin_ia32_gatherdiv16si: 2153 case X86::BI__builtin_ia32_scatterdiv2df: 2154 case X86::BI__builtin_ia32_scatterdiv2di: 2155 case X86::BI__builtin_ia32_scatterdiv4df: 2156 case X86::BI__builtin_ia32_scatterdiv4di: 2157 case X86::BI__builtin_ia32_scatterdiv4sf: 2158 case X86::BI__builtin_ia32_scatterdiv4si: 2159 case X86::BI__builtin_ia32_scatterdiv8sf: 2160 case X86::BI__builtin_ia32_scatterdiv8si: 2161 case X86::BI__builtin_ia32_scattersiv2df: 2162 case X86::BI__builtin_ia32_scattersiv2di: 2163 case X86::BI__builtin_ia32_scattersiv4df: 2164 case X86::BI__builtin_ia32_scattersiv4di: 2165 case X86::BI__builtin_ia32_scattersiv4sf: 2166 case X86::BI__builtin_ia32_scattersiv4si: 2167 case X86::BI__builtin_ia32_scattersiv8sf: 2168 case X86::BI__builtin_ia32_scattersiv8si: 2169 case X86::BI__builtin_ia32_scattersiv8df: 2170 case X86::BI__builtin_ia32_scattersiv16sf: 2171 case X86::BI__builtin_ia32_scatterdiv8df: 2172 case X86::BI__builtin_ia32_scatterdiv16sf: 2173 case X86::BI__builtin_ia32_scattersiv8di: 2174 case X86::BI__builtin_ia32_scattersiv16si: 2175 case X86::BI__builtin_ia32_scatterdiv8di: 2176 case X86::BI__builtin_ia32_scatterdiv16si: 2177 ArgNum = 4; 2178 break; 2179 } 2180 2181 llvm::APSInt Result; 2182 2183 // We can't check the value of a dependent argument. 2184 Expr *Arg = TheCall->getArg(ArgNum); 2185 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2186 return false; 2187 2188 // Check constant-ness first. 2189 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2190 return true; 2191 2192 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 2193 return false; 2194 2195 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale) 2196 << Arg->getSourceRange(); 2197 } 2198 2199 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2200 if (BuiltinID == X86::BI__builtin_cpu_supports) 2201 return SemaBuiltinCpuSupports(*this, TheCall); 2202 2203 if (BuiltinID == X86::BI__builtin_cpu_is) 2204 return SemaBuiltinCpuIs(*this, TheCall); 2205 2206 // If the intrinsic has rounding or SAE make sure its valid. 2207 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 2208 return true; 2209 2210 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 2211 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 2212 return true; 2213 2214 // For intrinsics which take an immediate value as part of the instruction, 2215 // range check them here. 2216 int i = 0, l = 0, u = 0; 2217 switch (BuiltinID) { 2218 default: 2219 return false; 2220 case X86::BI_mm_prefetch: 2221 i = 1; l = 0; u = 3; 2222 break; 2223 case X86::BI__builtin_ia32_sha1rnds4: 2224 case X86::BI__builtin_ia32_shuf_f32x4_256_mask: 2225 case X86::BI__builtin_ia32_shuf_f64x2_256_mask: 2226 case X86::BI__builtin_ia32_shuf_i32x4_256_mask: 2227 case X86::BI__builtin_ia32_shuf_i64x2_256_mask: 2228 i = 2; l = 0; u = 3; 2229 break; 2230 case X86::BI__builtin_ia32_vpermil2pd: 2231 case X86::BI__builtin_ia32_vpermil2pd256: 2232 case X86::BI__builtin_ia32_vpermil2ps: 2233 case X86::BI__builtin_ia32_vpermil2ps256: 2234 i = 3; l = 0; u = 3; 2235 break; 2236 case X86::BI__builtin_ia32_cmpb128_mask: 2237 case X86::BI__builtin_ia32_cmpw128_mask: 2238 case X86::BI__builtin_ia32_cmpd128_mask: 2239 case X86::BI__builtin_ia32_cmpq128_mask: 2240 case X86::BI__builtin_ia32_cmpb256_mask: 2241 case X86::BI__builtin_ia32_cmpw256_mask: 2242 case X86::BI__builtin_ia32_cmpd256_mask: 2243 case X86::BI__builtin_ia32_cmpq256_mask: 2244 case X86::BI__builtin_ia32_cmpb512_mask: 2245 case X86::BI__builtin_ia32_cmpw512_mask: 2246 case X86::BI__builtin_ia32_cmpd512_mask: 2247 case X86::BI__builtin_ia32_cmpq512_mask: 2248 case X86::BI__builtin_ia32_ucmpb128_mask: 2249 case X86::BI__builtin_ia32_ucmpw128_mask: 2250 case X86::BI__builtin_ia32_ucmpd128_mask: 2251 case X86::BI__builtin_ia32_ucmpq128_mask: 2252 case X86::BI__builtin_ia32_ucmpb256_mask: 2253 case X86::BI__builtin_ia32_ucmpw256_mask: 2254 case X86::BI__builtin_ia32_ucmpd256_mask: 2255 case X86::BI__builtin_ia32_ucmpq256_mask: 2256 case X86::BI__builtin_ia32_ucmpb512_mask: 2257 case X86::BI__builtin_ia32_ucmpw512_mask: 2258 case X86::BI__builtin_ia32_ucmpd512_mask: 2259 case X86::BI__builtin_ia32_ucmpq512_mask: 2260 case X86::BI__builtin_ia32_vpcomub: 2261 case X86::BI__builtin_ia32_vpcomuw: 2262 case X86::BI__builtin_ia32_vpcomud: 2263 case X86::BI__builtin_ia32_vpcomuq: 2264 case X86::BI__builtin_ia32_vpcomb: 2265 case X86::BI__builtin_ia32_vpcomw: 2266 case X86::BI__builtin_ia32_vpcomd: 2267 case X86::BI__builtin_ia32_vpcomq: 2268 i = 2; l = 0; u = 7; 2269 break; 2270 case X86::BI__builtin_ia32_roundps: 2271 case X86::BI__builtin_ia32_roundpd: 2272 case X86::BI__builtin_ia32_roundps256: 2273 case X86::BI__builtin_ia32_roundpd256: 2274 i = 1; l = 0; u = 15; 2275 break; 2276 case X86::BI__builtin_ia32_roundss: 2277 case X86::BI__builtin_ia32_roundsd: 2278 case X86::BI__builtin_ia32_rangepd128_mask: 2279 case X86::BI__builtin_ia32_rangepd256_mask: 2280 case X86::BI__builtin_ia32_rangepd512_mask: 2281 case X86::BI__builtin_ia32_rangeps128_mask: 2282 case X86::BI__builtin_ia32_rangeps256_mask: 2283 case X86::BI__builtin_ia32_rangeps512_mask: 2284 case X86::BI__builtin_ia32_getmantsd_round_mask: 2285 case X86::BI__builtin_ia32_getmantss_round_mask: 2286 i = 2; l = 0; u = 15; 2287 break; 2288 case X86::BI__builtin_ia32_cmpps: 2289 case X86::BI__builtin_ia32_cmpss: 2290 case X86::BI__builtin_ia32_cmppd: 2291 case X86::BI__builtin_ia32_cmpsd: 2292 case X86::BI__builtin_ia32_cmpps256: 2293 case X86::BI__builtin_ia32_cmppd256: 2294 case X86::BI__builtin_ia32_cmpps128_mask: 2295 case X86::BI__builtin_ia32_cmppd128_mask: 2296 case X86::BI__builtin_ia32_cmpps256_mask: 2297 case X86::BI__builtin_ia32_cmppd256_mask: 2298 case X86::BI__builtin_ia32_cmpps512_mask: 2299 case X86::BI__builtin_ia32_cmppd512_mask: 2300 case X86::BI__builtin_ia32_cmpsd_mask: 2301 case X86::BI__builtin_ia32_cmpss_mask: 2302 i = 2; l = 0; u = 31; 2303 break; 2304 case X86::BI__builtin_ia32_xabort: 2305 i = 0; l = -128; u = 255; 2306 break; 2307 case X86::BI__builtin_ia32_pshufw: 2308 case X86::BI__builtin_ia32_aeskeygenassist128: 2309 i = 1; l = -128; u = 255; 2310 break; 2311 case X86::BI__builtin_ia32_vcvtps2ph: 2312 case X86::BI__builtin_ia32_vcvtps2ph256: 2313 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2314 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2315 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2316 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2317 case X86::BI__builtin_ia32_rndscaleps_mask: 2318 case X86::BI__builtin_ia32_rndscalepd_mask: 2319 case X86::BI__builtin_ia32_reducepd128_mask: 2320 case X86::BI__builtin_ia32_reducepd256_mask: 2321 case X86::BI__builtin_ia32_reducepd512_mask: 2322 case X86::BI__builtin_ia32_reduceps128_mask: 2323 case X86::BI__builtin_ia32_reduceps256_mask: 2324 case X86::BI__builtin_ia32_reduceps512_mask: 2325 case X86::BI__builtin_ia32_prold512_mask: 2326 case X86::BI__builtin_ia32_prolq512_mask: 2327 case X86::BI__builtin_ia32_prold128_mask: 2328 case X86::BI__builtin_ia32_prold256_mask: 2329 case X86::BI__builtin_ia32_prolq128_mask: 2330 case X86::BI__builtin_ia32_prolq256_mask: 2331 case X86::BI__builtin_ia32_prord128_mask: 2332 case X86::BI__builtin_ia32_prord256_mask: 2333 case X86::BI__builtin_ia32_prorq128_mask: 2334 case X86::BI__builtin_ia32_prorq256_mask: 2335 case X86::BI__builtin_ia32_fpclasspd128_mask: 2336 case X86::BI__builtin_ia32_fpclasspd256_mask: 2337 case X86::BI__builtin_ia32_fpclassps128_mask: 2338 case X86::BI__builtin_ia32_fpclassps256_mask: 2339 case X86::BI__builtin_ia32_fpclassps512_mask: 2340 case X86::BI__builtin_ia32_fpclasspd512_mask: 2341 case X86::BI__builtin_ia32_fpclasssd_mask: 2342 case X86::BI__builtin_ia32_fpclassss_mask: 2343 i = 1; l = 0; u = 255; 2344 break; 2345 case X86::BI__builtin_ia32_palignr: 2346 case X86::BI__builtin_ia32_insertps128: 2347 case X86::BI__builtin_ia32_dpps: 2348 case X86::BI__builtin_ia32_dppd: 2349 case X86::BI__builtin_ia32_dpps256: 2350 case X86::BI__builtin_ia32_mpsadbw128: 2351 case X86::BI__builtin_ia32_mpsadbw256: 2352 case X86::BI__builtin_ia32_pcmpistrm128: 2353 case X86::BI__builtin_ia32_pcmpistri128: 2354 case X86::BI__builtin_ia32_pcmpistria128: 2355 case X86::BI__builtin_ia32_pcmpistric128: 2356 case X86::BI__builtin_ia32_pcmpistrio128: 2357 case X86::BI__builtin_ia32_pcmpistris128: 2358 case X86::BI__builtin_ia32_pcmpistriz128: 2359 case X86::BI__builtin_ia32_pclmulqdq128: 2360 case X86::BI__builtin_ia32_vperm2f128_pd256: 2361 case X86::BI__builtin_ia32_vperm2f128_ps256: 2362 case X86::BI__builtin_ia32_vperm2f128_si256: 2363 case X86::BI__builtin_ia32_permti256: 2364 i = 2; l = -128; u = 255; 2365 break; 2366 case X86::BI__builtin_ia32_palignr128: 2367 case X86::BI__builtin_ia32_palignr256: 2368 case X86::BI__builtin_ia32_palignr512_mask: 2369 case X86::BI__builtin_ia32_vcomisd: 2370 case X86::BI__builtin_ia32_vcomiss: 2371 case X86::BI__builtin_ia32_shuf_f32x4_mask: 2372 case X86::BI__builtin_ia32_shuf_f64x2_mask: 2373 case X86::BI__builtin_ia32_shuf_i32x4_mask: 2374 case X86::BI__builtin_ia32_shuf_i64x2_mask: 2375 case X86::BI__builtin_ia32_dbpsadbw128_mask: 2376 case X86::BI__builtin_ia32_dbpsadbw256_mask: 2377 case X86::BI__builtin_ia32_dbpsadbw512_mask: 2378 i = 2; l = 0; u = 255; 2379 break; 2380 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2381 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2382 case X86::BI__builtin_ia32_fixupimmps512_mask: 2383 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2384 case X86::BI__builtin_ia32_fixupimmsd_mask: 2385 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2386 case X86::BI__builtin_ia32_fixupimmss_mask: 2387 case X86::BI__builtin_ia32_fixupimmss_maskz: 2388 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2389 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2390 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2391 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2392 case X86::BI__builtin_ia32_fixupimmps128_mask: 2393 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2394 case X86::BI__builtin_ia32_fixupimmps256_mask: 2395 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2396 case X86::BI__builtin_ia32_pternlogd512_mask: 2397 case X86::BI__builtin_ia32_pternlogd512_maskz: 2398 case X86::BI__builtin_ia32_pternlogq512_mask: 2399 case X86::BI__builtin_ia32_pternlogq512_maskz: 2400 case X86::BI__builtin_ia32_pternlogd128_mask: 2401 case X86::BI__builtin_ia32_pternlogd128_maskz: 2402 case X86::BI__builtin_ia32_pternlogd256_mask: 2403 case X86::BI__builtin_ia32_pternlogd256_maskz: 2404 case X86::BI__builtin_ia32_pternlogq128_mask: 2405 case X86::BI__builtin_ia32_pternlogq128_maskz: 2406 case X86::BI__builtin_ia32_pternlogq256_mask: 2407 case X86::BI__builtin_ia32_pternlogq256_maskz: 2408 i = 3; l = 0; u = 255; 2409 break; 2410 case X86::BI__builtin_ia32_gatherpfdpd: 2411 case X86::BI__builtin_ia32_gatherpfdps: 2412 case X86::BI__builtin_ia32_gatherpfqpd: 2413 case X86::BI__builtin_ia32_gatherpfqps: 2414 case X86::BI__builtin_ia32_scatterpfdpd: 2415 case X86::BI__builtin_ia32_scatterpfdps: 2416 case X86::BI__builtin_ia32_scatterpfqpd: 2417 case X86::BI__builtin_ia32_scatterpfqps: 2418 i = 4; l = 2; u = 3; 2419 break; 2420 case X86::BI__builtin_ia32_pcmpestrm128: 2421 case X86::BI__builtin_ia32_pcmpestri128: 2422 case X86::BI__builtin_ia32_pcmpestria128: 2423 case X86::BI__builtin_ia32_pcmpestric128: 2424 case X86::BI__builtin_ia32_pcmpestrio128: 2425 case X86::BI__builtin_ia32_pcmpestris128: 2426 case X86::BI__builtin_ia32_pcmpestriz128: 2427 i = 4; l = -128; u = 255; 2428 break; 2429 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2430 case X86::BI__builtin_ia32_rndscaless_round_mask: 2431 i = 4; l = 0; u = 255; 2432 break; 2433 } 2434 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2435 } 2436 2437 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2438 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2439 /// Returns true when the format fits the function and the FormatStringInfo has 2440 /// been populated. 2441 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2442 FormatStringInfo *FSI) { 2443 FSI->HasVAListArg = Format->getFirstArg() == 0; 2444 FSI->FormatIdx = Format->getFormatIdx() - 1; 2445 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2446 2447 // The way the format attribute works in GCC, the implicit this argument 2448 // of member functions is counted. However, it doesn't appear in our own 2449 // lists, so decrement format_idx in that case. 2450 if (IsCXXMember) { 2451 if(FSI->FormatIdx == 0) 2452 return false; 2453 --FSI->FormatIdx; 2454 if (FSI->FirstDataArg != 0) 2455 --FSI->FirstDataArg; 2456 } 2457 return true; 2458 } 2459 2460 /// Checks if a the given expression evaluates to null. 2461 /// 2462 /// \brief Returns true if the value evaluates to null. 2463 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2464 // If the expression has non-null type, it doesn't evaluate to null. 2465 if (auto nullability 2466 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2467 if (*nullability == NullabilityKind::NonNull) 2468 return false; 2469 } 2470 2471 // As a special case, transparent unions initialized with zero are 2472 // considered null for the purposes of the nonnull attribute. 2473 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2474 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2475 if (const CompoundLiteralExpr *CLE = 2476 dyn_cast<CompoundLiteralExpr>(Expr)) 2477 if (const InitListExpr *ILE = 2478 dyn_cast<InitListExpr>(CLE->getInitializer())) 2479 Expr = ILE->getInit(0); 2480 } 2481 2482 bool Result; 2483 return (!Expr->isValueDependent() && 2484 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2485 !Result); 2486 } 2487 2488 static void CheckNonNullArgument(Sema &S, 2489 const Expr *ArgExpr, 2490 SourceLocation CallSiteLoc) { 2491 if (CheckNonNullExpr(S, ArgExpr)) 2492 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2493 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2494 } 2495 2496 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2497 FormatStringInfo FSI; 2498 if ((GetFormatStringType(Format) == FST_NSString) && 2499 getFormatStringInfo(Format, false, &FSI)) { 2500 Idx = FSI.FormatIdx; 2501 return true; 2502 } 2503 return false; 2504 } 2505 /// \brief Diagnose use of %s directive in an NSString which is being passed 2506 /// as formatting string to formatting method. 2507 static void 2508 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 2509 const NamedDecl *FDecl, 2510 Expr **Args, 2511 unsigned NumArgs) { 2512 unsigned Idx = 0; 2513 bool Format = false; 2514 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 2515 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 2516 Idx = 2; 2517 Format = true; 2518 } 2519 else 2520 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2521 if (S.GetFormatNSStringIdx(I, Idx)) { 2522 Format = true; 2523 break; 2524 } 2525 } 2526 if (!Format || NumArgs <= Idx) 2527 return; 2528 const Expr *FormatExpr = Args[Idx]; 2529 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2530 FormatExpr = CSCE->getSubExpr(); 2531 const StringLiteral *FormatString; 2532 if (const ObjCStringLiteral *OSL = 2533 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2534 FormatString = OSL->getString(); 2535 else 2536 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2537 if (!FormatString) 2538 return; 2539 if (S.FormatStringHasSArg(FormatString)) { 2540 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2541 << "%s" << 1 << 1; 2542 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2543 << FDecl->getDeclName(); 2544 } 2545 } 2546 2547 /// Determine whether the given type has a non-null nullability annotation. 2548 static bool isNonNullType(ASTContext &ctx, QualType type) { 2549 if (auto nullability = type->getNullability(ctx)) 2550 return *nullability == NullabilityKind::NonNull; 2551 2552 return false; 2553 } 2554 2555 static void CheckNonNullArguments(Sema &S, 2556 const NamedDecl *FDecl, 2557 const FunctionProtoType *Proto, 2558 ArrayRef<const Expr *> Args, 2559 SourceLocation CallSiteLoc) { 2560 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2561 2562 // Check the attributes attached to the method/function itself. 2563 llvm::SmallBitVector NonNullArgs; 2564 if (FDecl) { 2565 // Handle the nonnull attribute on the function/method declaration itself. 2566 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2567 if (!NonNull->args_size()) { 2568 // Easy case: all pointer arguments are nonnull. 2569 for (const auto *Arg : Args) 2570 if (S.isValidPointerAttrType(Arg->getType())) 2571 CheckNonNullArgument(S, Arg, CallSiteLoc); 2572 return; 2573 } 2574 2575 for (unsigned Val : NonNull->args()) { 2576 if (Val >= Args.size()) 2577 continue; 2578 if (NonNullArgs.empty()) 2579 NonNullArgs.resize(Args.size()); 2580 NonNullArgs.set(Val); 2581 } 2582 } 2583 } 2584 2585 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2586 // Handle the nonnull attribute on the parameters of the 2587 // function/method. 2588 ArrayRef<ParmVarDecl*> parms; 2589 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2590 parms = FD->parameters(); 2591 else 2592 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2593 2594 unsigned ParamIndex = 0; 2595 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2596 I != E; ++I, ++ParamIndex) { 2597 const ParmVarDecl *PVD = *I; 2598 if (PVD->hasAttr<NonNullAttr>() || 2599 isNonNullType(S.Context, PVD->getType())) { 2600 if (NonNullArgs.empty()) 2601 NonNullArgs.resize(Args.size()); 2602 2603 NonNullArgs.set(ParamIndex); 2604 } 2605 } 2606 } else { 2607 // If we have a non-function, non-method declaration but no 2608 // function prototype, try to dig out the function prototype. 2609 if (!Proto) { 2610 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2611 QualType type = VD->getType().getNonReferenceType(); 2612 if (auto pointerType = type->getAs<PointerType>()) 2613 type = pointerType->getPointeeType(); 2614 else if (auto blockType = type->getAs<BlockPointerType>()) 2615 type = blockType->getPointeeType(); 2616 // FIXME: data member pointers? 2617 2618 // Dig out the function prototype, if there is one. 2619 Proto = type->getAs<FunctionProtoType>(); 2620 } 2621 } 2622 2623 // Fill in non-null argument information from the nullability 2624 // information on the parameter types (if we have them). 2625 if (Proto) { 2626 unsigned Index = 0; 2627 for (auto paramType : Proto->getParamTypes()) { 2628 if (isNonNullType(S.Context, paramType)) { 2629 if (NonNullArgs.empty()) 2630 NonNullArgs.resize(Args.size()); 2631 2632 NonNullArgs.set(Index); 2633 } 2634 2635 ++Index; 2636 } 2637 } 2638 } 2639 2640 // Check for non-null arguments. 2641 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2642 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2643 if (NonNullArgs[ArgIndex]) 2644 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2645 } 2646 } 2647 2648 /// Handles the checks for format strings, non-POD arguments to vararg 2649 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 2650 /// attributes. 2651 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2652 const Expr *ThisArg, ArrayRef<const Expr *> Args, 2653 bool IsMemberFunction, SourceLocation Loc, 2654 SourceRange Range, VariadicCallType CallType) { 2655 // FIXME: We should check as much as we can in the template definition. 2656 if (CurContext->isDependentContext()) 2657 return; 2658 2659 // Printf and scanf checking. 2660 llvm::SmallBitVector CheckedVarArgs; 2661 if (FDecl) { 2662 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2663 // Only create vector if there are format attributes. 2664 CheckedVarArgs.resize(Args.size()); 2665 2666 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2667 CheckedVarArgs); 2668 } 2669 } 2670 2671 // Refuse POD arguments that weren't caught by the format string 2672 // checks above. 2673 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 2674 if (CallType != VariadicDoesNotApply && 2675 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 2676 unsigned NumParams = Proto ? Proto->getNumParams() 2677 : FDecl && isa<FunctionDecl>(FDecl) 2678 ? cast<FunctionDecl>(FDecl)->getNumParams() 2679 : FDecl && isa<ObjCMethodDecl>(FDecl) 2680 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2681 : 0; 2682 2683 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2684 // Args[ArgIdx] can be null in malformed code. 2685 if (const Expr *Arg = Args[ArgIdx]) { 2686 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 2687 checkVariadicArgument(Arg, CallType); 2688 } 2689 } 2690 } 2691 2692 if (FDecl || Proto) { 2693 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 2694 2695 // Type safety checking. 2696 if (FDecl) { 2697 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 2698 CheckArgumentWithTypeTag(I, Args.data()); 2699 } 2700 } 2701 2702 if (FD) 2703 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 2704 } 2705 2706 /// CheckConstructorCall - Check a constructor call for correctness and safety 2707 /// properties not enforced by the C type system. 2708 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 2709 ArrayRef<const Expr *> Args, 2710 const FunctionProtoType *Proto, 2711 SourceLocation Loc) { 2712 VariadicCallType CallType = 2713 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 2714 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 2715 Loc, SourceRange(), CallType); 2716 } 2717 2718 /// CheckFunctionCall - Check a direct function call for various correctness 2719 /// and safety properties not strictly enforced by the C type system. 2720 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2721 const FunctionProtoType *Proto) { 2722 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 2723 isa<CXXMethodDecl>(FDecl); 2724 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 2725 IsMemberOperatorCall; 2726 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 2727 TheCall->getCallee()); 2728 Expr** Args = TheCall->getArgs(); 2729 unsigned NumArgs = TheCall->getNumArgs(); 2730 2731 Expr *ImplicitThis = nullptr; 2732 if (IsMemberOperatorCall) { 2733 // If this is a call to a member operator, hide the first argument 2734 // from checkCall. 2735 // FIXME: Our choice of AST representation here is less than ideal. 2736 ImplicitThis = Args[0]; 2737 ++Args; 2738 --NumArgs; 2739 } else if (IsMemberFunction) 2740 ImplicitThis = 2741 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 2742 2743 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 2744 IsMemberFunction, TheCall->getRParenLoc(), 2745 TheCall->getCallee()->getSourceRange(), CallType); 2746 2747 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 2748 // None of the checks below are needed for functions that don't have 2749 // simple names (e.g., C++ conversion functions). 2750 if (!FnInfo) 2751 return false; 2752 2753 CheckAbsoluteValueFunction(TheCall, FDecl); 2754 CheckMaxUnsignedZero(TheCall, FDecl); 2755 2756 if (getLangOpts().ObjC1) 2757 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 2758 2759 unsigned CMId = FDecl->getMemoryFunctionKind(); 2760 if (CMId == 0) 2761 return false; 2762 2763 // Handle memory setting and copying functions. 2764 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 2765 CheckStrlcpycatArguments(TheCall, FnInfo); 2766 else if (CMId == Builtin::BIstrncat) 2767 CheckStrncatArguments(TheCall, FnInfo); 2768 else 2769 CheckMemaccessArguments(TheCall, CMId, FnInfo); 2770 2771 return false; 2772 } 2773 2774 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 2775 ArrayRef<const Expr *> Args) { 2776 VariadicCallType CallType = 2777 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 2778 2779 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 2780 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 2781 CallType); 2782 2783 return false; 2784 } 2785 2786 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2787 const FunctionProtoType *Proto) { 2788 QualType Ty; 2789 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 2790 Ty = V->getType().getNonReferenceType(); 2791 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 2792 Ty = F->getType().getNonReferenceType(); 2793 else 2794 return false; 2795 2796 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 2797 !Ty->isFunctionProtoType()) 2798 return false; 2799 2800 VariadicCallType CallType; 2801 if (!Proto || !Proto->isVariadic()) { 2802 CallType = VariadicDoesNotApply; 2803 } else if (Ty->isBlockPointerType()) { 2804 CallType = VariadicBlock; 2805 } else { // Ty->isFunctionPointerType() 2806 CallType = VariadicFunction; 2807 } 2808 2809 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 2810 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2811 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2812 TheCall->getCallee()->getSourceRange(), CallType); 2813 2814 return false; 2815 } 2816 2817 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2818 /// such as function pointers returned from functions. 2819 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 2820 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 2821 TheCall->getCallee()); 2822 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 2823 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2824 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2825 TheCall->getCallee()->getSourceRange(), CallType); 2826 2827 return false; 2828 } 2829 2830 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 2831 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 2832 return false; 2833 2834 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 2835 switch (Op) { 2836 case AtomicExpr::AO__c11_atomic_init: 2837 case AtomicExpr::AO__opencl_atomic_init: 2838 llvm_unreachable("There is no ordering argument for an init"); 2839 2840 case AtomicExpr::AO__c11_atomic_load: 2841 case AtomicExpr::AO__opencl_atomic_load: 2842 case AtomicExpr::AO__atomic_load_n: 2843 case AtomicExpr::AO__atomic_load: 2844 return OrderingCABI != llvm::AtomicOrderingCABI::release && 2845 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2846 2847 case AtomicExpr::AO__c11_atomic_store: 2848 case AtomicExpr::AO__opencl_atomic_store: 2849 case AtomicExpr::AO__atomic_store: 2850 case AtomicExpr::AO__atomic_store_n: 2851 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 2852 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 2853 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2854 2855 default: 2856 return true; 2857 } 2858 } 2859 2860 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 2861 AtomicExpr::AtomicOp Op) { 2862 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 2863 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2864 2865 // All the non-OpenCL operations take one of the following forms. 2866 // The OpenCL operations take the __c11 forms with one extra argument for 2867 // synchronization scope. 2868 enum { 2869 // C __c11_atomic_init(A *, C) 2870 Init, 2871 // C __c11_atomic_load(A *, int) 2872 Load, 2873 // void __atomic_load(A *, CP, int) 2874 LoadCopy, 2875 // void __atomic_store(A *, CP, int) 2876 Copy, 2877 // C __c11_atomic_add(A *, M, int) 2878 Arithmetic, 2879 // C __atomic_exchange_n(A *, CP, int) 2880 Xchg, 2881 // void __atomic_exchange(A *, C *, CP, int) 2882 GNUXchg, 2883 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 2884 C11CmpXchg, 2885 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 2886 GNUCmpXchg 2887 } Form = Init; 2888 const unsigned NumForm = GNUCmpXchg + 1; 2889 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 2890 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 2891 // where: 2892 // C is an appropriate type, 2893 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 2894 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 2895 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 2896 // the int parameters are for orderings. 2897 2898 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 2899 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 2900 "need to update code for modified forms"); 2901 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 2902 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 2903 AtomicExpr::AO__atomic_load, 2904 "need to update code for modified C11 atomics"); 2905 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 2906 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 2907 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 2908 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 2909 IsOpenCL; 2910 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 2911 Op == AtomicExpr::AO__atomic_store_n || 2912 Op == AtomicExpr::AO__atomic_exchange_n || 2913 Op == AtomicExpr::AO__atomic_compare_exchange_n; 2914 bool IsAddSub = false; 2915 2916 switch (Op) { 2917 case AtomicExpr::AO__c11_atomic_init: 2918 case AtomicExpr::AO__opencl_atomic_init: 2919 Form = Init; 2920 break; 2921 2922 case AtomicExpr::AO__c11_atomic_load: 2923 case AtomicExpr::AO__opencl_atomic_load: 2924 case AtomicExpr::AO__atomic_load_n: 2925 Form = Load; 2926 break; 2927 2928 case AtomicExpr::AO__atomic_load: 2929 Form = LoadCopy; 2930 break; 2931 2932 case AtomicExpr::AO__c11_atomic_store: 2933 case AtomicExpr::AO__opencl_atomic_store: 2934 case AtomicExpr::AO__atomic_store: 2935 case AtomicExpr::AO__atomic_store_n: 2936 Form = Copy; 2937 break; 2938 2939 case AtomicExpr::AO__c11_atomic_fetch_add: 2940 case AtomicExpr::AO__c11_atomic_fetch_sub: 2941 case AtomicExpr::AO__opencl_atomic_fetch_add: 2942 case AtomicExpr::AO__opencl_atomic_fetch_sub: 2943 case AtomicExpr::AO__opencl_atomic_fetch_min: 2944 case AtomicExpr::AO__opencl_atomic_fetch_max: 2945 case AtomicExpr::AO__atomic_fetch_add: 2946 case AtomicExpr::AO__atomic_fetch_sub: 2947 case AtomicExpr::AO__atomic_add_fetch: 2948 case AtomicExpr::AO__atomic_sub_fetch: 2949 IsAddSub = true; 2950 // Fall through. 2951 case AtomicExpr::AO__c11_atomic_fetch_and: 2952 case AtomicExpr::AO__c11_atomic_fetch_or: 2953 case AtomicExpr::AO__c11_atomic_fetch_xor: 2954 case AtomicExpr::AO__opencl_atomic_fetch_and: 2955 case AtomicExpr::AO__opencl_atomic_fetch_or: 2956 case AtomicExpr::AO__opencl_atomic_fetch_xor: 2957 case AtomicExpr::AO__atomic_fetch_and: 2958 case AtomicExpr::AO__atomic_fetch_or: 2959 case AtomicExpr::AO__atomic_fetch_xor: 2960 case AtomicExpr::AO__atomic_fetch_nand: 2961 case AtomicExpr::AO__atomic_and_fetch: 2962 case AtomicExpr::AO__atomic_or_fetch: 2963 case AtomicExpr::AO__atomic_xor_fetch: 2964 case AtomicExpr::AO__atomic_nand_fetch: 2965 Form = Arithmetic; 2966 break; 2967 2968 case AtomicExpr::AO__c11_atomic_exchange: 2969 case AtomicExpr::AO__opencl_atomic_exchange: 2970 case AtomicExpr::AO__atomic_exchange_n: 2971 Form = Xchg; 2972 break; 2973 2974 case AtomicExpr::AO__atomic_exchange: 2975 Form = GNUXchg; 2976 break; 2977 2978 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 2979 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 2980 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 2981 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 2982 Form = C11CmpXchg; 2983 break; 2984 2985 case AtomicExpr::AO__atomic_compare_exchange: 2986 case AtomicExpr::AO__atomic_compare_exchange_n: 2987 Form = GNUCmpXchg; 2988 break; 2989 } 2990 2991 unsigned AdjustedNumArgs = NumArgs[Form]; 2992 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 2993 ++AdjustedNumArgs; 2994 // Check we have the right number of arguments. 2995 if (TheCall->getNumArgs() < AdjustedNumArgs) { 2996 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 2997 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 2998 << TheCall->getCallee()->getSourceRange(); 2999 return ExprError(); 3000 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 3001 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(), 3002 diag::err_typecheck_call_too_many_args) 3003 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 3004 << TheCall->getCallee()->getSourceRange(); 3005 return ExprError(); 3006 } 3007 3008 // Inspect the first argument of the atomic operation. 3009 Expr *Ptr = TheCall->getArg(0); 3010 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 3011 if (ConvertedPtr.isInvalid()) 3012 return ExprError(); 3013 3014 Ptr = ConvertedPtr.get(); 3015 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 3016 if (!pointerType) { 3017 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3018 << Ptr->getType() << Ptr->getSourceRange(); 3019 return ExprError(); 3020 } 3021 3022 // For a __c11 builtin, this should be a pointer to an _Atomic type. 3023 QualType AtomTy = pointerType->getPointeeType(); // 'A' 3024 QualType ValType = AtomTy; // 'C' 3025 if (IsC11) { 3026 if (!AtomTy->isAtomicType()) { 3027 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 3028 << Ptr->getType() << Ptr->getSourceRange(); 3029 return ExprError(); 3030 } 3031 if (AtomTy.isConstQualified() || 3032 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 3033 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 3034 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 3035 << Ptr->getSourceRange(); 3036 return ExprError(); 3037 } 3038 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 3039 } else if (Form != Load && Form != LoadCopy) { 3040 if (ValType.isConstQualified()) { 3041 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 3042 << Ptr->getType() << Ptr->getSourceRange(); 3043 return ExprError(); 3044 } 3045 } 3046 3047 // For an arithmetic operation, the implied arithmetic must be well-formed. 3048 if (Form == Arithmetic) { 3049 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 3050 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 3051 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3052 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3053 return ExprError(); 3054 } 3055 if (!IsAddSub && !ValType->isIntegerType()) { 3056 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 3057 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3058 return ExprError(); 3059 } 3060 if (IsC11 && ValType->isPointerType() && 3061 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 3062 diag::err_incomplete_type)) { 3063 return ExprError(); 3064 } 3065 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 3066 // For __atomic_*_n operations, the value type must be a scalar integral or 3067 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 3068 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3069 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3070 return ExprError(); 3071 } 3072 3073 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 3074 !AtomTy->isScalarType()) { 3075 // For GNU atomics, require a trivially-copyable type. This is not part of 3076 // the GNU atomics specification, but we enforce it for sanity. 3077 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 3078 << Ptr->getType() << Ptr->getSourceRange(); 3079 return ExprError(); 3080 } 3081 3082 switch (ValType.getObjCLifetime()) { 3083 case Qualifiers::OCL_None: 3084 case Qualifiers::OCL_ExplicitNone: 3085 // okay 3086 break; 3087 3088 case Qualifiers::OCL_Weak: 3089 case Qualifiers::OCL_Strong: 3090 case Qualifiers::OCL_Autoreleasing: 3091 // FIXME: Can this happen? By this point, ValType should be known 3092 // to be trivially copyable. 3093 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3094 << ValType << Ptr->getSourceRange(); 3095 return ExprError(); 3096 } 3097 3098 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 3099 // volatile-ness of the pointee-type inject itself into the result or the 3100 // other operands. Similarly atomic_load can take a pointer to a const 'A'. 3101 ValType.removeLocalVolatile(); 3102 ValType.removeLocalConst(); 3103 QualType ResultType = ValType; 3104 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 3105 Form == Init) 3106 ResultType = Context.VoidTy; 3107 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 3108 ResultType = Context.BoolTy; 3109 3110 // The type of a parameter passed 'by value'. In the GNU atomics, such 3111 // arguments are actually passed as pointers. 3112 QualType ByValType = ValType; // 'CP' 3113 if (!IsC11 && !IsN) 3114 ByValType = Ptr->getType(); 3115 3116 // The first argument --- the pointer --- has a fixed type; we 3117 // deduce the types of the rest of the arguments accordingly. Walk 3118 // the remaining arguments, converting them to the deduced value type. 3119 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) { 3120 QualType Ty; 3121 if (i < NumVals[Form] + 1) { 3122 switch (i) { 3123 case 1: 3124 // The second argument is the non-atomic operand. For arithmetic, this 3125 // is always passed by value, and for a compare_exchange it is always 3126 // passed by address. For the rest, GNU uses by-address and C11 uses 3127 // by-value. 3128 assert(Form != Load); 3129 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 3130 Ty = ValType; 3131 else if (Form == Copy || Form == Xchg) 3132 Ty = ByValType; 3133 else if (Form == Arithmetic) 3134 Ty = Context.getPointerDiffType(); 3135 else { 3136 Expr *ValArg = TheCall->getArg(i); 3137 // Treat this argument as _Nonnull as we want to show a warning if 3138 // NULL is passed into it. 3139 CheckNonNullArgument(*this, ValArg, DRE->getLocStart()); 3140 unsigned AS = 0; 3141 // Keep address space of non-atomic pointer type. 3142 if (const PointerType *PtrTy = 3143 ValArg->getType()->getAs<PointerType>()) { 3144 AS = PtrTy->getPointeeType().getAddressSpace(); 3145 } 3146 Ty = Context.getPointerType( 3147 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 3148 } 3149 break; 3150 case 2: 3151 // The third argument to compare_exchange / GNU exchange is a 3152 // (pointer to a) desired value. 3153 Ty = ByValType; 3154 break; 3155 case 3: 3156 // The fourth argument to GNU compare_exchange is a 'weak' flag. 3157 Ty = Context.BoolTy; 3158 break; 3159 } 3160 } else { 3161 // The order(s) and scope are always converted to int. 3162 Ty = Context.IntTy; 3163 } 3164 3165 InitializedEntity Entity = 3166 InitializedEntity::InitializeParameter(Context, Ty, false); 3167 ExprResult Arg = TheCall->getArg(i); 3168 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3169 if (Arg.isInvalid()) 3170 return true; 3171 TheCall->setArg(i, Arg.get()); 3172 } 3173 3174 // Permute the arguments into a 'consistent' order. 3175 SmallVector<Expr*, 5> SubExprs; 3176 SubExprs.push_back(Ptr); 3177 switch (Form) { 3178 case Init: 3179 // Note, AtomicExpr::getVal1() has a special case for this atomic. 3180 SubExprs.push_back(TheCall->getArg(1)); // Val1 3181 break; 3182 case Load: 3183 SubExprs.push_back(TheCall->getArg(1)); // Order 3184 break; 3185 case LoadCopy: 3186 case Copy: 3187 case Arithmetic: 3188 case Xchg: 3189 SubExprs.push_back(TheCall->getArg(2)); // Order 3190 SubExprs.push_back(TheCall->getArg(1)); // Val1 3191 break; 3192 case GNUXchg: 3193 // Note, AtomicExpr::getVal2() has a special case for this atomic. 3194 SubExprs.push_back(TheCall->getArg(3)); // Order 3195 SubExprs.push_back(TheCall->getArg(1)); // Val1 3196 SubExprs.push_back(TheCall->getArg(2)); // Val2 3197 break; 3198 case C11CmpXchg: 3199 SubExprs.push_back(TheCall->getArg(3)); // Order 3200 SubExprs.push_back(TheCall->getArg(1)); // Val1 3201 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 3202 SubExprs.push_back(TheCall->getArg(2)); // Val2 3203 break; 3204 case GNUCmpXchg: 3205 SubExprs.push_back(TheCall->getArg(4)); // Order 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 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 3223 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 3224 llvm::APSInt Result(32); 3225 if (Scope->isIntegerConstantExpr(Result, Context) && 3226 !ScopeModel->isValid(Result.getZExtValue())) { 3227 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope) 3228 << Scope->getSourceRange(); 3229 } 3230 SubExprs.push_back(Scope); 3231 } 3232 3233 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 3234 SubExprs, ResultType, Op, 3235 TheCall->getRParenLoc()); 3236 3237 if ((Op == AtomicExpr::AO__c11_atomic_load || 3238 Op == AtomicExpr::AO__c11_atomic_store || 3239 Op == AtomicExpr::AO__opencl_atomic_load || 3240 Op == AtomicExpr::AO__opencl_atomic_store ) && 3241 Context.AtomicUsesUnsupportedLibcall(AE)) 3242 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) 3243 << ((Op == AtomicExpr::AO__c11_atomic_load || 3244 Op == AtomicExpr::AO__opencl_atomic_load) 3245 ? 0 : 1); 3246 3247 return AE; 3248 } 3249 3250 /// checkBuiltinArgument - Given a call to a builtin function, perform 3251 /// normal type-checking on the given argument, updating the call in 3252 /// place. This is useful when a builtin function requires custom 3253 /// type-checking for some of its arguments but not necessarily all of 3254 /// them. 3255 /// 3256 /// Returns true on error. 3257 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 3258 FunctionDecl *Fn = E->getDirectCallee(); 3259 assert(Fn && "builtin call without direct callee!"); 3260 3261 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 3262 InitializedEntity Entity = 3263 InitializedEntity::InitializeParameter(S.Context, Param); 3264 3265 ExprResult Arg = E->getArg(0); 3266 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 3267 if (Arg.isInvalid()) 3268 return true; 3269 3270 E->setArg(ArgIndex, Arg.get()); 3271 return false; 3272 } 3273 3274 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 3275 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 3276 /// type of its first argument. The main ActOnCallExpr routines have already 3277 /// promoted the types of arguments because all of these calls are prototyped as 3278 /// void(...). 3279 /// 3280 /// This function goes through and does final semantic checking for these 3281 /// builtins, 3282 ExprResult 3283 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3284 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3285 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3286 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3287 3288 // Ensure that we have at least one argument to do type inference from. 3289 if (TheCall->getNumArgs() < 1) { 3290 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3291 << 0 << 1 << TheCall->getNumArgs() 3292 << TheCall->getCallee()->getSourceRange(); 3293 return ExprError(); 3294 } 3295 3296 // Inspect the first argument of the atomic builtin. This should always be 3297 // a pointer type, whose element is an integral scalar or pointer type. 3298 // Because it is a pointer type, we don't have to worry about any implicit 3299 // casts here. 3300 // FIXME: We don't allow floating point scalars as input. 3301 Expr *FirstArg = TheCall->getArg(0); 3302 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3303 if (FirstArgResult.isInvalid()) 3304 return ExprError(); 3305 FirstArg = FirstArgResult.get(); 3306 TheCall->setArg(0, FirstArg); 3307 3308 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3309 if (!pointerType) { 3310 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3311 << FirstArg->getType() << FirstArg->getSourceRange(); 3312 return ExprError(); 3313 } 3314 3315 QualType ValType = pointerType->getPointeeType(); 3316 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3317 !ValType->isBlockPointerType()) { 3318 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3319 << FirstArg->getType() << FirstArg->getSourceRange(); 3320 return ExprError(); 3321 } 3322 3323 switch (ValType.getObjCLifetime()) { 3324 case Qualifiers::OCL_None: 3325 case Qualifiers::OCL_ExplicitNone: 3326 // okay 3327 break; 3328 3329 case Qualifiers::OCL_Weak: 3330 case Qualifiers::OCL_Strong: 3331 case Qualifiers::OCL_Autoreleasing: 3332 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3333 << ValType << FirstArg->getSourceRange(); 3334 return ExprError(); 3335 } 3336 3337 // Strip any qualifiers off ValType. 3338 ValType = ValType.getUnqualifiedType(); 3339 3340 // The majority of builtins return a value, but a few have special return 3341 // types, so allow them to override appropriately below. 3342 QualType ResultType = ValType; 3343 3344 // We need to figure out which concrete builtin this maps onto. For example, 3345 // __sync_fetch_and_add with a 2 byte object turns into 3346 // __sync_fetch_and_add_2. 3347 #define BUILTIN_ROW(x) \ 3348 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3349 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3350 3351 static const unsigned BuiltinIndices[][5] = { 3352 BUILTIN_ROW(__sync_fetch_and_add), 3353 BUILTIN_ROW(__sync_fetch_and_sub), 3354 BUILTIN_ROW(__sync_fetch_and_or), 3355 BUILTIN_ROW(__sync_fetch_and_and), 3356 BUILTIN_ROW(__sync_fetch_and_xor), 3357 BUILTIN_ROW(__sync_fetch_and_nand), 3358 3359 BUILTIN_ROW(__sync_add_and_fetch), 3360 BUILTIN_ROW(__sync_sub_and_fetch), 3361 BUILTIN_ROW(__sync_and_and_fetch), 3362 BUILTIN_ROW(__sync_or_and_fetch), 3363 BUILTIN_ROW(__sync_xor_and_fetch), 3364 BUILTIN_ROW(__sync_nand_and_fetch), 3365 3366 BUILTIN_ROW(__sync_val_compare_and_swap), 3367 BUILTIN_ROW(__sync_bool_compare_and_swap), 3368 BUILTIN_ROW(__sync_lock_test_and_set), 3369 BUILTIN_ROW(__sync_lock_release), 3370 BUILTIN_ROW(__sync_swap) 3371 }; 3372 #undef BUILTIN_ROW 3373 3374 // Determine the index of the size. 3375 unsigned SizeIndex; 3376 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3377 case 1: SizeIndex = 0; break; 3378 case 2: SizeIndex = 1; break; 3379 case 4: SizeIndex = 2; break; 3380 case 8: SizeIndex = 3; break; 3381 case 16: SizeIndex = 4; break; 3382 default: 3383 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3384 << FirstArg->getType() << FirstArg->getSourceRange(); 3385 return ExprError(); 3386 } 3387 3388 // Each of these builtins has one pointer argument, followed by some number of 3389 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3390 // that we ignore. Find out which row of BuiltinIndices to read from as well 3391 // as the number of fixed args. 3392 unsigned BuiltinID = FDecl->getBuiltinID(); 3393 unsigned BuiltinIndex, NumFixed = 1; 3394 bool WarnAboutSemanticsChange = false; 3395 switch (BuiltinID) { 3396 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3397 case Builtin::BI__sync_fetch_and_add: 3398 case Builtin::BI__sync_fetch_and_add_1: 3399 case Builtin::BI__sync_fetch_and_add_2: 3400 case Builtin::BI__sync_fetch_and_add_4: 3401 case Builtin::BI__sync_fetch_and_add_8: 3402 case Builtin::BI__sync_fetch_and_add_16: 3403 BuiltinIndex = 0; 3404 break; 3405 3406 case Builtin::BI__sync_fetch_and_sub: 3407 case Builtin::BI__sync_fetch_and_sub_1: 3408 case Builtin::BI__sync_fetch_and_sub_2: 3409 case Builtin::BI__sync_fetch_and_sub_4: 3410 case Builtin::BI__sync_fetch_and_sub_8: 3411 case Builtin::BI__sync_fetch_and_sub_16: 3412 BuiltinIndex = 1; 3413 break; 3414 3415 case Builtin::BI__sync_fetch_and_or: 3416 case Builtin::BI__sync_fetch_and_or_1: 3417 case Builtin::BI__sync_fetch_and_or_2: 3418 case Builtin::BI__sync_fetch_and_or_4: 3419 case Builtin::BI__sync_fetch_and_or_8: 3420 case Builtin::BI__sync_fetch_and_or_16: 3421 BuiltinIndex = 2; 3422 break; 3423 3424 case Builtin::BI__sync_fetch_and_and: 3425 case Builtin::BI__sync_fetch_and_and_1: 3426 case Builtin::BI__sync_fetch_and_and_2: 3427 case Builtin::BI__sync_fetch_and_and_4: 3428 case Builtin::BI__sync_fetch_and_and_8: 3429 case Builtin::BI__sync_fetch_and_and_16: 3430 BuiltinIndex = 3; 3431 break; 3432 3433 case Builtin::BI__sync_fetch_and_xor: 3434 case Builtin::BI__sync_fetch_and_xor_1: 3435 case Builtin::BI__sync_fetch_and_xor_2: 3436 case Builtin::BI__sync_fetch_and_xor_4: 3437 case Builtin::BI__sync_fetch_and_xor_8: 3438 case Builtin::BI__sync_fetch_and_xor_16: 3439 BuiltinIndex = 4; 3440 break; 3441 3442 case Builtin::BI__sync_fetch_and_nand: 3443 case Builtin::BI__sync_fetch_and_nand_1: 3444 case Builtin::BI__sync_fetch_and_nand_2: 3445 case Builtin::BI__sync_fetch_and_nand_4: 3446 case Builtin::BI__sync_fetch_and_nand_8: 3447 case Builtin::BI__sync_fetch_and_nand_16: 3448 BuiltinIndex = 5; 3449 WarnAboutSemanticsChange = true; 3450 break; 3451 3452 case Builtin::BI__sync_add_and_fetch: 3453 case Builtin::BI__sync_add_and_fetch_1: 3454 case Builtin::BI__sync_add_and_fetch_2: 3455 case Builtin::BI__sync_add_and_fetch_4: 3456 case Builtin::BI__sync_add_and_fetch_8: 3457 case Builtin::BI__sync_add_and_fetch_16: 3458 BuiltinIndex = 6; 3459 break; 3460 3461 case Builtin::BI__sync_sub_and_fetch: 3462 case Builtin::BI__sync_sub_and_fetch_1: 3463 case Builtin::BI__sync_sub_and_fetch_2: 3464 case Builtin::BI__sync_sub_and_fetch_4: 3465 case Builtin::BI__sync_sub_and_fetch_8: 3466 case Builtin::BI__sync_sub_and_fetch_16: 3467 BuiltinIndex = 7; 3468 break; 3469 3470 case Builtin::BI__sync_and_and_fetch: 3471 case Builtin::BI__sync_and_and_fetch_1: 3472 case Builtin::BI__sync_and_and_fetch_2: 3473 case Builtin::BI__sync_and_and_fetch_4: 3474 case Builtin::BI__sync_and_and_fetch_8: 3475 case Builtin::BI__sync_and_and_fetch_16: 3476 BuiltinIndex = 8; 3477 break; 3478 3479 case Builtin::BI__sync_or_and_fetch: 3480 case Builtin::BI__sync_or_and_fetch_1: 3481 case Builtin::BI__sync_or_and_fetch_2: 3482 case Builtin::BI__sync_or_and_fetch_4: 3483 case Builtin::BI__sync_or_and_fetch_8: 3484 case Builtin::BI__sync_or_and_fetch_16: 3485 BuiltinIndex = 9; 3486 break; 3487 3488 case Builtin::BI__sync_xor_and_fetch: 3489 case Builtin::BI__sync_xor_and_fetch_1: 3490 case Builtin::BI__sync_xor_and_fetch_2: 3491 case Builtin::BI__sync_xor_and_fetch_4: 3492 case Builtin::BI__sync_xor_and_fetch_8: 3493 case Builtin::BI__sync_xor_and_fetch_16: 3494 BuiltinIndex = 10; 3495 break; 3496 3497 case Builtin::BI__sync_nand_and_fetch: 3498 case Builtin::BI__sync_nand_and_fetch_1: 3499 case Builtin::BI__sync_nand_and_fetch_2: 3500 case Builtin::BI__sync_nand_and_fetch_4: 3501 case Builtin::BI__sync_nand_and_fetch_8: 3502 case Builtin::BI__sync_nand_and_fetch_16: 3503 BuiltinIndex = 11; 3504 WarnAboutSemanticsChange = true; 3505 break; 3506 3507 case Builtin::BI__sync_val_compare_and_swap: 3508 case Builtin::BI__sync_val_compare_and_swap_1: 3509 case Builtin::BI__sync_val_compare_and_swap_2: 3510 case Builtin::BI__sync_val_compare_and_swap_4: 3511 case Builtin::BI__sync_val_compare_and_swap_8: 3512 case Builtin::BI__sync_val_compare_and_swap_16: 3513 BuiltinIndex = 12; 3514 NumFixed = 2; 3515 break; 3516 3517 case Builtin::BI__sync_bool_compare_and_swap: 3518 case Builtin::BI__sync_bool_compare_and_swap_1: 3519 case Builtin::BI__sync_bool_compare_and_swap_2: 3520 case Builtin::BI__sync_bool_compare_and_swap_4: 3521 case Builtin::BI__sync_bool_compare_and_swap_8: 3522 case Builtin::BI__sync_bool_compare_and_swap_16: 3523 BuiltinIndex = 13; 3524 NumFixed = 2; 3525 ResultType = Context.BoolTy; 3526 break; 3527 3528 case Builtin::BI__sync_lock_test_and_set: 3529 case Builtin::BI__sync_lock_test_and_set_1: 3530 case Builtin::BI__sync_lock_test_and_set_2: 3531 case Builtin::BI__sync_lock_test_and_set_4: 3532 case Builtin::BI__sync_lock_test_and_set_8: 3533 case Builtin::BI__sync_lock_test_and_set_16: 3534 BuiltinIndex = 14; 3535 break; 3536 3537 case Builtin::BI__sync_lock_release: 3538 case Builtin::BI__sync_lock_release_1: 3539 case Builtin::BI__sync_lock_release_2: 3540 case Builtin::BI__sync_lock_release_4: 3541 case Builtin::BI__sync_lock_release_8: 3542 case Builtin::BI__sync_lock_release_16: 3543 BuiltinIndex = 15; 3544 NumFixed = 0; 3545 ResultType = Context.VoidTy; 3546 break; 3547 3548 case Builtin::BI__sync_swap: 3549 case Builtin::BI__sync_swap_1: 3550 case Builtin::BI__sync_swap_2: 3551 case Builtin::BI__sync_swap_4: 3552 case Builtin::BI__sync_swap_8: 3553 case Builtin::BI__sync_swap_16: 3554 BuiltinIndex = 16; 3555 break; 3556 } 3557 3558 // Now that we know how many fixed arguments we expect, first check that we 3559 // have at least that many. 3560 if (TheCall->getNumArgs() < 1+NumFixed) { 3561 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3562 << 0 << 1+NumFixed << TheCall->getNumArgs() 3563 << TheCall->getCallee()->getSourceRange(); 3564 return ExprError(); 3565 } 3566 3567 if (WarnAboutSemanticsChange) { 3568 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 3569 << TheCall->getCallee()->getSourceRange(); 3570 } 3571 3572 // Get the decl for the concrete builtin from this, we can tell what the 3573 // concrete integer type we should convert to is. 3574 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 3575 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 3576 FunctionDecl *NewBuiltinDecl; 3577 if (NewBuiltinID == BuiltinID) 3578 NewBuiltinDecl = FDecl; 3579 else { 3580 // Perform builtin lookup to avoid redeclaring it. 3581 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3582 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3583 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3584 assert(Res.getFoundDecl()); 3585 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3586 if (!NewBuiltinDecl) 3587 return ExprError(); 3588 } 3589 3590 // The first argument --- the pointer --- has a fixed type; we 3591 // deduce the types of the rest of the arguments accordingly. Walk 3592 // the remaining arguments, converting them to the deduced value type. 3593 for (unsigned i = 0; i != NumFixed; ++i) { 3594 ExprResult Arg = TheCall->getArg(i+1); 3595 3596 // GCC does an implicit conversion to the pointer or integer ValType. This 3597 // can fail in some cases (1i -> int**), check for this error case now. 3598 // Initialize the argument. 3599 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3600 ValType, /*consume*/ false); 3601 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3602 if (Arg.isInvalid()) 3603 return ExprError(); 3604 3605 // Okay, we have something that *can* be converted to the right type. Check 3606 // to see if there is a potentially weird extension going on here. This can 3607 // happen when you do an atomic operation on something like an char* and 3608 // pass in 42. The 42 gets converted to char. This is even more strange 3609 // for things like 45.123 -> char, etc. 3610 // FIXME: Do this check. 3611 TheCall->setArg(i+1, Arg.get()); 3612 } 3613 3614 ASTContext& Context = this->getASTContext(); 3615 3616 // Create a new DeclRefExpr to refer to the new decl. 3617 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3618 Context, 3619 DRE->getQualifierLoc(), 3620 SourceLocation(), 3621 NewBuiltinDecl, 3622 /*enclosing*/ false, 3623 DRE->getLocation(), 3624 Context.BuiltinFnTy, 3625 DRE->getValueKind()); 3626 3627 // Set the callee in the CallExpr. 3628 // FIXME: This loses syntactic information. 3629 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3630 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3631 CK_BuiltinFnToFnPtr); 3632 TheCall->setCallee(PromotedCall.get()); 3633 3634 // Change the result type of the call to match the original value type. This 3635 // is arbitrary, but the codegen for these builtins ins design to handle it 3636 // gracefully. 3637 TheCall->setType(ResultType); 3638 3639 return TheCallResult; 3640 } 3641 3642 /// SemaBuiltinNontemporalOverloaded - We have a call to 3643 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 3644 /// overloaded function based on the pointer type of its last argument. 3645 /// 3646 /// This function goes through and does final semantic checking for these 3647 /// builtins. 3648 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 3649 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3650 DeclRefExpr *DRE = 3651 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3652 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3653 unsigned BuiltinID = FDecl->getBuiltinID(); 3654 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 3655 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 3656 "Unexpected nontemporal load/store builtin!"); 3657 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 3658 unsigned numArgs = isStore ? 2 : 1; 3659 3660 // Ensure that we have the proper number of arguments. 3661 if (checkArgCount(*this, TheCall, numArgs)) 3662 return ExprError(); 3663 3664 // Inspect the last argument of the nontemporal builtin. This should always 3665 // be a pointer type, from which we imply the type of the memory access. 3666 // Because it is a pointer type, we don't have to worry about any implicit 3667 // casts here. 3668 Expr *PointerArg = TheCall->getArg(numArgs - 1); 3669 ExprResult PointerArgResult = 3670 DefaultFunctionArrayLvalueConversion(PointerArg); 3671 3672 if (PointerArgResult.isInvalid()) 3673 return ExprError(); 3674 PointerArg = PointerArgResult.get(); 3675 TheCall->setArg(numArgs - 1, PointerArg); 3676 3677 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3678 if (!pointerType) { 3679 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 3680 << PointerArg->getType() << PointerArg->getSourceRange(); 3681 return ExprError(); 3682 } 3683 3684 QualType ValType = pointerType->getPointeeType(); 3685 3686 // Strip any qualifiers off ValType. 3687 ValType = ValType.getUnqualifiedType(); 3688 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3689 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 3690 !ValType->isVectorType()) { 3691 Diag(DRE->getLocStart(), 3692 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 3693 << PointerArg->getType() << PointerArg->getSourceRange(); 3694 return ExprError(); 3695 } 3696 3697 if (!isStore) { 3698 TheCall->setType(ValType); 3699 return TheCallResult; 3700 } 3701 3702 ExprResult ValArg = TheCall->getArg(0); 3703 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3704 Context, ValType, /*consume*/ false); 3705 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3706 if (ValArg.isInvalid()) 3707 return ExprError(); 3708 3709 TheCall->setArg(0, ValArg.get()); 3710 TheCall->setType(Context.VoidTy); 3711 return TheCallResult; 3712 } 3713 3714 /// CheckObjCString - Checks that the argument to the builtin 3715 /// CFString constructor is correct 3716 /// Note: It might also make sense to do the UTF-16 conversion here (would 3717 /// simplify the backend). 3718 bool Sema::CheckObjCString(Expr *Arg) { 3719 Arg = Arg->IgnoreParenCasts(); 3720 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 3721 3722 if (!Literal || !Literal->isAscii()) { 3723 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 3724 << Arg->getSourceRange(); 3725 return true; 3726 } 3727 3728 if (Literal->containsNonAsciiOrNull()) { 3729 StringRef String = Literal->getString(); 3730 unsigned NumBytes = String.size(); 3731 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 3732 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 3733 llvm::UTF16 *ToPtr = &ToBuf[0]; 3734 3735 llvm::ConversionResult Result = 3736 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 3737 ToPtr + NumBytes, llvm::strictConversion); 3738 // Check for conversion failure. 3739 if (Result != llvm::conversionOK) 3740 Diag(Arg->getLocStart(), 3741 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 3742 } 3743 return false; 3744 } 3745 3746 /// CheckObjCString - Checks that the format string argument to the os_log() 3747 /// and os_trace() functions is correct, and converts it to const char *. 3748 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 3749 Arg = Arg->IgnoreParenCasts(); 3750 auto *Literal = dyn_cast<StringLiteral>(Arg); 3751 if (!Literal) { 3752 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 3753 Literal = ObjcLiteral->getString(); 3754 } 3755 } 3756 3757 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 3758 return ExprError( 3759 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 3760 << Arg->getSourceRange()); 3761 } 3762 3763 ExprResult Result(Literal); 3764 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 3765 InitializedEntity Entity = 3766 InitializedEntity::InitializeParameter(Context, ResultTy, false); 3767 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 3768 return Result; 3769 } 3770 3771 /// Check that the user is calling the appropriate va_start builtin for the 3772 /// target and calling convention. 3773 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 3774 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 3775 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 3776 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 3777 bool IsWindows = TT.isOSWindows(); 3778 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 3779 if (IsX64 || IsAArch64) { 3780 clang::CallingConv CC = CC_C; 3781 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 3782 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3783 if (IsMSVAStart) { 3784 // Don't allow this in System V ABI functions. 3785 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 3786 return S.Diag(Fn->getLocStart(), 3787 diag::err_ms_va_start_used_in_sysv_function); 3788 } else { 3789 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 3790 // On x64 Windows, don't allow this in System V ABI functions. 3791 // (Yes, that means there's no corresponding way to support variadic 3792 // System V ABI functions on Windows.) 3793 if ((IsWindows && CC == CC_X86_64SysV) || 3794 (!IsWindows && CC == CC_Win64)) 3795 return S.Diag(Fn->getLocStart(), 3796 diag::err_va_start_used_in_wrong_abi_function) 3797 << !IsWindows; 3798 } 3799 return false; 3800 } 3801 3802 if (IsMSVAStart) 3803 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only); 3804 return false; 3805 } 3806 3807 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 3808 ParmVarDecl **LastParam = nullptr) { 3809 // Determine whether the current function, block, or obj-c method is variadic 3810 // and get its parameter list. 3811 bool IsVariadic = false; 3812 ArrayRef<ParmVarDecl *> Params; 3813 DeclContext *Caller = S.CurContext; 3814 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 3815 IsVariadic = Block->isVariadic(); 3816 Params = Block->parameters(); 3817 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 3818 IsVariadic = FD->isVariadic(); 3819 Params = FD->parameters(); 3820 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 3821 IsVariadic = MD->isVariadic(); 3822 // FIXME: This isn't correct for methods (results in bogus warning). 3823 Params = MD->parameters(); 3824 } else if (isa<CapturedDecl>(Caller)) { 3825 // We don't support va_start in a CapturedDecl. 3826 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt); 3827 return true; 3828 } else { 3829 // This must be some other declcontext that parses exprs. 3830 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function); 3831 return true; 3832 } 3833 3834 if (!IsVariadic) { 3835 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function); 3836 return true; 3837 } 3838 3839 if (LastParam) 3840 *LastParam = Params.empty() ? nullptr : Params.back(); 3841 3842 return false; 3843 } 3844 3845 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 3846 /// for validity. Emit an error and return true on failure; return false 3847 /// on success. 3848 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 3849 Expr *Fn = TheCall->getCallee(); 3850 3851 if (checkVAStartABI(*this, BuiltinID, Fn)) 3852 return true; 3853 3854 if (TheCall->getNumArgs() > 2) { 3855 Diag(TheCall->getArg(2)->getLocStart(), 3856 diag::err_typecheck_call_too_many_args) 3857 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3858 << Fn->getSourceRange() 3859 << SourceRange(TheCall->getArg(2)->getLocStart(), 3860 (*(TheCall->arg_end()-1))->getLocEnd()); 3861 return true; 3862 } 3863 3864 if (TheCall->getNumArgs() < 2) { 3865 return Diag(TheCall->getLocEnd(), 3866 diag::err_typecheck_call_too_few_args_at_least) 3867 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 3868 } 3869 3870 // Type-check the first argument normally. 3871 if (checkBuiltinArgument(*this, TheCall, 0)) 3872 return true; 3873 3874 // Check that the current function is variadic, and get its last parameter. 3875 ParmVarDecl *LastParam; 3876 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 3877 return true; 3878 3879 // Verify that the second argument to the builtin is the last argument of the 3880 // current function or method. 3881 bool SecondArgIsLastNamedArgument = false; 3882 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 3883 3884 // These are valid if SecondArgIsLastNamedArgument is false after the next 3885 // block. 3886 QualType Type; 3887 SourceLocation ParamLoc; 3888 bool IsCRegister = false; 3889 3890 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 3891 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 3892 SecondArgIsLastNamedArgument = PV == LastParam; 3893 3894 Type = PV->getType(); 3895 ParamLoc = PV->getLocation(); 3896 IsCRegister = 3897 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 3898 } 3899 } 3900 3901 if (!SecondArgIsLastNamedArgument) 3902 Diag(TheCall->getArg(1)->getLocStart(), 3903 diag::warn_second_arg_of_va_start_not_last_named_param); 3904 else if (IsCRegister || Type->isReferenceType() || 3905 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 3906 // Promotable integers are UB, but enumerations need a bit of 3907 // extra checking to see what their promotable type actually is. 3908 if (!Type->isPromotableIntegerType()) 3909 return false; 3910 if (!Type->isEnumeralType()) 3911 return true; 3912 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 3913 return !(ED && 3914 Context.typesAreCompatible(ED->getPromotionType(), Type)); 3915 }()) { 3916 unsigned Reason = 0; 3917 if (Type->isReferenceType()) Reason = 1; 3918 else if (IsCRegister) Reason = 2; 3919 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 3920 Diag(ParamLoc, diag::note_parameter_type) << Type; 3921 } 3922 3923 TheCall->setType(Context.VoidTy); 3924 return false; 3925 } 3926 3927 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) { 3928 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 3929 // const char *named_addr); 3930 3931 Expr *Func = Call->getCallee(); 3932 3933 if (Call->getNumArgs() < 3) 3934 return Diag(Call->getLocEnd(), 3935 diag::err_typecheck_call_too_few_args_at_least) 3936 << 0 /*function call*/ << 3 << Call->getNumArgs(); 3937 3938 // Type-check the first argument normally. 3939 if (checkBuiltinArgument(*this, Call, 0)) 3940 return true; 3941 3942 // Check that the current function is variadic. 3943 if (checkVAStartIsInVariadicFunction(*this, Func)) 3944 return true; 3945 3946 const struct { 3947 unsigned ArgNo; 3948 QualType Type; 3949 } ArgumentTypes[] = { 3950 { 1, Context.getPointerType(Context.CharTy.withConst()) }, 3951 { 2, Context.getSizeType() }, 3952 }; 3953 3954 for (const auto &AT : ArgumentTypes) { 3955 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens(); 3956 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType()) 3957 continue; 3958 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible) 3959 << Arg->getType() << AT.Type << 1 /* different class */ 3960 << 0 /* qualifier difference */ << 3 /* parameter mismatch */ 3961 << AT.ArgNo + 1 << Arg->getType() << AT.Type; 3962 } 3963 3964 return false; 3965 } 3966 3967 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 3968 /// friends. This is declared to take (...), so we have to check everything. 3969 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 3970 if (TheCall->getNumArgs() < 2) 3971 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3972 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 3973 if (TheCall->getNumArgs() > 2) 3974 return Diag(TheCall->getArg(2)->getLocStart(), 3975 diag::err_typecheck_call_too_many_args) 3976 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3977 << SourceRange(TheCall->getArg(2)->getLocStart(), 3978 (*(TheCall->arg_end()-1))->getLocEnd()); 3979 3980 ExprResult OrigArg0 = TheCall->getArg(0); 3981 ExprResult OrigArg1 = TheCall->getArg(1); 3982 3983 // Do standard promotions between the two arguments, returning their common 3984 // type. 3985 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 3986 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 3987 return true; 3988 3989 // Make sure any conversions are pushed back into the call; this is 3990 // type safe since unordered compare builtins are declared as "_Bool 3991 // foo(...)". 3992 TheCall->setArg(0, OrigArg0.get()); 3993 TheCall->setArg(1, OrigArg1.get()); 3994 3995 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 3996 return false; 3997 3998 // If the common type isn't a real floating type, then the arguments were 3999 // invalid for this operation. 4000 if (Res.isNull() || !Res->isRealFloatingType()) 4001 return Diag(OrigArg0.get()->getLocStart(), 4002 diag::err_typecheck_call_invalid_ordered_compare) 4003 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 4004 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 4005 4006 return false; 4007 } 4008 4009 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 4010 /// __builtin_isnan and friends. This is declared to take (...), so we have 4011 /// to check everything. We expect the last argument to be a floating point 4012 /// value. 4013 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 4014 if (TheCall->getNumArgs() < NumArgs) 4015 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4016 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 4017 if (TheCall->getNumArgs() > NumArgs) 4018 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 4019 diag::err_typecheck_call_too_many_args) 4020 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 4021 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 4022 (*(TheCall->arg_end()-1))->getLocEnd()); 4023 4024 Expr *OrigArg = TheCall->getArg(NumArgs-1); 4025 4026 if (OrigArg->isTypeDependent()) 4027 return false; 4028 4029 // This operation requires a non-_Complex floating-point number. 4030 if (!OrigArg->getType()->isRealFloatingType()) 4031 return Diag(OrigArg->getLocStart(), 4032 diag::err_typecheck_call_invalid_unary_fp) 4033 << OrigArg->getType() << OrigArg->getSourceRange(); 4034 4035 // If this is an implicit conversion from float -> float or double, remove it. 4036 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 4037 // Only remove standard FloatCasts, leaving other casts inplace 4038 if (Cast->getCastKind() == CK_FloatingCast) { 4039 Expr *CastArg = Cast->getSubExpr(); 4040 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 4041 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 4042 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) && 4043 "promotion from float to either float or double is the only expected cast here"); 4044 Cast->setSubExpr(nullptr); 4045 TheCall->setArg(NumArgs-1, CastArg); 4046 } 4047 } 4048 } 4049 4050 return false; 4051 } 4052 4053 // Customized Sema Checking for VSX builtins that have the following signature: 4054 // vector [...] builtinName(vector [...], vector [...], const int); 4055 // Which takes the same type of vectors (any legal vector type) for the first 4056 // two arguments and takes compile time constant for the third argument. 4057 // Example builtins are : 4058 // vector double vec_xxpermdi(vector double, vector double, int); 4059 // vector short vec_xxsldwi(vector short, vector short, int); 4060 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 4061 unsigned ExpectedNumArgs = 3; 4062 if (TheCall->getNumArgs() < ExpectedNumArgs) 4063 return Diag(TheCall->getLocEnd(), 4064 diag::err_typecheck_call_too_few_args_at_least) 4065 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4066 << TheCall->getSourceRange(); 4067 4068 if (TheCall->getNumArgs() > ExpectedNumArgs) 4069 return Diag(TheCall->getLocEnd(), 4070 diag::err_typecheck_call_too_many_args_at_most) 4071 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4072 << TheCall->getSourceRange(); 4073 4074 // Check the third argument is a compile time constant 4075 llvm::APSInt Value; 4076 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 4077 return Diag(TheCall->getLocStart(), 4078 diag::err_vsx_builtin_nonconstant_argument) 4079 << 3 /* argument index */ << TheCall->getDirectCallee() 4080 << SourceRange(TheCall->getArg(2)->getLocStart(), 4081 TheCall->getArg(2)->getLocEnd()); 4082 4083 QualType Arg1Ty = TheCall->getArg(0)->getType(); 4084 QualType Arg2Ty = TheCall->getArg(1)->getType(); 4085 4086 // Check the type of argument 1 and argument 2 are vectors. 4087 SourceLocation BuiltinLoc = TheCall->getLocStart(); 4088 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 4089 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 4090 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 4091 << TheCall->getDirectCallee() 4092 << SourceRange(TheCall->getArg(0)->getLocStart(), 4093 TheCall->getArg(1)->getLocEnd()); 4094 } 4095 4096 // Check the first two arguments are the same type. 4097 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 4098 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 4099 << TheCall->getDirectCallee() 4100 << SourceRange(TheCall->getArg(0)->getLocStart(), 4101 TheCall->getArg(1)->getLocEnd()); 4102 } 4103 4104 // When default clang type checking is turned off and the customized type 4105 // checking is used, the returning type of the function must be explicitly 4106 // set. Otherwise it is _Bool by default. 4107 TheCall->setType(Arg1Ty); 4108 4109 return false; 4110 } 4111 4112 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 4113 // This is declared to take (...), so we have to check everything. 4114 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 4115 if (TheCall->getNumArgs() < 2) 4116 return ExprError(Diag(TheCall->getLocEnd(), 4117 diag::err_typecheck_call_too_few_args_at_least) 4118 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4119 << TheCall->getSourceRange()); 4120 4121 // Determine which of the following types of shufflevector we're checking: 4122 // 1) unary, vector mask: (lhs, mask) 4123 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 4124 QualType resType = TheCall->getArg(0)->getType(); 4125 unsigned numElements = 0; 4126 4127 if (!TheCall->getArg(0)->isTypeDependent() && 4128 !TheCall->getArg(1)->isTypeDependent()) { 4129 QualType LHSType = TheCall->getArg(0)->getType(); 4130 QualType RHSType = TheCall->getArg(1)->getType(); 4131 4132 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 4133 return ExprError(Diag(TheCall->getLocStart(), 4134 diag::err_vec_builtin_non_vector) 4135 << TheCall->getDirectCallee() 4136 << SourceRange(TheCall->getArg(0)->getLocStart(), 4137 TheCall->getArg(1)->getLocEnd())); 4138 4139 numElements = LHSType->getAs<VectorType>()->getNumElements(); 4140 unsigned numResElements = TheCall->getNumArgs() - 2; 4141 4142 // Check to see if we have a call with 2 vector arguments, the unary shuffle 4143 // with mask. If so, verify that RHS is an integer vector type with the 4144 // same number of elts as lhs. 4145 if (TheCall->getNumArgs() == 2) { 4146 if (!RHSType->hasIntegerRepresentation() || 4147 RHSType->getAs<VectorType>()->getNumElements() != numElements) 4148 return ExprError(Diag(TheCall->getLocStart(), 4149 diag::err_vec_builtin_incompatible_vector) 4150 << TheCall->getDirectCallee() 4151 << SourceRange(TheCall->getArg(1)->getLocStart(), 4152 TheCall->getArg(1)->getLocEnd())); 4153 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 4154 return ExprError(Diag(TheCall->getLocStart(), 4155 diag::err_vec_builtin_incompatible_vector) 4156 << TheCall->getDirectCallee() 4157 << SourceRange(TheCall->getArg(0)->getLocStart(), 4158 TheCall->getArg(1)->getLocEnd())); 4159 } else if (numElements != numResElements) { 4160 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 4161 resType = Context.getVectorType(eltType, numResElements, 4162 VectorType::GenericVector); 4163 } 4164 } 4165 4166 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 4167 if (TheCall->getArg(i)->isTypeDependent() || 4168 TheCall->getArg(i)->isValueDependent()) 4169 continue; 4170 4171 llvm::APSInt Result(32); 4172 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 4173 return ExprError(Diag(TheCall->getLocStart(), 4174 diag::err_shufflevector_nonconstant_argument) 4175 << TheCall->getArg(i)->getSourceRange()); 4176 4177 // Allow -1 which will be translated to undef in the IR. 4178 if (Result.isSigned() && Result.isAllOnesValue()) 4179 continue; 4180 4181 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 4182 return ExprError(Diag(TheCall->getLocStart(), 4183 diag::err_shufflevector_argument_too_large) 4184 << TheCall->getArg(i)->getSourceRange()); 4185 } 4186 4187 SmallVector<Expr*, 32> exprs; 4188 4189 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 4190 exprs.push_back(TheCall->getArg(i)); 4191 TheCall->setArg(i, nullptr); 4192 } 4193 4194 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 4195 TheCall->getCallee()->getLocStart(), 4196 TheCall->getRParenLoc()); 4197 } 4198 4199 /// SemaConvertVectorExpr - Handle __builtin_convertvector 4200 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 4201 SourceLocation BuiltinLoc, 4202 SourceLocation RParenLoc) { 4203 ExprValueKind VK = VK_RValue; 4204 ExprObjectKind OK = OK_Ordinary; 4205 QualType DstTy = TInfo->getType(); 4206 QualType SrcTy = E->getType(); 4207 4208 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 4209 return ExprError(Diag(BuiltinLoc, 4210 diag::err_convertvector_non_vector) 4211 << E->getSourceRange()); 4212 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 4213 return ExprError(Diag(BuiltinLoc, 4214 diag::err_convertvector_non_vector_type)); 4215 4216 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 4217 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 4218 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 4219 if (SrcElts != DstElts) 4220 return ExprError(Diag(BuiltinLoc, 4221 diag::err_convertvector_incompatible_vector) 4222 << E->getSourceRange()); 4223 } 4224 4225 return new (Context) 4226 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4227 } 4228 4229 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 4230 // This is declared to take (const void*, ...) and can take two 4231 // optional constant int args. 4232 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 4233 unsigned NumArgs = TheCall->getNumArgs(); 4234 4235 if (NumArgs > 3) 4236 return Diag(TheCall->getLocEnd(), 4237 diag::err_typecheck_call_too_many_args_at_most) 4238 << 0 /*function call*/ << 3 << NumArgs 4239 << TheCall->getSourceRange(); 4240 4241 // Argument 0 is checked for us and the remaining arguments must be 4242 // constant integers. 4243 for (unsigned i = 1; i != NumArgs; ++i) 4244 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 4245 return true; 4246 4247 return false; 4248 } 4249 4250 /// SemaBuiltinAssume - Handle __assume (MS Extension). 4251 // __assume does not evaluate its arguments, and should warn if its argument 4252 // has side effects. 4253 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 4254 Expr *Arg = TheCall->getArg(0); 4255 if (Arg->isInstantiationDependent()) return false; 4256 4257 if (Arg->HasSideEffects(Context)) 4258 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 4259 << Arg->getSourceRange() 4260 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 4261 4262 return false; 4263 } 4264 4265 /// Handle __builtin_alloca_with_align. This is declared 4266 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 4267 /// than 8. 4268 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 4269 // The alignment must be a constant integer. 4270 Expr *Arg = TheCall->getArg(1); 4271 4272 // We can't check the value of a dependent argument. 4273 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4274 if (const auto *UE = 4275 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 4276 if (UE->getKind() == UETT_AlignOf) 4277 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 4278 << Arg->getSourceRange(); 4279 4280 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 4281 4282 if (!Result.isPowerOf2()) 4283 return Diag(TheCall->getLocStart(), 4284 diag::err_alignment_not_power_of_two) 4285 << Arg->getSourceRange(); 4286 4287 if (Result < Context.getCharWidth()) 4288 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 4289 << (unsigned)Context.getCharWidth() 4290 << Arg->getSourceRange(); 4291 4292 if (Result > INT32_MAX) 4293 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 4294 << INT32_MAX 4295 << Arg->getSourceRange(); 4296 } 4297 4298 return false; 4299 } 4300 4301 /// Handle __builtin_assume_aligned. This is declared 4302 /// as (const void*, size_t, ...) and can take one optional constant int arg. 4303 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 4304 unsigned NumArgs = TheCall->getNumArgs(); 4305 4306 if (NumArgs > 3) 4307 return Diag(TheCall->getLocEnd(), 4308 diag::err_typecheck_call_too_many_args_at_most) 4309 << 0 /*function call*/ << 3 << NumArgs 4310 << TheCall->getSourceRange(); 4311 4312 // The alignment must be a constant integer. 4313 Expr *Arg = TheCall->getArg(1); 4314 4315 // We can't check the value of a dependent argument. 4316 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4317 llvm::APSInt Result; 4318 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4319 return true; 4320 4321 if (!Result.isPowerOf2()) 4322 return Diag(TheCall->getLocStart(), 4323 diag::err_alignment_not_power_of_two) 4324 << Arg->getSourceRange(); 4325 } 4326 4327 if (NumArgs > 2) { 4328 ExprResult Arg(TheCall->getArg(2)); 4329 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4330 Context.getSizeType(), false); 4331 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4332 if (Arg.isInvalid()) return true; 4333 TheCall->setArg(2, Arg.get()); 4334 } 4335 4336 return false; 4337 } 4338 4339 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 4340 unsigned BuiltinID = 4341 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 4342 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 4343 4344 unsigned NumArgs = TheCall->getNumArgs(); 4345 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 4346 if (NumArgs < NumRequiredArgs) { 4347 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4348 << 0 /* function call */ << NumRequiredArgs << NumArgs 4349 << TheCall->getSourceRange(); 4350 } 4351 if (NumArgs >= NumRequiredArgs + 0x100) { 4352 return Diag(TheCall->getLocEnd(), 4353 diag::err_typecheck_call_too_many_args_at_most) 4354 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 4355 << TheCall->getSourceRange(); 4356 } 4357 unsigned i = 0; 4358 4359 // For formatting call, check buffer arg. 4360 if (!IsSizeCall) { 4361 ExprResult Arg(TheCall->getArg(i)); 4362 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4363 Context, Context.VoidPtrTy, false); 4364 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4365 if (Arg.isInvalid()) 4366 return true; 4367 TheCall->setArg(i, Arg.get()); 4368 i++; 4369 } 4370 4371 // Check string literal arg. 4372 unsigned FormatIdx = i; 4373 { 4374 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4375 if (Arg.isInvalid()) 4376 return true; 4377 TheCall->setArg(i, Arg.get()); 4378 i++; 4379 } 4380 4381 // Make sure variadic args are scalar. 4382 unsigned FirstDataArg = i; 4383 while (i < NumArgs) { 4384 ExprResult Arg = DefaultVariadicArgumentPromotion( 4385 TheCall->getArg(i), VariadicFunction, nullptr); 4386 if (Arg.isInvalid()) 4387 return true; 4388 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4389 if (ArgSize.getQuantity() >= 0x100) { 4390 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4391 << i << (int)ArgSize.getQuantity() << 0xff 4392 << TheCall->getSourceRange(); 4393 } 4394 TheCall->setArg(i, Arg.get()); 4395 i++; 4396 } 4397 4398 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4399 // call to avoid duplicate diagnostics. 4400 if (!IsSizeCall) { 4401 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4402 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4403 bool Success = CheckFormatArguments( 4404 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4405 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4406 CheckedVarArgs); 4407 if (!Success) 4408 return true; 4409 } 4410 4411 if (IsSizeCall) { 4412 TheCall->setType(Context.getSizeType()); 4413 } else { 4414 TheCall->setType(Context.VoidPtrTy); 4415 } 4416 return false; 4417 } 4418 4419 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4420 /// TheCall is a constant expression. 4421 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4422 llvm::APSInt &Result) { 4423 Expr *Arg = TheCall->getArg(ArgNum); 4424 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4425 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4426 4427 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4428 4429 if (!Arg->isIntegerConstantExpr(Result, Context)) 4430 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 4431 << FDecl->getDeclName() << Arg->getSourceRange(); 4432 4433 return false; 4434 } 4435 4436 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 4437 /// TheCall is a constant expression in the range [Low, High]. 4438 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 4439 int Low, int High) { 4440 llvm::APSInt Result; 4441 4442 // We can't check the value of a dependent argument. 4443 Expr *Arg = TheCall->getArg(ArgNum); 4444 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4445 return false; 4446 4447 // Check constant-ness first. 4448 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4449 return true; 4450 4451 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 4452 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 4453 << Low << High << Arg->getSourceRange(); 4454 4455 return false; 4456 } 4457 4458 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 4459 /// TheCall is a constant expression is a multiple of Num.. 4460 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 4461 unsigned Num) { 4462 llvm::APSInt Result; 4463 4464 // We can't check the value of a dependent argument. 4465 Expr *Arg = TheCall->getArg(ArgNum); 4466 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4467 return false; 4468 4469 // Check constant-ness first. 4470 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4471 return true; 4472 4473 if (Result.getSExtValue() % Num != 0) 4474 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 4475 << Num << Arg->getSourceRange(); 4476 4477 return false; 4478 } 4479 4480 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 4481 /// TheCall is an ARM/AArch64 special register string literal. 4482 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 4483 int ArgNum, unsigned ExpectedFieldNum, 4484 bool AllowName) { 4485 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 4486 BuiltinID == ARM::BI__builtin_arm_wsr64 || 4487 BuiltinID == ARM::BI__builtin_arm_rsr || 4488 BuiltinID == ARM::BI__builtin_arm_rsrp || 4489 BuiltinID == ARM::BI__builtin_arm_wsr || 4490 BuiltinID == ARM::BI__builtin_arm_wsrp; 4491 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 4492 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 4493 BuiltinID == AArch64::BI__builtin_arm_rsr || 4494 BuiltinID == AArch64::BI__builtin_arm_rsrp || 4495 BuiltinID == AArch64::BI__builtin_arm_wsr || 4496 BuiltinID == AArch64::BI__builtin_arm_wsrp; 4497 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 4498 4499 // We can't check the value of a dependent argument. 4500 Expr *Arg = TheCall->getArg(ArgNum); 4501 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4502 return false; 4503 4504 // Check if the argument is a string literal. 4505 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4506 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 4507 << Arg->getSourceRange(); 4508 4509 // Check the type of special register given. 4510 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4511 SmallVector<StringRef, 6> Fields; 4512 Reg.split(Fields, ":"); 4513 4514 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 4515 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4516 << Arg->getSourceRange(); 4517 4518 // If the string is the name of a register then we cannot check that it is 4519 // valid here but if the string is of one the forms described in ACLE then we 4520 // can check that the supplied fields are integers and within the valid 4521 // ranges. 4522 if (Fields.size() > 1) { 4523 bool FiveFields = Fields.size() == 5; 4524 4525 bool ValidString = true; 4526 if (IsARMBuiltin) { 4527 ValidString &= Fields[0].startswith_lower("cp") || 4528 Fields[0].startswith_lower("p"); 4529 if (ValidString) 4530 Fields[0] = 4531 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 4532 4533 ValidString &= Fields[2].startswith_lower("c"); 4534 if (ValidString) 4535 Fields[2] = Fields[2].drop_front(1); 4536 4537 if (FiveFields) { 4538 ValidString &= Fields[3].startswith_lower("c"); 4539 if (ValidString) 4540 Fields[3] = Fields[3].drop_front(1); 4541 } 4542 } 4543 4544 SmallVector<int, 5> Ranges; 4545 if (FiveFields) 4546 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 4547 else 4548 Ranges.append({15, 7, 15}); 4549 4550 for (unsigned i=0; i<Fields.size(); ++i) { 4551 int IntField; 4552 ValidString &= !Fields[i].getAsInteger(10, IntField); 4553 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 4554 } 4555 4556 if (!ValidString) 4557 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4558 << Arg->getSourceRange(); 4559 4560 } else if (IsAArch64Builtin && Fields.size() == 1) { 4561 // If the register name is one of those that appear in the condition below 4562 // and the special register builtin being used is one of the write builtins, 4563 // then we require that the argument provided for writing to the register 4564 // is an integer constant expression. This is because it will be lowered to 4565 // an MSR (immediate) instruction, so we need to know the immediate at 4566 // compile time. 4567 if (TheCall->getNumArgs() != 2) 4568 return false; 4569 4570 std::string RegLower = Reg.lower(); 4571 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 4572 RegLower != "pan" && RegLower != "uao") 4573 return false; 4574 4575 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4576 } 4577 4578 return false; 4579 } 4580 4581 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 4582 /// This checks that the target supports __builtin_longjmp and 4583 /// that val is a constant 1. 4584 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 4585 if (!Context.getTargetInfo().hasSjLjLowering()) 4586 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 4587 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4588 4589 Expr *Arg = TheCall->getArg(1); 4590 llvm::APSInt Result; 4591 4592 // TODO: This is less than ideal. Overload this to take a value. 4593 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4594 return true; 4595 4596 if (Result != 1) 4597 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 4598 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 4599 4600 return false; 4601 } 4602 4603 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 4604 /// This checks that the target supports __builtin_setjmp. 4605 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 4606 if (!Context.getTargetInfo().hasSjLjLowering()) 4607 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 4608 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4609 return false; 4610 } 4611 4612 namespace { 4613 class UncoveredArgHandler { 4614 enum { Unknown = -1, AllCovered = -2 }; 4615 signed FirstUncoveredArg; 4616 SmallVector<const Expr *, 4> DiagnosticExprs; 4617 4618 public: 4619 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { } 4620 4621 bool hasUncoveredArg() const { 4622 return (FirstUncoveredArg >= 0); 4623 } 4624 4625 unsigned getUncoveredArg() const { 4626 assert(hasUncoveredArg() && "no uncovered argument"); 4627 return FirstUncoveredArg; 4628 } 4629 4630 void setAllCovered() { 4631 // A string has been found with all arguments covered, so clear out 4632 // the diagnostics. 4633 DiagnosticExprs.clear(); 4634 FirstUncoveredArg = AllCovered; 4635 } 4636 4637 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 4638 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 4639 4640 // Don't update if a previous string covers all arguments. 4641 if (FirstUncoveredArg == AllCovered) 4642 return; 4643 4644 // UncoveredArgHandler tracks the highest uncovered argument index 4645 // and with it all the strings that match this index. 4646 if (NewFirstUncoveredArg == FirstUncoveredArg) 4647 DiagnosticExprs.push_back(StrExpr); 4648 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 4649 DiagnosticExprs.clear(); 4650 DiagnosticExprs.push_back(StrExpr); 4651 FirstUncoveredArg = NewFirstUncoveredArg; 4652 } 4653 } 4654 4655 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 4656 }; 4657 4658 enum StringLiteralCheckType { 4659 SLCT_NotALiteral, 4660 SLCT_UncheckedLiteral, 4661 SLCT_CheckedLiteral 4662 }; 4663 } // end anonymous namespace 4664 4665 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 4666 BinaryOperatorKind BinOpKind, 4667 bool AddendIsRight) { 4668 unsigned BitWidth = Offset.getBitWidth(); 4669 unsigned AddendBitWidth = Addend.getBitWidth(); 4670 // There might be negative interim results. 4671 if (Addend.isUnsigned()) { 4672 Addend = Addend.zext(++AddendBitWidth); 4673 Addend.setIsSigned(true); 4674 } 4675 // Adjust the bit width of the APSInts. 4676 if (AddendBitWidth > BitWidth) { 4677 Offset = Offset.sext(AddendBitWidth); 4678 BitWidth = AddendBitWidth; 4679 } else if (BitWidth > AddendBitWidth) { 4680 Addend = Addend.sext(BitWidth); 4681 } 4682 4683 bool Ov = false; 4684 llvm::APSInt ResOffset = Offset; 4685 if (BinOpKind == BO_Add) 4686 ResOffset = Offset.sadd_ov(Addend, Ov); 4687 else { 4688 assert(AddendIsRight && BinOpKind == BO_Sub && 4689 "operator must be add or sub with addend on the right"); 4690 ResOffset = Offset.ssub_ov(Addend, Ov); 4691 } 4692 4693 // We add an offset to a pointer here so we should support an offset as big as 4694 // possible. 4695 if (Ov) { 4696 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big"); 4697 Offset = Offset.sext(2 * BitWidth); 4698 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 4699 return; 4700 } 4701 4702 Offset = ResOffset; 4703 } 4704 4705 namespace { 4706 // This is a wrapper class around StringLiteral to support offsetted string 4707 // literals as format strings. It takes the offset into account when returning 4708 // the string and its length or the source locations to display notes correctly. 4709 class FormatStringLiteral { 4710 const StringLiteral *FExpr; 4711 int64_t Offset; 4712 4713 public: 4714 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 4715 : FExpr(fexpr), Offset(Offset) {} 4716 4717 StringRef getString() const { 4718 return FExpr->getString().drop_front(Offset); 4719 } 4720 4721 unsigned getByteLength() const { 4722 return FExpr->getByteLength() - getCharByteWidth() * Offset; 4723 } 4724 unsigned getLength() const { return FExpr->getLength() - Offset; } 4725 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 4726 4727 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 4728 4729 QualType getType() const { return FExpr->getType(); } 4730 4731 bool isAscii() const { return FExpr->isAscii(); } 4732 bool isWide() const { return FExpr->isWide(); } 4733 bool isUTF8() const { return FExpr->isUTF8(); } 4734 bool isUTF16() const { return FExpr->isUTF16(); } 4735 bool isUTF32() const { return FExpr->isUTF32(); } 4736 bool isPascal() const { return FExpr->isPascal(); } 4737 4738 SourceLocation getLocationOfByte( 4739 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 4740 const TargetInfo &Target, unsigned *StartToken = nullptr, 4741 unsigned *StartTokenByteOffset = nullptr) const { 4742 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 4743 StartToken, StartTokenByteOffset); 4744 } 4745 4746 SourceLocation getLocStart() const LLVM_READONLY { 4747 return FExpr->getLocStart().getLocWithOffset(Offset); 4748 } 4749 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 4750 }; 4751 } // end anonymous namespace 4752 4753 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 4754 const Expr *OrigFormatExpr, 4755 ArrayRef<const Expr *> Args, 4756 bool HasVAListArg, unsigned format_idx, 4757 unsigned firstDataArg, 4758 Sema::FormatStringType Type, 4759 bool inFunctionCall, 4760 Sema::VariadicCallType CallType, 4761 llvm::SmallBitVector &CheckedVarArgs, 4762 UncoveredArgHandler &UncoveredArg); 4763 4764 // Determine if an expression is a string literal or constant string. 4765 // If this function returns false on the arguments to a function expecting a 4766 // format string, we will usually need to emit a warning. 4767 // True string literals are then checked by CheckFormatString. 4768 static StringLiteralCheckType 4769 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 4770 bool HasVAListArg, unsigned format_idx, 4771 unsigned firstDataArg, Sema::FormatStringType Type, 4772 Sema::VariadicCallType CallType, bool InFunctionCall, 4773 llvm::SmallBitVector &CheckedVarArgs, 4774 UncoveredArgHandler &UncoveredArg, 4775 llvm::APSInt Offset) { 4776 tryAgain: 4777 assert(Offset.isSigned() && "invalid offset"); 4778 4779 if (E->isTypeDependent() || E->isValueDependent()) 4780 return SLCT_NotALiteral; 4781 4782 E = E->IgnoreParenCasts(); 4783 4784 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 4785 // Technically -Wformat-nonliteral does not warn about this case. 4786 // The behavior of printf and friends in this case is implementation 4787 // dependent. Ideally if the format string cannot be null then 4788 // it should have a 'nonnull' attribute in the function prototype. 4789 return SLCT_UncheckedLiteral; 4790 4791 switch (E->getStmtClass()) { 4792 case Stmt::BinaryConditionalOperatorClass: 4793 case Stmt::ConditionalOperatorClass: { 4794 // The expression is a literal if both sub-expressions were, and it was 4795 // completely checked only if both sub-expressions were checked. 4796 const AbstractConditionalOperator *C = 4797 cast<AbstractConditionalOperator>(E); 4798 4799 // Determine whether it is necessary to check both sub-expressions, for 4800 // example, because the condition expression is a constant that can be 4801 // evaluated at compile time. 4802 bool CheckLeft = true, CheckRight = true; 4803 4804 bool Cond; 4805 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 4806 if (Cond) 4807 CheckRight = false; 4808 else 4809 CheckLeft = false; 4810 } 4811 4812 // We need to maintain the offsets for the right and the left hand side 4813 // separately to check if every possible indexed expression is a valid 4814 // string literal. They might have different offsets for different string 4815 // literals in the end. 4816 StringLiteralCheckType Left; 4817 if (!CheckLeft) 4818 Left = SLCT_UncheckedLiteral; 4819 else { 4820 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 4821 HasVAListArg, format_idx, firstDataArg, 4822 Type, CallType, InFunctionCall, 4823 CheckedVarArgs, UncoveredArg, Offset); 4824 if (Left == SLCT_NotALiteral || !CheckRight) { 4825 return Left; 4826 } 4827 } 4828 4829 StringLiteralCheckType Right = 4830 checkFormatStringExpr(S, C->getFalseExpr(), Args, 4831 HasVAListArg, format_idx, firstDataArg, 4832 Type, CallType, InFunctionCall, CheckedVarArgs, 4833 UncoveredArg, Offset); 4834 4835 return (CheckLeft && Left < Right) ? Left : Right; 4836 } 4837 4838 case Stmt::ImplicitCastExprClass: { 4839 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4840 goto tryAgain; 4841 } 4842 4843 case Stmt::OpaqueValueExprClass: 4844 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 4845 E = src; 4846 goto tryAgain; 4847 } 4848 return SLCT_NotALiteral; 4849 4850 case Stmt::PredefinedExprClass: 4851 // While __func__, etc., are technically not string literals, they 4852 // cannot contain format specifiers and thus are not a security 4853 // liability. 4854 return SLCT_UncheckedLiteral; 4855 4856 case Stmt::DeclRefExprClass: { 4857 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 4858 4859 // As an exception, do not flag errors for variables binding to 4860 // const string literals. 4861 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 4862 bool isConstant = false; 4863 QualType T = DR->getType(); 4864 4865 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 4866 isConstant = AT->getElementType().isConstant(S.Context); 4867 } else if (const PointerType *PT = T->getAs<PointerType>()) { 4868 isConstant = T.isConstant(S.Context) && 4869 PT->getPointeeType().isConstant(S.Context); 4870 } else if (T->isObjCObjectPointerType()) { 4871 // In ObjC, there is usually no "const ObjectPointer" type, 4872 // so don't check if the pointee type is constant. 4873 isConstant = T.isConstant(S.Context); 4874 } 4875 4876 if (isConstant) { 4877 if (const Expr *Init = VD->getAnyInitializer()) { 4878 // Look through initializers like const char c[] = { "foo" } 4879 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4880 if (InitList->isStringLiteralInit()) 4881 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 4882 } 4883 return checkFormatStringExpr(S, Init, Args, 4884 HasVAListArg, format_idx, 4885 firstDataArg, Type, CallType, 4886 /*InFunctionCall*/ false, CheckedVarArgs, 4887 UncoveredArg, Offset); 4888 } 4889 } 4890 4891 // For vprintf* functions (i.e., HasVAListArg==true), we add a 4892 // special check to see if the format string is a function parameter 4893 // of the function calling the printf function. If the function 4894 // has an attribute indicating it is a printf-like function, then we 4895 // should suppress warnings concerning non-literals being used in a call 4896 // to a vprintf function. For example: 4897 // 4898 // void 4899 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 4900 // va_list ap; 4901 // va_start(ap, fmt); 4902 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 4903 // ... 4904 // } 4905 if (HasVAListArg) { 4906 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 4907 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 4908 int PVIndex = PV->getFunctionScopeIndex() + 1; 4909 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 4910 // adjust for implicit parameter 4911 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4912 if (MD->isInstance()) 4913 ++PVIndex; 4914 // We also check if the formats are compatible. 4915 // We can't pass a 'scanf' string to a 'printf' function. 4916 if (PVIndex == PVFormat->getFormatIdx() && 4917 Type == S.GetFormatStringType(PVFormat)) 4918 return SLCT_UncheckedLiteral; 4919 } 4920 } 4921 } 4922 } 4923 } 4924 4925 return SLCT_NotALiteral; 4926 } 4927 4928 case Stmt::CallExprClass: 4929 case Stmt::CXXMemberCallExprClass: { 4930 const CallExpr *CE = cast<CallExpr>(E); 4931 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 4932 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 4933 unsigned ArgIndex = FA->getFormatIdx(); 4934 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4935 if (MD->isInstance()) 4936 --ArgIndex; 4937 const Expr *Arg = CE->getArg(ArgIndex - 1); 4938 4939 return checkFormatStringExpr(S, Arg, Args, 4940 HasVAListArg, format_idx, firstDataArg, 4941 Type, CallType, InFunctionCall, 4942 CheckedVarArgs, UncoveredArg, Offset); 4943 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 4944 unsigned BuiltinID = FD->getBuiltinID(); 4945 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 4946 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 4947 const Expr *Arg = CE->getArg(0); 4948 return checkFormatStringExpr(S, Arg, Args, 4949 HasVAListArg, format_idx, 4950 firstDataArg, Type, CallType, 4951 InFunctionCall, CheckedVarArgs, 4952 UncoveredArg, Offset); 4953 } 4954 } 4955 } 4956 4957 return SLCT_NotALiteral; 4958 } 4959 case Stmt::ObjCMessageExprClass: { 4960 const auto *ME = cast<ObjCMessageExpr>(E); 4961 if (const auto *ND = ME->getMethodDecl()) { 4962 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 4963 unsigned ArgIndex = FA->getFormatIdx(); 4964 const Expr *Arg = ME->getArg(ArgIndex - 1); 4965 return checkFormatStringExpr( 4966 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 4967 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 4968 } 4969 } 4970 4971 return SLCT_NotALiteral; 4972 } 4973 case Stmt::ObjCStringLiteralClass: 4974 case Stmt::StringLiteralClass: { 4975 const StringLiteral *StrE = nullptr; 4976 4977 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 4978 StrE = ObjCFExpr->getString(); 4979 else 4980 StrE = cast<StringLiteral>(E); 4981 4982 if (StrE) { 4983 if (Offset.isNegative() || Offset > StrE->getLength()) { 4984 // TODO: It would be better to have an explicit warning for out of 4985 // bounds literals. 4986 return SLCT_NotALiteral; 4987 } 4988 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 4989 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 4990 firstDataArg, Type, InFunctionCall, CallType, 4991 CheckedVarArgs, UncoveredArg); 4992 return SLCT_CheckedLiteral; 4993 } 4994 4995 return SLCT_NotALiteral; 4996 } 4997 case Stmt::BinaryOperatorClass: { 4998 llvm::APSInt LResult; 4999 llvm::APSInt RResult; 5000 5001 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 5002 5003 // A string literal + an int offset is still a string literal. 5004 if (BinOp->isAdditiveOp()) { 5005 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 5006 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 5007 5008 if (LIsInt != RIsInt) { 5009 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 5010 5011 if (LIsInt) { 5012 if (BinOpKind == BO_Add) { 5013 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 5014 E = BinOp->getRHS(); 5015 goto tryAgain; 5016 } 5017 } else { 5018 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 5019 E = BinOp->getLHS(); 5020 goto tryAgain; 5021 } 5022 } 5023 } 5024 5025 return SLCT_NotALiteral; 5026 } 5027 case Stmt::UnaryOperatorClass: { 5028 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 5029 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 5030 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) { 5031 llvm::APSInt IndexResult; 5032 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 5033 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 5034 E = ASE->getBase(); 5035 goto tryAgain; 5036 } 5037 } 5038 5039 return SLCT_NotALiteral; 5040 } 5041 5042 default: 5043 return SLCT_NotALiteral; 5044 } 5045 } 5046 5047 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 5048 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 5049 .Case("scanf", FST_Scanf) 5050 .Cases("printf", "printf0", FST_Printf) 5051 .Cases("NSString", "CFString", FST_NSString) 5052 .Case("strftime", FST_Strftime) 5053 .Case("strfmon", FST_Strfmon) 5054 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 5055 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 5056 .Case("os_trace", FST_OSLog) 5057 .Case("os_log", FST_OSLog) 5058 .Default(FST_Unknown); 5059 } 5060 5061 /// CheckFormatArguments - Check calls to printf and scanf (and similar 5062 /// functions) for correct use of format strings. 5063 /// Returns true if a format string has been fully checked. 5064 bool Sema::CheckFormatArguments(const FormatAttr *Format, 5065 ArrayRef<const Expr *> Args, 5066 bool IsCXXMember, 5067 VariadicCallType CallType, 5068 SourceLocation Loc, SourceRange Range, 5069 llvm::SmallBitVector &CheckedVarArgs) { 5070 FormatStringInfo FSI; 5071 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 5072 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 5073 FSI.FirstDataArg, GetFormatStringType(Format), 5074 CallType, Loc, Range, CheckedVarArgs); 5075 return false; 5076 } 5077 5078 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 5079 bool HasVAListArg, unsigned format_idx, 5080 unsigned firstDataArg, FormatStringType Type, 5081 VariadicCallType CallType, 5082 SourceLocation Loc, SourceRange Range, 5083 llvm::SmallBitVector &CheckedVarArgs) { 5084 // CHECK: printf/scanf-like function is called with no format string. 5085 if (format_idx >= Args.size()) { 5086 Diag(Loc, diag::warn_missing_format_string) << Range; 5087 return false; 5088 } 5089 5090 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 5091 5092 // CHECK: format string is not a string literal. 5093 // 5094 // Dynamically generated format strings are difficult to 5095 // automatically vet at compile time. Requiring that format strings 5096 // are string literals: (1) permits the checking of format strings by 5097 // the compiler and thereby (2) can practically remove the source of 5098 // many format string exploits. 5099 5100 // Format string can be either ObjC string (e.g. @"%d") or 5101 // C string (e.g. "%d") 5102 // ObjC string uses the same format specifiers as C string, so we can use 5103 // the same format string checking logic for both ObjC and C strings. 5104 UncoveredArgHandler UncoveredArg; 5105 StringLiteralCheckType CT = 5106 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 5107 format_idx, firstDataArg, Type, CallType, 5108 /*IsFunctionCall*/ true, CheckedVarArgs, 5109 UncoveredArg, 5110 /*no string offset*/ llvm::APSInt(64, false) = 0); 5111 5112 // Generate a diagnostic where an uncovered argument is detected. 5113 if (UncoveredArg.hasUncoveredArg()) { 5114 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 5115 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 5116 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 5117 } 5118 5119 if (CT != SLCT_NotALiteral) 5120 // Literal format string found, check done! 5121 return CT == SLCT_CheckedLiteral; 5122 5123 // Strftime is particular as it always uses a single 'time' argument, 5124 // so it is safe to pass a non-literal string. 5125 if (Type == FST_Strftime) 5126 return false; 5127 5128 // Do not emit diag when the string param is a macro expansion and the 5129 // format is either NSString or CFString. This is a hack to prevent 5130 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 5131 // which are usually used in place of NS and CF string literals. 5132 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 5133 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 5134 return false; 5135 5136 // If there are no arguments specified, warn with -Wformat-security, otherwise 5137 // warn only with -Wformat-nonliteral. 5138 if (Args.size() == firstDataArg) { 5139 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 5140 << OrigFormatExpr->getSourceRange(); 5141 switch (Type) { 5142 default: 5143 break; 5144 case FST_Kprintf: 5145 case FST_FreeBSDKPrintf: 5146 case FST_Printf: 5147 Diag(FormatLoc, diag::note_format_security_fixit) 5148 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 5149 break; 5150 case FST_NSString: 5151 Diag(FormatLoc, diag::note_format_security_fixit) 5152 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 5153 break; 5154 } 5155 } else { 5156 Diag(FormatLoc, diag::warn_format_nonliteral) 5157 << OrigFormatExpr->getSourceRange(); 5158 } 5159 return false; 5160 } 5161 5162 namespace { 5163 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 5164 protected: 5165 Sema &S; 5166 const FormatStringLiteral *FExpr; 5167 const Expr *OrigFormatExpr; 5168 const Sema::FormatStringType FSType; 5169 const unsigned FirstDataArg; 5170 const unsigned NumDataArgs; 5171 const char *Beg; // Start of format string. 5172 const bool HasVAListArg; 5173 ArrayRef<const Expr *> Args; 5174 unsigned FormatIdx; 5175 llvm::SmallBitVector CoveredArgs; 5176 bool usesPositionalArgs; 5177 bool atFirstArg; 5178 bool inFunctionCall; 5179 Sema::VariadicCallType CallType; 5180 llvm::SmallBitVector &CheckedVarArgs; 5181 UncoveredArgHandler &UncoveredArg; 5182 5183 public: 5184 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 5185 const Expr *origFormatExpr, 5186 const Sema::FormatStringType type, unsigned firstDataArg, 5187 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5188 ArrayRef<const Expr *> Args, unsigned formatIdx, 5189 bool inFunctionCall, Sema::VariadicCallType callType, 5190 llvm::SmallBitVector &CheckedVarArgs, 5191 UncoveredArgHandler &UncoveredArg) 5192 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 5193 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 5194 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 5195 usesPositionalArgs(false), atFirstArg(true), 5196 inFunctionCall(inFunctionCall), CallType(callType), 5197 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 5198 CoveredArgs.resize(numDataArgs); 5199 CoveredArgs.reset(); 5200 } 5201 5202 void DoneProcessing(); 5203 5204 void HandleIncompleteSpecifier(const char *startSpecifier, 5205 unsigned specifierLen) override; 5206 5207 void HandleInvalidLengthModifier( 5208 const analyze_format_string::FormatSpecifier &FS, 5209 const analyze_format_string::ConversionSpecifier &CS, 5210 const char *startSpecifier, unsigned specifierLen, 5211 unsigned DiagID); 5212 5213 void HandleNonStandardLengthModifier( 5214 const analyze_format_string::FormatSpecifier &FS, 5215 const char *startSpecifier, unsigned specifierLen); 5216 5217 void HandleNonStandardConversionSpecifier( 5218 const analyze_format_string::ConversionSpecifier &CS, 5219 const char *startSpecifier, unsigned specifierLen); 5220 5221 void HandlePosition(const char *startPos, unsigned posLen) override; 5222 5223 void HandleInvalidPosition(const char *startSpecifier, 5224 unsigned specifierLen, 5225 analyze_format_string::PositionContext p) override; 5226 5227 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 5228 5229 void HandleNullChar(const char *nullCharacter) override; 5230 5231 template <typename Range> 5232 static void 5233 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 5234 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 5235 bool IsStringLocation, Range StringRange, 5236 ArrayRef<FixItHint> Fixit = None); 5237 5238 protected: 5239 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 5240 const char *startSpec, 5241 unsigned specifierLen, 5242 const char *csStart, unsigned csLen); 5243 5244 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 5245 const char *startSpec, 5246 unsigned specifierLen); 5247 5248 SourceRange getFormatStringRange(); 5249 CharSourceRange getSpecifierRange(const char *startSpecifier, 5250 unsigned specifierLen); 5251 SourceLocation getLocationOfByte(const char *x); 5252 5253 const Expr *getDataArg(unsigned i) const; 5254 5255 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 5256 const analyze_format_string::ConversionSpecifier &CS, 5257 const char *startSpecifier, unsigned specifierLen, 5258 unsigned argIndex); 5259 5260 template <typename Range> 5261 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5262 bool IsStringLocation, Range StringRange, 5263 ArrayRef<FixItHint> Fixit = None); 5264 }; 5265 } // end anonymous namespace 5266 5267 SourceRange CheckFormatHandler::getFormatStringRange() { 5268 return OrigFormatExpr->getSourceRange(); 5269 } 5270 5271 CharSourceRange CheckFormatHandler:: 5272 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 5273 SourceLocation Start = getLocationOfByte(startSpecifier); 5274 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 5275 5276 // Advance the end SourceLocation by one due to half-open ranges. 5277 End = End.getLocWithOffset(1); 5278 5279 return CharSourceRange::getCharRange(Start, End); 5280 } 5281 5282 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 5283 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 5284 S.getLangOpts(), S.Context.getTargetInfo()); 5285 } 5286 5287 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 5288 unsigned specifierLen){ 5289 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 5290 getLocationOfByte(startSpecifier), 5291 /*IsStringLocation*/true, 5292 getSpecifierRange(startSpecifier, specifierLen)); 5293 } 5294 5295 void CheckFormatHandler::HandleInvalidLengthModifier( 5296 const analyze_format_string::FormatSpecifier &FS, 5297 const analyze_format_string::ConversionSpecifier &CS, 5298 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 5299 using namespace analyze_format_string; 5300 5301 const LengthModifier &LM = FS.getLengthModifier(); 5302 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5303 5304 // See if we know how to fix this length modifier. 5305 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5306 if (FixedLM) { 5307 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5308 getLocationOfByte(LM.getStart()), 5309 /*IsStringLocation*/true, 5310 getSpecifierRange(startSpecifier, specifierLen)); 5311 5312 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5313 << FixedLM->toString() 5314 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5315 5316 } else { 5317 FixItHint Hint; 5318 if (DiagID == diag::warn_format_nonsensical_length) 5319 Hint = FixItHint::CreateRemoval(LMRange); 5320 5321 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5322 getLocationOfByte(LM.getStart()), 5323 /*IsStringLocation*/true, 5324 getSpecifierRange(startSpecifier, specifierLen), 5325 Hint); 5326 } 5327 } 5328 5329 void CheckFormatHandler::HandleNonStandardLengthModifier( 5330 const analyze_format_string::FormatSpecifier &FS, 5331 const char *startSpecifier, unsigned specifierLen) { 5332 using namespace analyze_format_string; 5333 5334 const LengthModifier &LM = FS.getLengthModifier(); 5335 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5336 5337 // See if we know how to fix this length modifier. 5338 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5339 if (FixedLM) { 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 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5347 << FixedLM->toString() 5348 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5349 5350 } else { 5351 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5352 << LM.toString() << 0, 5353 getLocationOfByte(LM.getStart()), 5354 /*IsStringLocation*/true, 5355 getSpecifierRange(startSpecifier, specifierLen)); 5356 } 5357 } 5358 5359 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5360 const analyze_format_string::ConversionSpecifier &CS, 5361 const char *startSpecifier, unsigned specifierLen) { 5362 using namespace analyze_format_string; 5363 5364 // See if we know how to fix this conversion specifier. 5365 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5366 if (FixedCS) { 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 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5374 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5375 << FixedCS->toString() 5376 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5377 } else { 5378 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5379 << CS.toString() << /*conversion specifier*/1, 5380 getLocationOfByte(CS.getStart()), 5381 /*IsStringLocation*/true, 5382 getSpecifierRange(startSpecifier, specifierLen)); 5383 } 5384 } 5385 5386 void CheckFormatHandler::HandlePosition(const char *startPos, 5387 unsigned posLen) { 5388 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5389 getLocationOfByte(startPos), 5390 /*IsStringLocation*/true, 5391 getSpecifierRange(startPos, posLen)); 5392 } 5393 5394 void 5395 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5396 analyze_format_string::PositionContext p) { 5397 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5398 << (unsigned) p, 5399 getLocationOfByte(startPos), /*IsStringLocation*/true, 5400 getSpecifierRange(startPos, posLen)); 5401 } 5402 5403 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5404 unsigned posLen) { 5405 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5406 getLocationOfByte(startPos), 5407 /*IsStringLocation*/true, 5408 getSpecifierRange(startPos, posLen)); 5409 } 5410 5411 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5412 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5413 // The presence of a null character is likely an error. 5414 EmitFormatDiagnostic( 5415 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5416 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5417 getFormatStringRange()); 5418 } 5419 } 5420 5421 // Note that this may return NULL if there was an error parsing or building 5422 // one of the argument expressions. 5423 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5424 return Args[FirstDataArg + i]; 5425 } 5426 5427 void CheckFormatHandler::DoneProcessing() { 5428 // Does the number of data arguments exceed the number of 5429 // format conversions in the format string? 5430 if (!HasVAListArg) { 5431 // Find any arguments that weren't covered. 5432 CoveredArgs.flip(); 5433 signed notCoveredArg = CoveredArgs.find_first(); 5434 if (notCoveredArg >= 0) { 5435 assert((unsigned)notCoveredArg < NumDataArgs); 5436 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 5437 } else { 5438 UncoveredArg.setAllCovered(); 5439 } 5440 } 5441 } 5442 5443 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 5444 const Expr *ArgExpr) { 5445 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 5446 "Invalid state"); 5447 5448 if (!ArgExpr) 5449 return; 5450 5451 SourceLocation Loc = ArgExpr->getLocStart(); 5452 5453 if (S.getSourceManager().isInSystemMacro(Loc)) 5454 return; 5455 5456 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 5457 for (auto E : DiagnosticExprs) 5458 PDiag << E->getSourceRange(); 5459 5460 CheckFormatHandler::EmitFormatDiagnostic( 5461 S, IsFunctionCall, DiagnosticExprs[0], 5462 PDiag, Loc, /*IsStringLocation*/false, 5463 DiagnosticExprs[0]->getSourceRange()); 5464 } 5465 5466 bool 5467 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 5468 SourceLocation Loc, 5469 const char *startSpec, 5470 unsigned specifierLen, 5471 const char *csStart, 5472 unsigned csLen) { 5473 bool keepGoing = true; 5474 if (argIndex < NumDataArgs) { 5475 // Consider the argument coverered, even though the specifier doesn't 5476 // make sense. 5477 CoveredArgs.set(argIndex); 5478 } 5479 else { 5480 // If argIndex exceeds the number of data arguments we 5481 // don't issue a warning because that is just a cascade of warnings (and 5482 // they may have intended '%%' anyway). We don't want to continue processing 5483 // the format string after this point, however, as we will like just get 5484 // gibberish when trying to match arguments. 5485 keepGoing = false; 5486 } 5487 5488 StringRef Specifier(csStart, csLen); 5489 5490 // If the specifier in non-printable, it could be the first byte of a UTF-8 5491 // sequence. In that case, print the UTF-8 code point. If not, print the byte 5492 // hex value. 5493 std::string CodePointStr; 5494 if (!llvm::sys::locale::isPrint(*csStart)) { 5495 llvm::UTF32 CodePoint; 5496 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 5497 const llvm::UTF8 *E = 5498 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 5499 llvm::ConversionResult Result = 5500 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 5501 5502 if (Result != llvm::conversionOK) { 5503 unsigned char FirstChar = *csStart; 5504 CodePoint = (llvm::UTF32)FirstChar; 5505 } 5506 5507 llvm::raw_string_ostream OS(CodePointStr); 5508 if (CodePoint < 256) 5509 OS << "\\x" << llvm::format("%02x", CodePoint); 5510 else if (CodePoint <= 0xFFFF) 5511 OS << "\\u" << llvm::format("%04x", CodePoint); 5512 else 5513 OS << "\\U" << llvm::format("%08x", CodePoint); 5514 OS.flush(); 5515 Specifier = CodePointStr; 5516 } 5517 5518 EmitFormatDiagnostic( 5519 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 5520 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 5521 5522 return keepGoing; 5523 } 5524 5525 void 5526 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 5527 const char *startSpec, 5528 unsigned specifierLen) { 5529 EmitFormatDiagnostic( 5530 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 5531 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 5532 } 5533 5534 bool 5535 CheckFormatHandler::CheckNumArgs( 5536 const analyze_format_string::FormatSpecifier &FS, 5537 const analyze_format_string::ConversionSpecifier &CS, 5538 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 5539 5540 if (argIndex >= NumDataArgs) { 5541 PartialDiagnostic PDiag = FS.usesPositionalArg() 5542 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 5543 << (argIndex+1) << NumDataArgs) 5544 : S.PDiag(diag::warn_printf_insufficient_data_args); 5545 EmitFormatDiagnostic( 5546 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 5547 getSpecifierRange(startSpecifier, specifierLen)); 5548 5549 // Since more arguments than conversion tokens are given, by extension 5550 // all arguments are covered, so mark this as so. 5551 UncoveredArg.setAllCovered(); 5552 return false; 5553 } 5554 return true; 5555 } 5556 5557 template<typename Range> 5558 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 5559 SourceLocation Loc, 5560 bool IsStringLocation, 5561 Range StringRange, 5562 ArrayRef<FixItHint> FixIt) { 5563 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 5564 Loc, IsStringLocation, StringRange, FixIt); 5565 } 5566 5567 /// \brief If the format string is not within the funcion call, emit a note 5568 /// so that the function call and string are in diagnostic messages. 5569 /// 5570 /// \param InFunctionCall if true, the format string is within the function 5571 /// call and only one diagnostic message will be produced. Otherwise, an 5572 /// extra note will be emitted pointing to location of the format string. 5573 /// 5574 /// \param ArgumentExpr the expression that is passed as the format string 5575 /// argument in the function call. Used for getting locations when two 5576 /// diagnostics are emitted. 5577 /// 5578 /// \param PDiag the callee should already have provided any strings for the 5579 /// diagnostic message. This function only adds locations and fixits 5580 /// to diagnostics. 5581 /// 5582 /// \param Loc primary location for diagnostic. If two diagnostics are 5583 /// required, one will be at Loc and a new SourceLocation will be created for 5584 /// the other one. 5585 /// 5586 /// \param IsStringLocation if true, Loc points to the format string should be 5587 /// used for the note. Otherwise, Loc points to the argument list and will 5588 /// be used with PDiag. 5589 /// 5590 /// \param StringRange some or all of the string to highlight. This is 5591 /// templated so it can accept either a CharSourceRange or a SourceRange. 5592 /// 5593 /// \param FixIt optional fix it hint for the format string. 5594 template <typename Range> 5595 void CheckFormatHandler::EmitFormatDiagnostic( 5596 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 5597 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 5598 Range StringRange, ArrayRef<FixItHint> FixIt) { 5599 if (InFunctionCall) { 5600 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 5601 D << StringRange; 5602 D << FixIt; 5603 } else { 5604 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 5605 << ArgumentExpr->getSourceRange(); 5606 5607 const Sema::SemaDiagnosticBuilder &Note = 5608 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 5609 diag::note_format_string_defined); 5610 5611 Note << StringRange; 5612 Note << FixIt; 5613 } 5614 } 5615 5616 //===--- CHECK: Printf format string checking ------------------------------===// 5617 5618 namespace { 5619 class CheckPrintfHandler : public CheckFormatHandler { 5620 public: 5621 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 5622 const Expr *origFormatExpr, 5623 const Sema::FormatStringType type, unsigned firstDataArg, 5624 unsigned numDataArgs, bool isObjC, const char *beg, 5625 bool hasVAListArg, ArrayRef<const Expr *> Args, 5626 unsigned formatIdx, bool inFunctionCall, 5627 Sema::VariadicCallType CallType, 5628 llvm::SmallBitVector &CheckedVarArgs, 5629 UncoveredArgHandler &UncoveredArg) 5630 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 5631 numDataArgs, beg, hasVAListArg, Args, formatIdx, 5632 inFunctionCall, CallType, CheckedVarArgs, 5633 UncoveredArg) {} 5634 5635 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 5636 5637 /// Returns true if '%@' specifiers are allowed in the format string. 5638 bool allowsObjCArg() const { 5639 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 5640 FSType == Sema::FST_OSTrace; 5641 } 5642 5643 bool HandleInvalidPrintfConversionSpecifier( 5644 const analyze_printf::PrintfSpecifier &FS, 5645 const char *startSpecifier, 5646 unsigned specifierLen) override; 5647 5648 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 5649 const char *startSpecifier, 5650 unsigned specifierLen) override; 5651 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5652 const char *StartSpecifier, 5653 unsigned SpecifierLen, 5654 const Expr *E); 5655 5656 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 5657 const char *startSpecifier, unsigned specifierLen); 5658 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 5659 const analyze_printf::OptionalAmount &Amt, 5660 unsigned type, 5661 const char *startSpecifier, unsigned specifierLen); 5662 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5663 const analyze_printf::OptionalFlag &flag, 5664 const char *startSpecifier, unsigned specifierLen); 5665 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 5666 const analyze_printf::OptionalFlag &ignoredFlag, 5667 const analyze_printf::OptionalFlag &flag, 5668 const char *startSpecifier, unsigned specifierLen); 5669 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 5670 const Expr *E); 5671 5672 void HandleEmptyObjCModifierFlag(const char *startFlag, 5673 unsigned flagLen) override; 5674 5675 void HandleInvalidObjCModifierFlag(const char *startFlag, 5676 unsigned flagLen) override; 5677 5678 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 5679 const char *flagsEnd, 5680 const char *conversionPosition) 5681 override; 5682 }; 5683 } // end anonymous namespace 5684 5685 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 5686 const analyze_printf::PrintfSpecifier &FS, 5687 const char *startSpecifier, 5688 unsigned specifierLen) { 5689 const analyze_printf::PrintfConversionSpecifier &CS = 5690 FS.getConversionSpecifier(); 5691 5692 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5693 getLocationOfByte(CS.getStart()), 5694 startSpecifier, specifierLen, 5695 CS.getStart(), CS.getLength()); 5696 } 5697 5698 bool CheckPrintfHandler::HandleAmount( 5699 const analyze_format_string::OptionalAmount &Amt, 5700 unsigned k, const char *startSpecifier, 5701 unsigned specifierLen) { 5702 if (Amt.hasDataArgument()) { 5703 if (!HasVAListArg) { 5704 unsigned argIndex = Amt.getArgIndex(); 5705 if (argIndex >= NumDataArgs) { 5706 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 5707 << k, 5708 getLocationOfByte(Amt.getStart()), 5709 /*IsStringLocation*/true, 5710 getSpecifierRange(startSpecifier, specifierLen)); 5711 // Don't do any more checking. We will just emit 5712 // spurious errors. 5713 return false; 5714 } 5715 5716 // Type check the data argument. It should be an 'int'. 5717 // Although not in conformance with C99, we also allow the argument to be 5718 // an 'unsigned int' as that is a reasonably safe case. GCC also 5719 // doesn't emit a warning for that case. 5720 CoveredArgs.set(argIndex); 5721 const Expr *Arg = getDataArg(argIndex); 5722 if (!Arg) 5723 return false; 5724 5725 QualType T = Arg->getType(); 5726 5727 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 5728 assert(AT.isValid()); 5729 5730 if (!AT.matchesType(S.Context, T)) { 5731 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 5732 << k << AT.getRepresentativeTypeName(S.Context) 5733 << T << Arg->getSourceRange(), 5734 getLocationOfByte(Amt.getStart()), 5735 /*IsStringLocation*/true, 5736 getSpecifierRange(startSpecifier, specifierLen)); 5737 // Don't do any more checking. We will just emit 5738 // spurious errors. 5739 return false; 5740 } 5741 } 5742 } 5743 return true; 5744 } 5745 5746 void CheckPrintfHandler::HandleInvalidAmount( 5747 const analyze_printf::PrintfSpecifier &FS, 5748 const analyze_printf::OptionalAmount &Amt, 5749 unsigned type, 5750 const char *startSpecifier, 5751 unsigned specifierLen) { 5752 const analyze_printf::PrintfConversionSpecifier &CS = 5753 FS.getConversionSpecifier(); 5754 5755 FixItHint fixit = 5756 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 5757 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 5758 Amt.getConstantLength())) 5759 : FixItHint(); 5760 5761 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 5762 << type << CS.toString(), 5763 getLocationOfByte(Amt.getStart()), 5764 /*IsStringLocation*/true, 5765 getSpecifierRange(startSpecifier, specifierLen), 5766 fixit); 5767 } 5768 5769 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5770 const analyze_printf::OptionalFlag &flag, 5771 const char *startSpecifier, 5772 unsigned specifierLen) { 5773 // Warn about pointless flag with a fixit removal. 5774 const analyze_printf::PrintfConversionSpecifier &CS = 5775 FS.getConversionSpecifier(); 5776 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 5777 << flag.toString() << CS.toString(), 5778 getLocationOfByte(flag.getPosition()), 5779 /*IsStringLocation*/true, 5780 getSpecifierRange(startSpecifier, specifierLen), 5781 FixItHint::CreateRemoval( 5782 getSpecifierRange(flag.getPosition(), 1))); 5783 } 5784 5785 void CheckPrintfHandler::HandleIgnoredFlag( 5786 const analyze_printf::PrintfSpecifier &FS, 5787 const analyze_printf::OptionalFlag &ignoredFlag, 5788 const analyze_printf::OptionalFlag &flag, 5789 const char *startSpecifier, 5790 unsigned specifierLen) { 5791 // Warn about ignored flag with a fixit removal. 5792 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 5793 << ignoredFlag.toString() << flag.toString(), 5794 getLocationOfByte(ignoredFlag.getPosition()), 5795 /*IsStringLocation*/true, 5796 getSpecifierRange(startSpecifier, specifierLen), 5797 FixItHint::CreateRemoval( 5798 getSpecifierRange(ignoredFlag.getPosition(), 1))); 5799 } 5800 5801 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5802 // bool IsStringLocation, Range StringRange, 5803 // ArrayRef<FixItHint> Fixit = None); 5804 5805 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 5806 unsigned flagLen) { 5807 // Warn about an empty flag. 5808 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 5809 getLocationOfByte(startFlag), 5810 /*IsStringLocation*/true, 5811 getSpecifierRange(startFlag, flagLen)); 5812 } 5813 5814 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 5815 unsigned flagLen) { 5816 // Warn about an invalid flag. 5817 auto Range = getSpecifierRange(startFlag, flagLen); 5818 StringRef flag(startFlag, flagLen); 5819 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 5820 getLocationOfByte(startFlag), 5821 /*IsStringLocation*/true, 5822 Range, FixItHint::CreateRemoval(Range)); 5823 } 5824 5825 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 5826 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 5827 // Warn about using '[...]' without a '@' conversion. 5828 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 5829 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 5830 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 5831 getLocationOfByte(conversionPosition), 5832 /*IsStringLocation*/true, 5833 Range, FixItHint::CreateRemoval(Range)); 5834 } 5835 5836 // Determines if the specified is a C++ class or struct containing 5837 // a member with the specified name and kind (e.g. a CXXMethodDecl named 5838 // "c_str()"). 5839 template<typename MemberKind> 5840 static llvm::SmallPtrSet<MemberKind*, 1> 5841 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 5842 const RecordType *RT = Ty->getAs<RecordType>(); 5843 llvm::SmallPtrSet<MemberKind*, 1> Results; 5844 5845 if (!RT) 5846 return Results; 5847 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 5848 if (!RD || !RD->getDefinition()) 5849 return Results; 5850 5851 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 5852 Sema::LookupMemberName); 5853 R.suppressDiagnostics(); 5854 5855 // We just need to include all members of the right kind turned up by the 5856 // filter, at this point. 5857 if (S.LookupQualifiedName(R, RT->getDecl())) 5858 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 5859 NamedDecl *decl = (*I)->getUnderlyingDecl(); 5860 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 5861 Results.insert(FK); 5862 } 5863 return Results; 5864 } 5865 5866 /// Check if we could call '.c_str()' on an object. 5867 /// 5868 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 5869 /// allow the call, or if it would be ambiguous). 5870 bool Sema::hasCStrMethod(const Expr *E) { 5871 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5872 MethodSet Results = 5873 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 5874 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5875 MI != ME; ++MI) 5876 if ((*MI)->getMinRequiredArguments() == 0) 5877 return true; 5878 return false; 5879 } 5880 5881 // Check if a (w)string was passed when a (w)char* was needed, and offer a 5882 // better diagnostic if so. AT is assumed to be valid. 5883 // Returns true when a c_str() conversion method is found. 5884 bool CheckPrintfHandler::checkForCStrMembers( 5885 const analyze_printf::ArgType &AT, const Expr *E) { 5886 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5887 5888 MethodSet Results = 5889 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 5890 5891 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5892 MI != ME; ++MI) { 5893 const CXXMethodDecl *Method = *MI; 5894 if (Method->getMinRequiredArguments() == 0 && 5895 AT.matchesType(S.Context, Method->getReturnType())) { 5896 // FIXME: Suggest parens if the expression needs them. 5897 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 5898 S.Diag(E->getLocStart(), diag::note_printf_c_str) 5899 << "c_str()" 5900 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 5901 return true; 5902 } 5903 } 5904 5905 return false; 5906 } 5907 5908 bool 5909 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 5910 &FS, 5911 const char *startSpecifier, 5912 unsigned specifierLen) { 5913 using namespace analyze_format_string; 5914 using namespace analyze_printf; 5915 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 5916 5917 if (FS.consumesDataArgument()) { 5918 if (atFirstArg) { 5919 atFirstArg = false; 5920 usesPositionalArgs = FS.usesPositionalArg(); 5921 } 5922 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5923 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5924 startSpecifier, specifierLen); 5925 return false; 5926 } 5927 } 5928 5929 // First check if the field width, precision, and conversion specifier 5930 // have matching data arguments. 5931 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 5932 startSpecifier, specifierLen)) { 5933 return false; 5934 } 5935 5936 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 5937 startSpecifier, specifierLen)) { 5938 return false; 5939 } 5940 5941 if (!CS.consumesDataArgument()) { 5942 // FIXME: Technically specifying a precision or field width here 5943 // makes no sense. Worth issuing a warning at some point. 5944 return true; 5945 } 5946 5947 // Consume the argument. 5948 unsigned argIndex = FS.getArgIndex(); 5949 if (argIndex < NumDataArgs) { 5950 // The check to see if the argIndex is valid will come later. 5951 // We set the bit here because we may exit early from this 5952 // function if we encounter some other error. 5953 CoveredArgs.set(argIndex); 5954 } 5955 5956 // FreeBSD kernel extensions. 5957 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 5958 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 5959 // We need at least two arguments. 5960 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 5961 return false; 5962 5963 // Claim the second argument. 5964 CoveredArgs.set(argIndex + 1); 5965 5966 // Type check the first argument (int for %b, pointer for %D) 5967 const Expr *Ex = getDataArg(argIndex); 5968 const analyze_printf::ArgType &AT = 5969 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 5970 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 5971 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 5972 EmitFormatDiagnostic( 5973 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5974 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 5975 << false << Ex->getSourceRange(), 5976 Ex->getLocStart(), /*IsStringLocation*/false, 5977 getSpecifierRange(startSpecifier, specifierLen)); 5978 5979 // Type check the second argument (char * for both %b and %D) 5980 Ex = getDataArg(argIndex + 1); 5981 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 5982 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 5983 EmitFormatDiagnostic( 5984 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5985 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 5986 << false << Ex->getSourceRange(), 5987 Ex->getLocStart(), /*IsStringLocation*/false, 5988 getSpecifierRange(startSpecifier, specifierLen)); 5989 5990 return true; 5991 } 5992 5993 // Check for using an Objective-C specific conversion specifier 5994 // in a non-ObjC literal. 5995 if (!allowsObjCArg() && CS.isObjCArg()) { 5996 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5997 specifierLen); 5998 } 5999 6000 // %P can only be used with os_log. 6001 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 6002 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6003 specifierLen); 6004 } 6005 6006 // %n is not allowed with os_log. 6007 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 6008 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 6009 getLocationOfByte(CS.getStart()), 6010 /*IsStringLocation*/ false, 6011 getSpecifierRange(startSpecifier, specifierLen)); 6012 6013 return true; 6014 } 6015 6016 // Only scalars are allowed for os_trace. 6017 if (FSType == Sema::FST_OSTrace && 6018 (CS.getKind() == ConversionSpecifier::PArg || 6019 CS.getKind() == ConversionSpecifier::sArg || 6020 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 6021 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6022 specifierLen); 6023 } 6024 6025 // Check for use of public/private annotation outside of os_log(). 6026 if (FSType != Sema::FST_OSLog) { 6027 if (FS.isPublic().isSet()) { 6028 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6029 << "public", 6030 getLocationOfByte(FS.isPublic().getPosition()), 6031 /*IsStringLocation*/ false, 6032 getSpecifierRange(startSpecifier, specifierLen)); 6033 } 6034 if (FS.isPrivate().isSet()) { 6035 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6036 << "private", 6037 getLocationOfByte(FS.isPrivate().getPosition()), 6038 /*IsStringLocation*/ false, 6039 getSpecifierRange(startSpecifier, specifierLen)); 6040 } 6041 } 6042 6043 // Check for invalid use of field width 6044 if (!FS.hasValidFieldWidth()) { 6045 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 6046 startSpecifier, specifierLen); 6047 } 6048 6049 // Check for invalid use of precision 6050 if (!FS.hasValidPrecision()) { 6051 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 6052 startSpecifier, specifierLen); 6053 } 6054 6055 // Precision is mandatory for %P specifier. 6056 if (CS.getKind() == ConversionSpecifier::PArg && 6057 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 6058 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 6059 getLocationOfByte(startSpecifier), 6060 /*IsStringLocation*/ false, 6061 getSpecifierRange(startSpecifier, specifierLen)); 6062 } 6063 6064 // Check each flag does not conflict with any other component. 6065 if (!FS.hasValidThousandsGroupingPrefix()) 6066 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 6067 if (!FS.hasValidLeadingZeros()) 6068 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 6069 if (!FS.hasValidPlusPrefix()) 6070 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 6071 if (!FS.hasValidSpacePrefix()) 6072 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 6073 if (!FS.hasValidAlternativeForm()) 6074 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 6075 if (!FS.hasValidLeftJustified()) 6076 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 6077 6078 // Check that flags are not ignored by another flag 6079 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 6080 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 6081 startSpecifier, specifierLen); 6082 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 6083 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 6084 startSpecifier, specifierLen); 6085 6086 // Check the length modifier is valid with the given conversion specifier. 6087 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6088 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6089 diag::warn_format_nonsensical_length); 6090 else if (!FS.hasStandardLengthModifier()) 6091 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6092 else if (!FS.hasStandardLengthConversionCombination()) 6093 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6094 diag::warn_format_non_standard_conversion_spec); 6095 6096 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6097 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6098 6099 // The remaining checks depend on the data arguments. 6100 if (HasVAListArg) 6101 return true; 6102 6103 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6104 return false; 6105 6106 const Expr *Arg = getDataArg(argIndex); 6107 if (!Arg) 6108 return true; 6109 6110 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 6111 } 6112 6113 static bool requiresParensToAddCast(const Expr *E) { 6114 // FIXME: We should have a general way to reason about operator 6115 // precedence and whether parens are actually needed here. 6116 // Take care of a few common cases where they aren't. 6117 const Expr *Inside = E->IgnoreImpCasts(); 6118 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 6119 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 6120 6121 switch (Inside->getStmtClass()) { 6122 case Stmt::ArraySubscriptExprClass: 6123 case Stmt::CallExprClass: 6124 case Stmt::CharacterLiteralClass: 6125 case Stmt::CXXBoolLiteralExprClass: 6126 case Stmt::DeclRefExprClass: 6127 case Stmt::FloatingLiteralClass: 6128 case Stmt::IntegerLiteralClass: 6129 case Stmt::MemberExprClass: 6130 case Stmt::ObjCArrayLiteralClass: 6131 case Stmt::ObjCBoolLiteralExprClass: 6132 case Stmt::ObjCBoxedExprClass: 6133 case Stmt::ObjCDictionaryLiteralClass: 6134 case Stmt::ObjCEncodeExprClass: 6135 case Stmt::ObjCIvarRefExprClass: 6136 case Stmt::ObjCMessageExprClass: 6137 case Stmt::ObjCPropertyRefExprClass: 6138 case Stmt::ObjCStringLiteralClass: 6139 case Stmt::ObjCSubscriptRefExprClass: 6140 case Stmt::ParenExprClass: 6141 case Stmt::StringLiteralClass: 6142 case Stmt::UnaryOperatorClass: 6143 return false; 6144 default: 6145 return true; 6146 } 6147 } 6148 6149 static std::pair<QualType, StringRef> 6150 shouldNotPrintDirectly(const ASTContext &Context, 6151 QualType IntendedTy, 6152 const Expr *E) { 6153 // Use a 'while' to peel off layers of typedefs. 6154 QualType TyTy = IntendedTy; 6155 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 6156 StringRef Name = UserTy->getDecl()->getName(); 6157 QualType CastTy = llvm::StringSwitch<QualType>(Name) 6158 .Case("CFIndex", Context.LongTy) 6159 .Case("NSInteger", Context.LongTy) 6160 .Case("NSUInteger", Context.UnsignedLongTy) 6161 .Case("SInt32", Context.IntTy) 6162 .Case("UInt32", Context.UnsignedIntTy) 6163 .Default(QualType()); 6164 6165 if (!CastTy.isNull()) 6166 return std::make_pair(CastTy, Name); 6167 6168 TyTy = UserTy->desugar(); 6169 } 6170 6171 // Strip parens if necessary. 6172 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 6173 return shouldNotPrintDirectly(Context, 6174 PE->getSubExpr()->getType(), 6175 PE->getSubExpr()); 6176 6177 // If this is a conditional expression, then its result type is constructed 6178 // via usual arithmetic conversions and thus there might be no necessary 6179 // typedef sugar there. Recurse to operands to check for NSInteger & 6180 // Co. usage condition. 6181 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6182 QualType TrueTy, FalseTy; 6183 StringRef TrueName, FalseName; 6184 6185 std::tie(TrueTy, TrueName) = 6186 shouldNotPrintDirectly(Context, 6187 CO->getTrueExpr()->getType(), 6188 CO->getTrueExpr()); 6189 std::tie(FalseTy, FalseName) = 6190 shouldNotPrintDirectly(Context, 6191 CO->getFalseExpr()->getType(), 6192 CO->getFalseExpr()); 6193 6194 if (TrueTy == FalseTy) 6195 return std::make_pair(TrueTy, TrueName); 6196 else if (TrueTy.isNull()) 6197 return std::make_pair(FalseTy, FalseName); 6198 else if (FalseTy.isNull()) 6199 return std::make_pair(TrueTy, TrueName); 6200 } 6201 6202 return std::make_pair(QualType(), StringRef()); 6203 } 6204 6205 bool 6206 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6207 const char *StartSpecifier, 6208 unsigned SpecifierLen, 6209 const Expr *E) { 6210 using namespace analyze_format_string; 6211 using namespace analyze_printf; 6212 // Now type check the data expression that matches the 6213 // format specifier. 6214 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 6215 if (!AT.isValid()) 6216 return true; 6217 6218 QualType ExprTy = E->getType(); 6219 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 6220 ExprTy = TET->getUnderlyingExpr()->getType(); 6221 } 6222 6223 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 6224 6225 if (match == analyze_printf::ArgType::Match) { 6226 return true; 6227 } 6228 6229 // Look through argument promotions for our error message's reported type. 6230 // This includes the integral and floating promotions, but excludes array 6231 // and function pointer decay; seeing that an argument intended to be a 6232 // string has type 'char [6]' is probably more confusing than 'char *'. 6233 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6234 if (ICE->getCastKind() == CK_IntegralCast || 6235 ICE->getCastKind() == CK_FloatingCast) { 6236 E = ICE->getSubExpr(); 6237 ExprTy = E->getType(); 6238 6239 // Check if we didn't match because of an implicit cast from a 'char' 6240 // or 'short' to an 'int'. This is done because printf is a varargs 6241 // function. 6242 if (ICE->getType() == S.Context.IntTy || 6243 ICE->getType() == S.Context.UnsignedIntTy) { 6244 // All further checking is done on the subexpression. 6245 if (AT.matchesType(S.Context, ExprTy)) 6246 return true; 6247 } 6248 } 6249 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 6250 // Special case for 'a', which has type 'int' in C. 6251 // Note, however, that we do /not/ want to treat multibyte constants like 6252 // 'MooV' as characters! This form is deprecated but still exists. 6253 if (ExprTy == S.Context.IntTy) 6254 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 6255 ExprTy = S.Context.CharTy; 6256 } 6257 6258 // Look through enums to their underlying type. 6259 bool IsEnum = false; 6260 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 6261 ExprTy = EnumTy->getDecl()->getIntegerType(); 6262 IsEnum = true; 6263 } 6264 6265 // %C in an Objective-C context prints a unichar, not a wchar_t. 6266 // If the argument is an integer of some kind, believe the %C and suggest 6267 // a cast instead of changing the conversion specifier. 6268 QualType IntendedTy = ExprTy; 6269 if (isObjCContext() && 6270 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 6271 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 6272 !ExprTy->isCharType()) { 6273 // 'unichar' is defined as a typedef of unsigned short, but we should 6274 // prefer using the typedef if it is visible. 6275 IntendedTy = S.Context.UnsignedShortTy; 6276 6277 // While we are here, check if the value is an IntegerLiteral that happens 6278 // to be within the valid range. 6279 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 6280 const llvm::APInt &V = IL->getValue(); 6281 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 6282 return true; 6283 } 6284 6285 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 6286 Sema::LookupOrdinaryName); 6287 if (S.LookupName(Result, S.getCurScope())) { 6288 NamedDecl *ND = Result.getFoundDecl(); 6289 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 6290 if (TD->getUnderlyingType() == IntendedTy) 6291 IntendedTy = S.Context.getTypedefType(TD); 6292 } 6293 } 6294 } 6295 6296 // Special-case some of Darwin's platform-independence types by suggesting 6297 // casts to primitive types that are known to be large enough. 6298 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 6299 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 6300 QualType CastTy; 6301 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 6302 if (!CastTy.isNull()) { 6303 IntendedTy = CastTy; 6304 ShouldNotPrintDirectly = true; 6305 } 6306 } 6307 6308 // We may be able to offer a FixItHint if it is a supported type. 6309 PrintfSpecifier fixedFS = FS; 6310 bool success = 6311 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 6312 6313 if (success) { 6314 // Get the fix string from the fixed format specifier 6315 SmallString<16> buf; 6316 llvm::raw_svector_ostream os(buf); 6317 fixedFS.toString(os); 6318 6319 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 6320 6321 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 6322 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6323 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6324 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6325 } 6326 // In this case, the specifier is wrong and should be changed to match 6327 // the argument. 6328 EmitFormatDiagnostic(S.PDiag(diag) 6329 << AT.getRepresentativeTypeName(S.Context) 6330 << IntendedTy << IsEnum << E->getSourceRange(), 6331 E->getLocStart(), 6332 /*IsStringLocation*/ false, SpecRange, 6333 FixItHint::CreateReplacement(SpecRange, os.str())); 6334 } else { 6335 // The canonical type for formatting this value is different from the 6336 // actual type of the expression. (This occurs, for example, with Darwin's 6337 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 6338 // should be printed as 'long' for 64-bit compatibility.) 6339 // Rather than emitting a normal format/argument mismatch, we want to 6340 // add a cast to the recommended type (and correct the format string 6341 // if necessary). 6342 SmallString<16> CastBuf; 6343 llvm::raw_svector_ostream CastFix(CastBuf); 6344 CastFix << "("; 6345 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 6346 CastFix << ")"; 6347 6348 SmallVector<FixItHint,4> Hints; 6349 if (!AT.matchesType(S.Context, IntendedTy)) 6350 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 6351 6352 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 6353 // If there's already a cast present, just replace it. 6354 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 6355 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 6356 6357 } else if (!requiresParensToAddCast(E)) { 6358 // If the expression has high enough precedence, 6359 // just write the C-style cast. 6360 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6361 CastFix.str())); 6362 } else { 6363 // Otherwise, add parens around the expression as well as the cast. 6364 CastFix << "("; 6365 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6366 CastFix.str())); 6367 6368 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6369 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6370 } 6371 6372 if (ShouldNotPrintDirectly) { 6373 // The expression has a type that should not be printed directly. 6374 // We extract the name from the typedef because we don't want to show 6375 // the underlying type in the diagnostic. 6376 StringRef Name; 6377 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6378 Name = TypedefTy->getDecl()->getName(); 6379 else 6380 Name = CastTyName; 6381 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6382 << Name << IntendedTy << IsEnum 6383 << E->getSourceRange(), 6384 E->getLocStart(), /*IsStringLocation=*/false, 6385 SpecRange, Hints); 6386 } else { 6387 // In this case, the expression could be printed using a different 6388 // specifier, but we've decided that the specifier is probably correct 6389 // and we should cast instead. Just use the normal warning message. 6390 EmitFormatDiagnostic( 6391 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6392 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6393 << E->getSourceRange(), 6394 E->getLocStart(), /*IsStringLocation*/false, 6395 SpecRange, Hints); 6396 } 6397 } 6398 } else { 6399 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6400 SpecifierLen); 6401 // Since the warning for passing non-POD types to variadic functions 6402 // was deferred until now, we emit a warning for non-POD 6403 // arguments here. 6404 switch (S.isValidVarArgType(ExprTy)) { 6405 case Sema::VAK_Valid: 6406 case Sema::VAK_ValidInCXX11: { 6407 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6408 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6409 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6410 } 6411 6412 EmitFormatDiagnostic( 6413 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6414 << IsEnum << CSR << E->getSourceRange(), 6415 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6416 break; 6417 } 6418 case Sema::VAK_Undefined: 6419 case Sema::VAK_MSVCUndefined: 6420 EmitFormatDiagnostic( 6421 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6422 << S.getLangOpts().CPlusPlus11 6423 << ExprTy 6424 << CallType 6425 << AT.getRepresentativeTypeName(S.Context) 6426 << CSR 6427 << E->getSourceRange(), 6428 E->getLocStart(), /*IsStringLocation*/false, CSR); 6429 checkForCStrMembers(AT, E); 6430 break; 6431 6432 case Sema::VAK_Invalid: 6433 if (ExprTy->isObjCObjectType()) 6434 EmitFormatDiagnostic( 6435 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 6436 << S.getLangOpts().CPlusPlus11 6437 << ExprTy 6438 << CallType 6439 << AT.getRepresentativeTypeName(S.Context) 6440 << CSR 6441 << E->getSourceRange(), 6442 E->getLocStart(), /*IsStringLocation*/false, CSR); 6443 else 6444 // FIXME: If this is an initializer list, suggest removing the braces 6445 // or inserting a cast to the target type. 6446 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 6447 << isa<InitListExpr>(E) << ExprTy << CallType 6448 << AT.getRepresentativeTypeName(S.Context) 6449 << E->getSourceRange(); 6450 break; 6451 } 6452 6453 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 6454 "format string specifier index out of range"); 6455 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 6456 } 6457 6458 return true; 6459 } 6460 6461 //===--- CHECK: Scanf format string checking ------------------------------===// 6462 6463 namespace { 6464 class CheckScanfHandler : public CheckFormatHandler { 6465 public: 6466 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 6467 const Expr *origFormatExpr, Sema::FormatStringType type, 6468 unsigned firstDataArg, unsigned numDataArgs, 6469 const char *beg, bool hasVAListArg, 6470 ArrayRef<const Expr *> Args, unsigned formatIdx, 6471 bool inFunctionCall, Sema::VariadicCallType CallType, 6472 llvm::SmallBitVector &CheckedVarArgs, 6473 UncoveredArgHandler &UncoveredArg) 6474 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6475 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6476 inFunctionCall, CallType, CheckedVarArgs, 6477 UncoveredArg) {} 6478 6479 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 6480 const char *startSpecifier, 6481 unsigned specifierLen) override; 6482 6483 bool HandleInvalidScanfConversionSpecifier( 6484 const analyze_scanf::ScanfSpecifier &FS, 6485 const char *startSpecifier, 6486 unsigned specifierLen) override; 6487 6488 void HandleIncompleteScanList(const char *start, const char *end) override; 6489 }; 6490 } // end anonymous namespace 6491 6492 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 6493 const char *end) { 6494 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 6495 getLocationOfByte(end), /*IsStringLocation*/true, 6496 getSpecifierRange(start, end - start)); 6497 } 6498 6499 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 6500 const analyze_scanf::ScanfSpecifier &FS, 6501 const char *startSpecifier, 6502 unsigned specifierLen) { 6503 6504 const analyze_scanf::ScanfConversionSpecifier &CS = 6505 FS.getConversionSpecifier(); 6506 6507 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6508 getLocationOfByte(CS.getStart()), 6509 startSpecifier, specifierLen, 6510 CS.getStart(), CS.getLength()); 6511 } 6512 6513 bool CheckScanfHandler::HandleScanfSpecifier( 6514 const analyze_scanf::ScanfSpecifier &FS, 6515 const char *startSpecifier, 6516 unsigned specifierLen) { 6517 using namespace analyze_scanf; 6518 using namespace analyze_format_string; 6519 6520 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 6521 6522 // Handle case where '%' and '*' don't consume an argument. These shouldn't 6523 // be used to decide if we are using positional arguments consistently. 6524 if (FS.consumesDataArgument()) { 6525 if (atFirstArg) { 6526 atFirstArg = false; 6527 usesPositionalArgs = FS.usesPositionalArg(); 6528 } 6529 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6530 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6531 startSpecifier, specifierLen); 6532 return false; 6533 } 6534 } 6535 6536 // Check if the field with is non-zero. 6537 const OptionalAmount &Amt = FS.getFieldWidth(); 6538 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 6539 if (Amt.getConstantAmount() == 0) { 6540 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 6541 Amt.getConstantLength()); 6542 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 6543 getLocationOfByte(Amt.getStart()), 6544 /*IsStringLocation*/true, R, 6545 FixItHint::CreateRemoval(R)); 6546 } 6547 } 6548 6549 if (!FS.consumesDataArgument()) { 6550 // FIXME: Technically specifying a precision or field width here 6551 // makes no sense. Worth issuing a warning at some point. 6552 return true; 6553 } 6554 6555 // Consume the argument. 6556 unsigned argIndex = FS.getArgIndex(); 6557 if (argIndex < NumDataArgs) { 6558 // The check to see if the argIndex is valid will come later. 6559 // We set the bit here because we may exit early from this 6560 // function if we encounter some other error. 6561 CoveredArgs.set(argIndex); 6562 } 6563 6564 // Check the length modifier is valid with the given conversion specifier. 6565 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6566 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6567 diag::warn_format_nonsensical_length); 6568 else if (!FS.hasStandardLengthModifier()) 6569 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6570 else if (!FS.hasStandardLengthConversionCombination()) 6571 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6572 diag::warn_format_non_standard_conversion_spec); 6573 6574 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6575 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6576 6577 // The remaining checks depend on the data arguments. 6578 if (HasVAListArg) 6579 return true; 6580 6581 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6582 return false; 6583 6584 // Check that the argument type matches the format specifier. 6585 const Expr *Ex = getDataArg(argIndex); 6586 if (!Ex) 6587 return true; 6588 6589 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 6590 6591 if (!AT.isValid()) { 6592 return true; 6593 } 6594 6595 analyze_format_string::ArgType::MatchKind match = 6596 AT.matchesType(S.Context, Ex->getType()); 6597 if (match == analyze_format_string::ArgType::Match) { 6598 return true; 6599 } 6600 6601 ScanfSpecifier fixedFS = FS; 6602 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 6603 S.getLangOpts(), S.Context); 6604 6605 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6606 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6607 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6608 } 6609 6610 if (success) { 6611 // Get the fix string from the fixed format specifier. 6612 SmallString<128> buf; 6613 llvm::raw_svector_ostream os(buf); 6614 fixedFS.toString(os); 6615 6616 EmitFormatDiagnostic( 6617 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 6618 << Ex->getType() << false << Ex->getSourceRange(), 6619 Ex->getLocStart(), 6620 /*IsStringLocation*/ false, 6621 getSpecifierRange(startSpecifier, specifierLen), 6622 FixItHint::CreateReplacement( 6623 getSpecifierRange(startSpecifier, specifierLen), os.str())); 6624 } else { 6625 EmitFormatDiagnostic(S.PDiag(diag) 6626 << AT.getRepresentativeTypeName(S.Context) 6627 << Ex->getType() << false << Ex->getSourceRange(), 6628 Ex->getLocStart(), 6629 /*IsStringLocation*/ false, 6630 getSpecifierRange(startSpecifier, specifierLen)); 6631 } 6632 6633 return true; 6634 } 6635 6636 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6637 const Expr *OrigFormatExpr, 6638 ArrayRef<const Expr *> Args, 6639 bool HasVAListArg, unsigned format_idx, 6640 unsigned firstDataArg, 6641 Sema::FormatStringType Type, 6642 bool inFunctionCall, 6643 Sema::VariadicCallType CallType, 6644 llvm::SmallBitVector &CheckedVarArgs, 6645 UncoveredArgHandler &UncoveredArg) { 6646 // CHECK: is the format string a wide literal? 6647 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 6648 CheckFormatHandler::EmitFormatDiagnostic( 6649 S, inFunctionCall, Args[format_idx], 6650 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 6651 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6652 return; 6653 } 6654 6655 // Str - The format string. NOTE: this is NOT null-terminated! 6656 StringRef StrRef = FExpr->getString(); 6657 const char *Str = StrRef.data(); 6658 // Account for cases where the string literal is truncated in a declaration. 6659 const ConstantArrayType *T = 6660 S.Context.getAsConstantArrayType(FExpr->getType()); 6661 assert(T && "String literal not of constant array type!"); 6662 size_t TypeSize = T->getSize().getZExtValue(); 6663 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6664 const unsigned numDataArgs = Args.size() - firstDataArg; 6665 6666 // Emit a warning if the string literal is truncated and does not contain an 6667 // embedded null character. 6668 if (TypeSize <= StrRef.size() && 6669 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 6670 CheckFormatHandler::EmitFormatDiagnostic( 6671 S, inFunctionCall, Args[format_idx], 6672 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 6673 FExpr->getLocStart(), 6674 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 6675 return; 6676 } 6677 6678 // CHECK: empty format string? 6679 if (StrLen == 0 && numDataArgs > 0) { 6680 CheckFormatHandler::EmitFormatDiagnostic( 6681 S, inFunctionCall, Args[format_idx], 6682 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 6683 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6684 return; 6685 } 6686 6687 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 6688 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 6689 Type == Sema::FST_OSTrace) { 6690 CheckPrintfHandler H( 6691 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 6692 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 6693 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 6694 CheckedVarArgs, UncoveredArg); 6695 6696 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 6697 S.getLangOpts(), 6698 S.Context.getTargetInfo(), 6699 Type == Sema::FST_FreeBSDKPrintf)) 6700 H.DoneProcessing(); 6701 } else if (Type == Sema::FST_Scanf) { 6702 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 6703 numDataArgs, Str, HasVAListArg, Args, format_idx, 6704 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 6705 6706 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 6707 S.getLangOpts(), 6708 S.Context.getTargetInfo())) 6709 H.DoneProcessing(); 6710 } // TODO: handle other formats 6711 } 6712 6713 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 6714 // Str - The format string. NOTE: this is NOT null-terminated! 6715 StringRef StrRef = FExpr->getString(); 6716 const char *Str = StrRef.data(); 6717 // Account for cases where the string literal is truncated in a declaration. 6718 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 6719 assert(T && "String literal not of constant array type!"); 6720 size_t TypeSize = T->getSize().getZExtValue(); 6721 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6722 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 6723 getLangOpts(), 6724 Context.getTargetInfo()); 6725 } 6726 6727 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 6728 6729 // Returns the related absolute value function that is larger, of 0 if one 6730 // does not exist. 6731 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 6732 switch (AbsFunction) { 6733 default: 6734 return 0; 6735 6736 case Builtin::BI__builtin_abs: 6737 return Builtin::BI__builtin_labs; 6738 case Builtin::BI__builtin_labs: 6739 return Builtin::BI__builtin_llabs; 6740 case Builtin::BI__builtin_llabs: 6741 return 0; 6742 6743 case Builtin::BI__builtin_fabsf: 6744 return Builtin::BI__builtin_fabs; 6745 case Builtin::BI__builtin_fabs: 6746 return Builtin::BI__builtin_fabsl; 6747 case Builtin::BI__builtin_fabsl: 6748 return 0; 6749 6750 case Builtin::BI__builtin_cabsf: 6751 return Builtin::BI__builtin_cabs; 6752 case Builtin::BI__builtin_cabs: 6753 return Builtin::BI__builtin_cabsl; 6754 case Builtin::BI__builtin_cabsl: 6755 return 0; 6756 6757 case Builtin::BIabs: 6758 return Builtin::BIlabs; 6759 case Builtin::BIlabs: 6760 return Builtin::BIllabs; 6761 case Builtin::BIllabs: 6762 return 0; 6763 6764 case Builtin::BIfabsf: 6765 return Builtin::BIfabs; 6766 case Builtin::BIfabs: 6767 return Builtin::BIfabsl; 6768 case Builtin::BIfabsl: 6769 return 0; 6770 6771 case Builtin::BIcabsf: 6772 return Builtin::BIcabs; 6773 case Builtin::BIcabs: 6774 return Builtin::BIcabsl; 6775 case Builtin::BIcabsl: 6776 return 0; 6777 } 6778 } 6779 6780 // Returns the argument type of the absolute value function. 6781 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 6782 unsigned AbsType) { 6783 if (AbsType == 0) 6784 return QualType(); 6785 6786 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 6787 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 6788 if (Error != ASTContext::GE_None) 6789 return QualType(); 6790 6791 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 6792 if (!FT) 6793 return QualType(); 6794 6795 if (FT->getNumParams() != 1) 6796 return QualType(); 6797 6798 return FT->getParamType(0); 6799 } 6800 6801 // Returns the best absolute value function, or zero, based on type and 6802 // current absolute value function. 6803 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 6804 unsigned AbsFunctionKind) { 6805 unsigned BestKind = 0; 6806 uint64_t ArgSize = Context.getTypeSize(ArgType); 6807 for (unsigned Kind = AbsFunctionKind; Kind != 0; 6808 Kind = getLargerAbsoluteValueFunction(Kind)) { 6809 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 6810 if (Context.getTypeSize(ParamType) >= ArgSize) { 6811 if (BestKind == 0) 6812 BestKind = Kind; 6813 else if (Context.hasSameType(ParamType, ArgType)) { 6814 BestKind = Kind; 6815 break; 6816 } 6817 } 6818 } 6819 return BestKind; 6820 } 6821 6822 enum AbsoluteValueKind { 6823 AVK_Integer, 6824 AVK_Floating, 6825 AVK_Complex 6826 }; 6827 6828 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 6829 if (T->isIntegralOrEnumerationType()) 6830 return AVK_Integer; 6831 if (T->isRealFloatingType()) 6832 return AVK_Floating; 6833 if (T->isAnyComplexType()) 6834 return AVK_Complex; 6835 6836 llvm_unreachable("Type not integer, floating, or complex"); 6837 } 6838 6839 // Changes the absolute value function to a different type. Preserves whether 6840 // the function is a builtin. 6841 static unsigned changeAbsFunction(unsigned AbsKind, 6842 AbsoluteValueKind ValueKind) { 6843 switch (ValueKind) { 6844 case AVK_Integer: 6845 switch (AbsKind) { 6846 default: 6847 return 0; 6848 case Builtin::BI__builtin_fabsf: 6849 case Builtin::BI__builtin_fabs: 6850 case Builtin::BI__builtin_fabsl: 6851 case Builtin::BI__builtin_cabsf: 6852 case Builtin::BI__builtin_cabs: 6853 case Builtin::BI__builtin_cabsl: 6854 return Builtin::BI__builtin_abs; 6855 case Builtin::BIfabsf: 6856 case Builtin::BIfabs: 6857 case Builtin::BIfabsl: 6858 case Builtin::BIcabsf: 6859 case Builtin::BIcabs: 6860 case Builtin::BIcabsl: 6861 return Builtin::BIabs; 6862 } 6863 case AVK_Floating: 6864 switch (AbsKind) { 6865 default: 6866 return 0; 6867 case Builtin::BI__builtin_abs: 6868 case Builtin::BI__builtin_labs: 6869 case Builtin::BI__builtin_llabs: 6870 case Builtin::BI__builtin_cabsf: 6871 case Builtin::BI__builtin_cabs: 6872 case Builtin::BI__builtin_cabsl: 6873 return Builtin::BI__builtin_fabsf; 6874 case Builtin::BIabs: 6875 case Builtin::BIlabs: 6876 case Builtin::BIllabs: 6877 case Builtin::BIcabsf: 6878 case Builtin::BIcabs: 6879 case Builtin::BIcabsl: 6880 return Builtin::BIfabsf; 6881 } 6882 case AVK_Complex: 6883 switch (AbsKind) { 6884 default: 6885 return 0; 6886 case Builtin::BI__builtin_abs: 6887 case Builtin::BI__builtin_labs: 6888 case Builtin::BI__builtin_llabs: 6889 case Builtin::BI__builtin_fabsf: 6890 case Builtin::BI__builtin_fabs: 6891 case Builtin::BI__builtin_fabsl: 6892 return Builtin::BI__builtin_cabsf; 6893 case Builtin::BIabs: 6894 case Builtin::BIlabs: 6895 case Builtin::BIllabs: 6896 case Builtin::BIfabsf: 6897 case Builtin::BIfabs: 6898 case Builtin::BIfabsl: 6899 return Builtin::BIcabsf; 6900 } 6901 } 6902 llvm_unreachable("Unable to convert function"); 6903 } 6904 6905 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 6906 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 6907 if (!FnInfo) 6908 return 0; 6909 6910 switch (FDecl->getBuiltinID()) { 6911 default: 6912 return 0; 6913 case Builtin::BI__builtin_abs: 6914 case Builtin::BI__builtin_fabs: 6915 case Builtin::BI__builtin_fabsf: 6916 case Builtin::BI__builtin_fabsl: 6917 case Builtin::BI__builtin_labs: 6918 case Builtin::BI__builtin_llabs: 6919 case Builtin::BI__builtin_cabs: 6920 case Builtin::BI__builtin_cabsf: 6921 case Builtin::BI__builtin_cabsl: 6922 case Builtin::BIabs: 6923 case Builtin::BIlabs: 6924 case Builtin::BIllabs: 6925 case Builtin::BIfabs: 6926 case Builtin::BIfabsf: 6927 case Builtin::BIfabsl: 6928 case Builtin::BIcabs: 6929 case Builtin::BIcabsf: 6930 case Builtin::BIcabsl: 6931 return FDecl->getBuiltinID(); 6932 } 6933 llvm_unreachable("Unknown Builtin type"); 6934 } 6935 6936 // If the replacement is valid, emit a note with replacement function. 6937 // Additionally, suggest including the proper header if not already included. 6938 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 6939 unsigned AbsKind, QualType ArgType) { 6940 bool EmitHeaderHint = true; 6941 const char *HeaderName = nullptr; 6942 const char *FunctionName = nullptr; 6943 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 6944 FunctionName = "std::abs"; 6945 if (ArgType->isIntegralOrEnumerationType()) { 6946 HeaderName = "cstdlib"; 6947 } else if (ArgType->isRealFloatingType()) { 6948 HeaderName = "cmath"; 6949 } else { 6950 llvm_unreachable("Invalid Type"); 6951 } 6952 6953 // Lookup all std::abs 6954 if (NamespaceDecl *Std = S.getStdNamespace()) { 6955 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 6956 R.suppressDiagnostics(); 6957 S.LookupQualifiedName(R, Std); 6958 6959 for (const auto *I : R) { 6960 const FunctionDecl *FDecl = nullptr; 6961 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 6962 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 6963 } else { 6964 FDecl = dyn_cast<FunctionDecl>(I); 6965 } 6966 if (!FDecl) 6967 continue; 6968 6969 // Found std::abs(), check that they are the right ones. 6970 if (FDecl->getNumParams() != 1) 6971 continue; 6972 6973 // Check that the parameter type can handle the argument. 6974 QualType ParamType = FDecl->getParamDecl(0)->getType(); 6975 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 6976 S.Context.getTypeSize(ArgType) <= 6977 S.Context.getTypeSize(ParamType)) { 6978 // Found a function, don't need the header hint. 6979 EmitHeaderHint = false; 6980 break; 6981 } 6982 } 6983 } 6984 } else { 6985 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 6986 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 6987 6988 if (HeaderName) { 6989 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 6990 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 6991 R.suppressDiagnostics(); 6992 S.LookupName(R, S.getCurScope()); 6993 6994 if (R.isSingleResult()) { 6995 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 6996 if (FD && FD->getBuiltinID() == AbsKind) { 6997 EmitHeaderHint = false; 6998 } else { 6999 return; 7000 } 7001 } else if (!R.empty()) { 7002 return; 7003 } 7004 } 7005 } 7006 7007 S.Diag(Loc, diag::note_replace_abs_function) 7008 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 7009 7010 if (!HeaderName) 7011 return; 7012 7013 if (!EmitHeaderHint) 7014 return; 7015 7016 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 7017 << FunctionName; 7018 } 7019 7020 template <std::size_t StrLen> 7021 static bool IsStdFunction(const FunctionDecl *FDecl, 7022 const char (&Str)[StrLen]) { 7023 if (!FDecl) 7024 return false; 7025 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 7026 return false; 7027 if (!FDecl->isInStdNamespace()) 7028 return false; 7029 7030 return true; 7031 } 7032 7033 // Warn when using the wrong abs() function. 7034 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 7035 const FunctionDecl *FDecl) { 7036 if (Call->getNumArgs() != 1) 7037 return; 7038 7039 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 7040 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 7041 if (AbsKind == 0 && !IsStdAbs) 7042 return; 7043 7044 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7045 QualType ParamType = Call->getArg(0)->getType(); 7046 7047 // Unsigned types cannot be negative. Suggest removing the absolute value 7048 // function call. 7049 if (ArgType->isUnsignedIntegerType()) { 7050 const char *FunctionName = 7051 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 7052 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 7053 Diag(Call->getExprLoc(), diag::note_remove_abs) 7054 << FunctionName 7055 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 7056 return; 7057 } 7058 7059 // Taking the absolute value of a pointer is very suspicious, they probably 7060 // wanted to index into an array, dereference a pointer, call a function, etc. 7061 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 7062 unsigned DiagType = 0; 7063 if (ArgType->isFunctionType()) 7064 DiagType = 1; 7065 else if (ArgType->isArrayType()) 7066 DiagType = 2; 7067 7068 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 7069 return; 7070 } 7071 7072 // std::abs has overloads which prevent most of the absolute value problems 7073 // from occurring. 7074 if (IsStdAbs) 7075 return; 7076 7077 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 7078 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 7079 7080 // The argument and parameter are the same kind. Check if they are the right 7081 // size. 7082 if (ArgValueKind == ParamValueKind) { 7083 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 7084 return; 7085 7086 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 7087 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 7088 << FDecl << ArgType << ParamType; 7089 7090 if (NewAbsKind == 0) 7091 return; 7092 7093 emitReplacement(*this, Call->getExprLoc(), 7094 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7095 return; 7096 } 7097 7098 // ArgValueKind != ParamValueKind 7099 // The wrong type of absolute value function was used. Attempt to find the 7100 // proper one. 7101 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 7102 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 7103 if (NewAbsKind == 0) 7104 return; 7105 7106 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 7107 << FDecl << ParamValueKind << ArgValueKind; 7108 7109 emitReplacement(*this, Call->getExprLoc(), 7110 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7111 } 7112 7113 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 7114 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 7115 const FunctionDecl *FDecl) { 7116 if (!Call || !FDecl) return; 7117 7118 // Ignore template specializations and macros. 7119 if (inTemplateInstantiation()) return; 7120 if (Call->getExprLoc().isMacroID()) return; 7121 7122 // Only care about the one template argument, two function parameter std::max 7123 if (Call->getNumArgs() != 2) return; 7124 if (!IsStdFunction(FDecl, "max")) return; 7125 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 7126 if (!ArgList) return; 7127 if (ArgList->size() != 1) return; 7128 7129 // Check that template type argument is unsigned integer. 7130 const auto& TA = ArgList->get(0); 7131 if (TA.getKind() != TemplateArgument::Type) return; 7132 QualType ArgType = TA.getAsType(); 7133 if (!ArgType->isUnsignedIntegerType()) return; 7134 7135 // See if either argument is a literal zero. 7136 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 7137 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 7138 if (!MTE) return false; 7139 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 7140 if (!Num) return false; 7141 if (Num->getValue() != 0) return false; 7142 return true; 7143 }; 7144 7145 const Expr *FirstArg = Call->getArg(0); 7146 const Expr *SecondArg = Call->getArg(1); 7147 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 7148 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 7149 7150 // Only warn when exactly one argument is zero. 7151 if (IsFirstArgZero == IsSecondArgZero) return; 7152 7153 SourceRange FirstRange = FirstArg->getSourceRange(); 7154 SourceRange SecondRange = SecondArg->getSourceRange(); 7155 7156 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 7157 7158 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 7159 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 7160 7161 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 7162 SourceRange RemovalRange; 7163 if (IsFirstArgZero) { 7164 RemovalRange = SourceRange(FirstRange.getBegin(), 7165 SecondRange.getBegin().getLocWithOffset(-1)); 7166 } else { 7167 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 7168 SecondRange.getEnd()); 7169 } 7170 7171 Diag(Call->getExprLoc(), diag::note_remove_max_call) 7172 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 7173 << FixItHint::CreateRemoval(RemovalRange); 7174 } 7175 7176 //===--- CHECK: Standard memory functions ---------------------------------===// 7177 7178 /// \brief Takes the expression passed to the size_t parameter of functions 7179 /// such as memcmp, strncat, etc and warns if it's a comparison. 7180 /// 7181 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 7182 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 7183 IdentifierInfo *FnName, 7184 SourceLocation FnLoc, 7185 SourceLocation RParenLoc) { 7186 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 7187 if (!Size) 7188 return false; 7189 7190 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 7191 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 7192 return false; 7193 7194 SourceRange SizeRange = Size->getSourceRange(); 7195 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 7196 << SizeRange << FnName; 7197 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 7198 << FnName << FixItHint::CreateInsertion( 7199 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 7200 << FixItHint::CreateRemoval(RParenLoc); 7201 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 7202 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 7203 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 7204 ")"); 7205 7206 return true; 7207 } 7208 7209 /// \brief Determine whether the given type is or contains a dynamic class type 7210 /// (e.g., whether it has a vtable). 7211 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 7212 bool &IsContained) { 7213 // Look through array types while ignoring qualifiers. 7214 const Type *Ty = T->getBaseElementTypeUnsafe(); 7215 IsContained = false; 7216 7217 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 7218 RD = RD ? RD->getDefinition() : nullptr; 7219 if (!RD || RD->isInvalidDecl()) 7220 return nullptr; 7221 7222 if (RD->isDynamicClass()) 7223 return RD; 7224 7225 // Check all the fields. If any bases were dynamic, the class is dynamic. 7226 // It's impossible for a class to transitively contain itself by value, so 7227 // infinite recursion is impossible. 7228 for (auto *FD : RD->fields()) { 7229 bool SubContained; 7230 if (const CXXRecordDecl *ContainedRD = 7231 getContainedDynamicClass(FD->getType(), SubContained)) { 7232 IsContained = true; 7233 return ContainedRD; 7234 } 7235 } 7236 7237 return nullptr; 7238 } 7239 7240 /// \brief If E is a sizeof expression, returns its argument expression, 7241 /// otherwise returns NULL. 7242 static const Expr *getSizeOfExprArg(const Expr *E) { 7243 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7244 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7245 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 7246 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 7247 7248 return nullptr; 7249 } 7250 7251 /// \brief If E is a sizeof expression, returns its argument type. 7252 static QualType getSizeOfArgType(const Expr *E) { 7253 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7254 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7255 if (SizeOf->getKind() == clang::UETT_SizeOf) 7256 return SizeOf->getTypeOfArgument(); 7257 7258 return QualType(); 7259 } 7260 7261 /// \brief Check for dangerous or invalid arguments to memset(). 7262 /// 7263 /// This issues warnings on known problematic, dangerous or unspecified 7264 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 7265 /// function calls. 7266 /// 7267 /// \param Call The call expression to diagnose. 7268 void Sema::CheckMemaccessArguments(const CallExpr *Call, 7269 unsigned BId, 7270 IdentifierInfo *FnName) { 7271 assert(BId != 0); 7272 7273 // It is possible to have a non-standard definition of memset. Validate 7274 // we have enough arguments, and if not, abort further checking. 7275 unsigned ExpectedNumArgs = 7276 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 7277 if (Call->getNumArgs() < ExpectedNumArgs) 7278 return; 7279 7280 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 7281 BId == Builtin::BIstrndup ? 1 : 2); 7282 unsigned LenArg = 7283 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 7284 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 7285 7286 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 7287 Call->getLocStart(), Call->getRParenLoc())) 7288 return; 7289 7290 // We have special checking when the length is a sizeof expression. 7291 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 7292 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 7293 llvm::FoldingSetNodeID SizeOfArgID; 7294 7295 // Although widely used, 'bzero' is not a standard function. Be more strict 7296 // with the argument types before allowing diagnostics and only allow the 7297 // form bzero(ptr, sizeof(...)). 7298 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7299 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 7300 return; 7301 7302 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 7303 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 7304 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 7305 7306 QualType DestTy = Dest->getType(); 7307 QualType PointeeTy; 7308 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 7309 PointeeTy = DestPtrTy->getPointeeType(); 7310 7311 // Never warn about void type pointers. This can be used to suppress 7312 // false positives. 7313 if (PointeeTy->isVoidType()) 7314 continue; 7315 7316 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 7317 // actually comparing the expressions for equality. Because computing the 7318 // expression IDs can be expensive, we only do this if the diagnostic is 7319 // enabled. 7320 if (SizeOfArg && 7321 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 7322 SizeOfArg->getExprLoc())) { 7323 // We only compute IDs for expressions if the warning is enabled, and 7324 // cache the sizeof arg's ID. 7325 if (SizeOfArgID == llvm::FoldingSetNodeID()) 7326 SizeOfArg->Profile(SizeOfArgID, Context, true); 7327 llvm::FoldingSetNodeID DestID; 7328 Dest->Profile(DestID, Context, true); 7329 if (DestID == SizeOfArgID) { 7330 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 7331 // over sizeof(src) as well. 7332 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 7333 StringRef ReadableName = FnName->getName(); 7334 7335 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 7336 if (UnaryOp->getOpcode() == UO_AddrOf) 7337 ActionIdx = 1; // If its an address-of operator, just remove it. 7338 if (!PointeeTy->isIncompleteType() && 7339 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 7340 ActionIdx = 2; // If the pointee's size is sizeof(char), 7341 // suggest an explicit length. 7342 7343 // If the function is defined as a builtin macro, do not show macro 7344 // expansion. 7345 SourceLocation SL = SizeOfArg->getExprLoc(); 7346 SourceRange DSR = Dest->getSourceRange(); 7347 SourceRange SSR = SizeOfArg->getSourceRange(); 7348 SourceManager &SM = getSourceManager(); 7349 7350 if (SM.isMacroArgExpansion(SL)) { 7351 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 7352 SL = SM.getSpellingLoc(SL); 7353 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 7354 SM.getSpellingLoc(DSR.getEnd())); 7355 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 7356 SM.getSpellingLoc(SSR.getEnd())); 7357 } 7358 7359 DiagRuntimeBehavior(SL, SizeOfArg, 7360 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 7361 << ReadableName 7362 << PointeeTy 7363 << DestTy 7364 << DSR 7365 << SSR); 7366 DiagRuntimeBehavior(SL, SizeOfArg, 7367 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 7368 << ActionIdx 7369 << SSR); 7370 7371 break; 7372 } 7373 } 7374 7375 // Also check for cases where the sizeof argument is the exact same 7376 // type as the memory argument, and where it points to a user-defined 7377 // record type. 7378 if (SizeOfArgTy != QualType()) { 7379 if (PointeeTy->isRecordType() && 7380 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 7381 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 7382 PDiag(diag::warn_sizeof_pointer_type_memaccess) 7383 << FnName << SizeOfArgTy << ArgIdx 7384 << PointeeTy << Dest->getSourceRange() 7385 << LenExpr->getSourceRange()); 7386 break; 7387 } 7388 } 7389 } else if (DestTy->isArrayType()) { 7390 PointeeTy = DestTy; 7391 } 7392 7393 if (PointeeTy == QualType()) 7394 continue; 7395 7396 // Always complain about dynamic classes. 7397 bool IsContained; 7398 if (const CXXRecordDecl *ContainedRD = 7399 getContainedDynamicClass(PointeeTy, IsContained)) { 7400 7401 unsigned OperationType = 0; 7402 // "overwritten" if we're warning about the destination for any call 7403 // but memcmp; otherwise a verb appropriate to the call. 7404 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 7405 if (BId == Builtin::BImemcpy) 7406 OperationType = 1; 7407 else if(BId == Builtin::BImemmove) 7408 OperationType = 2; 7409 else if (BId == Builtin::BImemcmp) 7410 OperationType = 3; 7411 } 7412 7413 DiagRuntimeBehavior( 7414 Dest->getExprLoc(), Dest, 7415 PDiag(diag::warn_dyn_class_memaccess) 7416 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 7417 << FnName << IsContained << ContainedRD << OperationType 7418 << Call->getCallee()->getSourceRange()); 7419 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 7420 BId != Builtin::BImemset) 7421 DiagRuntimeBehavior( 7422 Dest->getExprLoc(), Dest, 7423 PDiag(diag::warn_arc_object_memaccess) 7424 << ArgIdx << FnName << PointeeTy 7425 << Call->getCallee()->getSourceRange()); 7426 else 7427 continue; 7428 7429 DiagRuntimeBehavior( 7430 Dest->getExprLoc(), Dest, 7431 PDiag(diag::note_bad_memaccess_silence) 7432 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 7433 break; 7434 } 7435 } 7436 7437 // A little helper routine: ignore addition and subtraction of integer literals. 7438 // This intentionally does not ignore all integer constant expressions because 7439 // we don't want to remove sizeof(). 7440 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 7441 Ex = Ex->IgnoreParenCasts(); 7442 7443 for (;;) { 7444 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 7445 if (!BO || !BO->isAdditiveOp()) 7446 break; 7447 7448 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 7449 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 7450 7451 if (isa<IntegerLiteral>(RHS)) 7452 Ex = LHS; 7453 else if (isa<IntegerLiteral>(LHS)) 7454 Ex = RHS; 7455 else 7456 break; 7457 } 7458 7459 return Ex; 7460 } 7461 7462 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 7463 ASTContext &Context) { 7464 // Only handle constant-sized or VLAs, but not flexible members. 7465 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 7466 // Only issue the FIXIT for arrays of size > 1. 7467 if (CAT->getSize().getSExtValue() <= 1) 7468 return false; 7469 } else if (!Ty->isVariableArrayType()) { 7470 return false; 7471 } 7472 return true; 7473 } 7474 7475 // Warn if the user has made the 'size' argument to strlcpy or strlcat 7476 // be the size of the source, instead of the destination. 7477 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 7478 IdentifierInfo *FnName) { 7479 7480 // Don't crash if the user has the wrong number of arguments 7481 unsigned NumArgs = Call->getNumArgs(); 7482 if ((NumArgs != 3) && (NumArgs != 4)) 7483 return; 7484 7485 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 7486 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 7487 const Expr *CompareWithSrc = nullptr; 7488 7489 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 7490 Call->getLocStart(), Call->getRParenLoc())) 7491 return; 7492 7493 // Look for 'strlcpy(dst, x, sizeof(x))' 7494 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 7495 CompareWithSrc = Ex; 7496 else { 7497 // Look for 'strlcpy(dst, x, strlen(x))' 7498 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 7499 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 7500 SizeCall->getNumArgs() == 1) 7501 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 7502 } 7503 } 7504 7505 if (!CompareWithSrc) 7506 return; 7507 7508 // Determine if the argument to sizeof/strlen is equal to the source 7509 // argument. In principle there's all kinds of things you could do 7510 // here, for instance creating an == expression and evaluating it with 7511 // EvaluateAsBooleanCondition, but this uses a more direct technique: 7512 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 7513 if (!SrcArgDRE) 7514 return; 7515 7516 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 7517 if (!CompareWithSrcDRE || 7518 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 7519 return; 7520 7521 const Expr *OriginalSizeArg = Call->getArg(2); 7522 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 7523 << OriginalSizeArg->getSourceRange() << FnName; 7524 7525 // Output a FIXIT hint if the destination is an array (rather than a 7526 // pointer to an array). This could be enhanced to handle some 7527 // pointers if we know the actual size, like if DstArg is 'array+2' 7528 // we could say 'sizeof(array)-2'. 7529 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 7530 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 7531 return; 7532 7533 SmallString<128> sizeString; 7534 llvm::raw_svector_ostream OS(sizeString); 7535 OS << "sizeof("; 7536 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7537 OS << ")"; 7538 7539 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 7540 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 7541 OS.str()); 7542 } 7543 7544 /// Check if two expressions refer to the same declaration. 7545 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 7546 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 7547 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 7548 return D1->getDecl() == D2->getDecl(); 7549 return false; 7550 } 7551 7552 static const Expr *getStrlenExprArg(const Expr *E) { 7553 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7554 const FunctionDecl *FD = CE->getDirectCallee(); 7555 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 7556 return nullptr; 7557 return CE->getArg(0)->IgnoreParenCasts(); 7558 } 7559 return nullptr; 7560 } 7561 7562 // Warn on anti-patterns as the 'size' argument to strncat. 7563 // The correct size argument should look like following: 7564 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 7565 void Sema::CheckStrncatArguments(const CallExpr *CE, 7566 IdentifierInfo *FnName) { 7567 // Don't crash if the user has the wrong number of arguments. 7568 if (CE->getNumArgs() < 3) 7569 return; 7570 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 7571 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 7572 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 7573 7574 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 7575 CE->getRParenLoc())) 7576 return; 7577 7578 // Identify common expressions, which are wrongly used as the size argument 7579 // to strncat and may lead to buffer overflows. 7580 unsigned PatternType = 0; 7581 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 7582 // - sizeof(dst) 7583 if (referToTheSameDecl(SizeOfArg, DstArg)) 7584 PatternType = 1; 7585 // - sizeof(src) 7586 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 7587 PatternType = 2; 7588 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 7589 if (BE->getOpcode() == BO_Sub) { 7590 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 7591 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 7592 // - sizeof(dst) - strlen(dst) 7593 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 7594 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 7595 PatternType = 1; 7596 // - sizeof(src) - (anything) 7597 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 7598 PatternType = 2; 7599 } 7600 } 7601 7602 if (PatternType == 0) 7603 return; 7604 7605 // Generate the diagnostic. 7606 SourceLocation SL = LenArg->getLocStart(); 7607 SourceRange SR = LenArg->getSourceRange(); 7608 SourceManager &SM = getSourceManager(); 7609 7610 // If the function is defined as a builtin macro, do not show macro expansion. 7611 if (SM.isMacroArgExpansion(SL)) { 7612 SL = SM.getSpellingLoc(SL); 7613 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 7614 SM.getSpellingLoc(SR.getEnd())); 7615 } 7616 7617 // Check if the destination is an array (rather than a pointer to an array). 7618 QualType DstTy = DstArg->getType(); 7619 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 7620 Context); 7621 if (!isKnownSizeArray) { 7622 if (PatternType == 1) 7623 Diag(SL, diag::warn_strncat_wrong_size) << SR; 7624 else 7625 Diag(SL, diag::warn_strncat_src_size) << SR; 7626 return; 7627 } 7628 7629 if (PatternType == 1) 7630 Diag(SL, diag::warn_strncat_large_size) << SR; 7631 else 7632 Diag(SL, diag::warn_strncat_src_size) << SR; 7633 7634 SmallString<128> sizeString; 7635 llvm::raw_svector_ostream OS(sizeString); 7636 OS << "sizeof("; 7637 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7638 OS << ") - "; 7639 OS << "strlen("; 7640 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7641 OS << ") - 1"; 7642 7643 Diag(SL, diag::note_strncat_wrong_size) 7644 << FixItHint::CreateReplacement(SR, OS.str()); 7645 } 7646 7647 //===--- CHECK: Return Address of Stack Variable --------------------------===// 7648 7649 static const Expr *EvalVal(const Expr *E, 7650 SmallVectorImpl<const DeclRefExpr *> &refVars, 7651 const Decl *ParentDecl); 7652 static const Expr *EvalAddr(const Expr *E, 7653 SmallVectorImpl<const DeclRefExpr *> &refVars, 7654 const Decl *ParentDecl); 7655 7656 /// CheckReturnStackAddr - Check if a return statement returns the address 7657 /// of a stack variable. 7658 static void 7659 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 7660 SourceLocation ReturnLoc) { 7661 7662 const Expr *stackE = nullptr; 7663 SmallVector<const DeclRefExpr *, 8> refVars; 7664 7665 // Perform checking for returned stack addresses, local blocks, 7666 // label addresses or references to temporaries. 7667 if (lhsType->isPointerType() || 7668 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 7669 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 7670 } else if (lhsType->isReferenceType()) { 7671 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 7672 } 7673 7674 if (!stackE) 7675 return; // Nothing suspicious was found. 7676 7677 // Parameters are initialized in the calling scope, so taking the address 7678 // of a parameter reference doesn't need a warning. 7679 for (auto *DRE : refVars) 7680 if (isa<ParmVarDecl>(DRE->getDecl())) 7681 return; 7682 7683 SourceLocation diagLoc; 7684 SourceRange diagRange; 7685 if (refVars.empty()) { 7686 diagLoc = stackE->getLocStart(); 7687 diagRange = stackE->getSourceRange(); 7688 } else { 7689 // We followed through a reference variable. 'stackE' contains the 7690 // problematic expression but we will warn at the return statement pointing 7691 // at the reference variable. We will later display the "trail" of 7692 // reference variables using notes. 7693 diagLoc = refVars[0]->getLocStart(); 7694 diagRange = refVars[0]->getSourceRange(); 7695 } 7696 7697 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 7698 // address of local var 7699 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 7700 << DR->getDecl()->getDeclName() << diagRange; 7701 } else if (isa<BlockExpr>(stackE)) { // local block. 7702 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 7703 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 7704 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 7705 } else { // local temporary. 7706 // If there is an LValue->RValue conversion, then the value of the 7707 // reference type is used, not the reference. 7708 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 7709 if (ICE->getCastKind() == CK_LValueToRValue) { 7710 return; 7711 } 7712 } 7713 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 7714 << lhsType->isReferenceType() << diagRange; 7715 } 7716 7717 // Display the "trail" of reference variables that we followed until we 7718 // found the problematic expression using notes. 7719 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 7720 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 7721 // If this var binds to another reference var, show the range of the next 7722 // var, otherwise the var binds to the problematic expression, in which case 7723 // show the range of the expression. 7724 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 7725 : stackE->getSourceRange(); 7726 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 7727 << VD->getDeclName() << range; 7728 } 7729 } 7730 7731 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 7732 /// check if the expression in a return statement evaluates to an address 7733 /// to a location on the stack, a local block, an address of a label, or a 7734 /// reference to local temporary. The recursion is used to traverse the 7735 /// AST of the return expression, with recursion backtracking when we 7736 /// encounter a subexpression that (1) clearly does not lead to one of the 7737 /// above problematic expressions (2) is something we cannot determine leads to 7738 /// a problematic expression based on such local checking. 7739 /// 7740 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 7741 /// the expression that they point to. Such variables are added to the 7742 /// 'refVars' vector so that we know what the reference variable "trail" was. 7743 /// 7744 /// EvalAddr processes expressions that are pointers that are used as 7745 /// references (and not L-values). EvalVal handles all other values. 7746 /// At the base case of the recursion is a check for the above problematic 7747 /// expressions. 7748 /// 7749 /// This implementation handles: 7750 /// 7751 /// * pointer-to-pointer casts 7752 /// * implicit conversions from array references to pointers 7753 /// * taking the address of fields 7754 /// * arbitrary interplay between "&" and "*" operators 7755 /// * pointer arithmetic from an address of a stack variable 7756 /// * taking the address of an array element where the array is on the stack 7757 static const Expr *EvalAddr(const Expr *E, 7758 SmallVectorImpl<const DeclRefExpr *> &refVars, 7759 const Decl *ParentDecl) { 7760 if (E->isTypeDependent()) 7761 return nullptr; 7762 7763 // We should only be called for evaluating pointer expressions. 7764 assert((E->getType()->isAnyPointerType() || 7765 E->getType()->isBlockPointerType() || 7766 E->getType()->isObjCQualifiedIdType()) && 7767 "EvalAddr only works on pointers"); 7768 7769 E = E->IgnoreParens(); 7770 7771 // Our "symbolic interpreter" is just a dispatch off the currently 7772 // viewed AST node. We then recursively traverse the AST by calling 7773 // EvalAddr and EvalVal appropriately. 7774 switch (E->getStmtClass()) { 7775 case Stmt::DeclRefExprClass: { 7776 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7777 7778 // If we leave the immediate function, the lifetime isn't about to end. 7779 if (DR->refersToEnclosingVariableOrCapture()) 7780 return nullptr; 7781 7782 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 7783 // If this is a reference variable, follow through to the expression that 7784 // it points to. 7785 if (V->hasLocalStorage() && 7786 V->getType()->isReferenceType() && V->hasInit()) { 7787 // Add the reference variable to the "trail". 7788 refVars.push_back(DR); 7789 return EvalAddr(V->getInit(), refVars, ParentDecl); 7790 } 7791 7792 return nullptr; 7793 } 7794 7795 case Stmt::UnaryOperatorClass: { 7796 // The only unary operator that make sense to handle here 7797 // is AddrOf. All others don't make sense as pointers. 7798 const UnaryOperator *U = cast<UnaryOperator>(E); 7799 7800 if (U->getOpcode() == UO_AddrOf) 7801 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 7802 return nullptr; 7803 } 7804 7805 case Stmt::BinaryOperatorClass: { 7806 // Handle pointer arithmetic. All other binary operators are not valid 7807 // in this context. 7808 const BinaryOperator *B = cast<BinaryOperator>(E); 7809 BinaryOperatorKind op = B->getOpcode(); 7810 7811 if (op != BO_Add && op != BO_Sub) 7812 return nullptr; 7813 7814 const Expr *Base = B->getLHS(); 7815 7816 // Determine which argument is the real pointer base. It could be 7817 // the RHS argument instead of the LHS. 7818 if (!Base->getType()->isPointerType()) 7819 Base = B->getRHS(); 7820 7821 assert(Base->getType()->isPointerType()); 7822 return EvalAddr(Base, refVars, ParentDecl); 7823 } 7824 7825 // For conditional operators we need to see if either the LHS or RHS are 7826 // valid DeclRefExpr*s. If one of them is valid, we return it. 7827 case Stmt::ConditionalOperatorClass: { 7828 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7829 7830 // Handle the GNU extension for missing LHS. 7831 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 7832 if (const Expr *LHSExpr = C->getLHS()) { 7833 // In C++, we can have a throw-expression, which has 'void' type. 7834 if (!LHSExpr->getType()->isVoidType()) 7835 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 7836 return LHS; 7837 } 7838 7839 // In C++, we can have a throw-expression, which has 'void' type. 7840 if (C->getRHS()->getType()->isVoidType()) 7841 return nullptr; 7842 7843 return EvalAddr(C->getRHS(), refVars, ParentDecl); 7844 } 7845 7846 case Stmt::BlockExprClass: 7847 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 7848 return E; // local block. 7849 return nullptr; 7850 7851 case Stmt::AddrLabelExprClass: 7852 return E; // address of label. 7853 7854 case Stmt::ExprWithCleanupsClass: 7855 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7856 ParentDecl); 7857 7858 // For casts, we need to handle conversions from arrays to 7859 // pointer values, and pointer-to-pointer conversions. 7860 case Stmt::ImplicitCastExprClass: 7861 case Stmt::CStyleCastExprClass: 7862 case Stmt::CXXFunctionalCastExprClass: 7863 case Stmt::ObjCBridgedCastExprClass: 7864 case Stmt::CXXStaticCastExprClass: 7865 case Stmt::CXXDynamicCastExprClass: 7866 case Stmt::CXXConstCastExprClass: 7867 case Stmt::CXXReinterpretCastExprClass: { 7868 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 7869 switch (cast<CastExpr>(E)->getCastKind()) { 7870 case CK_LValueToRValue: 7871 case CK_NoOp: 7872 case CK_BaseToDerived: 7873 case CK_DerivedToBase: 7874 case CK_UncheckedDerivedToBase: 7875 case CK_Dynamic: 7876 case CK_CPointerToObjCPointerCast: 7877 case CK_BlockPointerToObjCPointerCast: 7878 case CK_AnyPointerToBlockPointerCast: 7879 return EvalAddr(SubExpr, refVars, ParentDecl); 7880 7881 case CK_ArrayToPointerDecay: 7882 return EvalVal(SubExpr, refVars, ParentDecl); 7883 7884 case CK_BitCast: 7885 if (SubExpr->getType()->isAnyPointerType() || 7886 SubExpr->getType()->isBlockPointerType() || 7887 SubExpr->getType()->isObjCQualifiedIdType()) 7888 return EvalAddr(SubExpr, refVars, ParentDecl); 7889 else 7890 return nullptr; 7891 7892 default: 7893 return nullptr; 7894 } 7895 } 7896 7897 case Stmt::MaterializeTemporaryExprClass: 7898 if (const Expr *Result = 7899 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7900 refVars, ParentDecl)) 7901 return Result; 7902 return E; 7903 7904 // Everything else: we simply don't reason about them. 7905 default: 7906 return nullptr; 7907 } 7908 } 7909 7910 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 7911 /// See the comments for EvalAddr for more details. 7912 static const Expr *EvalVal(const Expr *E, 7913 SmallVectorImpl<const DeclRefExpr *> &refVars, 7914 const Decl *ParentDecl) { 7915 do { 7916 // We should only be called for evaluating non-pointer expressions, or 7917 // expressions with a pointer type that are not used as references but 7918 // instead 7919 // are l-values (e.g., DeclRefExpr with a pointer type). 7920 7921 // Our "symbolic interpreter" is just a dispatch off the currently 7922 // viewed AST node. We then recursively traverse the AST by calling 7923 // EvalAddr and EvalVal appropriately. 7924 7925 E = E->IgnoreParens(); 7926 switch (E->getStmtClass()) { 7927 case Stmt::ImplicitCastExprClass: { 7928 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 7929 if (IE->getValueKind() == VK_LValue) { 7930 E = IE->getSubExpr(); 7931 continue; 7932 } 7933 return nullptr; 7934 } 7935 7936 case Stmt::ExprWithCleanupsClass: 7937 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7938 ParentDecl); 7939 7940 case Stmt::DeclRefExprClass: { 7941 // When we hit a DeclRefExpr we are looking at code that refers to a 7942 // variable's name. If it's not a reference variable we check if it has 7943 // local storage within the function, and if so, return the expression. 7944 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7945 7946 // If we leave the immediate function, the lifetime isn't about to end. 7947 if (DR->refersToEnclosingVariableOrCapture()) 7948 return nullptr; 7949 7950 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 7951 // Check if it refers to itself, e.g. "int& i = i;". 7952 if (V == ParentDecl) 7953 return DR; 7954 7955 if (V->hasLocalStorage()) { 7956 if (!V->getType()->isReferenceType()) 7957 return DR; 7958 7959 // Reference variable, follow through to the expression that 7960 // it points to. 7961 if (V->hasInit()) { 7962 // Add the reference variable to the "trail". 7963 refVars.push_back(DR); 7964 return EvalVal(V->getInit(), refVars, V); 7965 } 7966 } 7967 } 7968 7969 return nullptr; 7970 } 7971 7972 case Stmt::UnaryOperatorClass: { 7973 // The only unary operator that make sense to handle here 7974 // is Deref. All others don't resolve to a "name." This includes 7975 // handling all sorts of rvalues passed to a unary operator. 7976 const UnaryOperator *U = cast<UnaryOperator>(E); 7977 7978 if (U->getOpcode() == UO_Deref) 7979 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 7980 7981 return nullptr; 7982 } 7983 7984 case Stmt::ArraySubscriptExprClass: { 7985 // Array subscripts are potential references to data on the stack. We 7986 // retrieve the DeclRefExpr* for the array variable if it indeed 7987 // has local storage. 7988 const auto *ASE = cast<ArraySubscriptExpr>(E); 7989 if (ASE->isTypeDependent()) 7990 return nullptr; 7991 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 7992 } 7993 7994 case Stmt::OMPArraySectionExprClass: { 7995 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 7996 ParentDecl); 7997 } 7998 7999 case Stmt::ConditionalOperatorClass: { 8000 // For conditional operators we need to see if either the LHS or RHS are 8001 // non-NULL Expr's. If one is non-NULL, we return it. 8002 const ConditionalOperator *C = cast<ConditionalOperator>(E); 8003 8004 // Handle the GNU extension for missing LHS. 8005 if (const Expr *LHSExpr = C->getLHS()) { 8006 // In C++, we can have a throw-expression, which has 'void' type. 8007 if (!LHSExpr->getType()->isVoidType()) 8008 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 8009 return LHS; 8010 } 8011 8012 // In C++, we can have a throw-expression, which has 'void' type. 8013 if (C->getRHS()->getType()->isVoidType()) 8014 return nullptr; 8015 8016 return EvalVal(C->getRHS(), refVars, ParentDecl); 8017 } 8018 8019 // Accesses to members are potential references to data on the stack. 8020 case Stmt::MemberExprClass: { 8021 const MemberExpr *M = cast<MemberExpr>(E); 8022 8023 // Check for indirect access. We only want direct field accesses. 8024 if (M->isArrow()) 8025 return nullptr; 8026 8027 // Check whether the member type is itself a reference, in which case 8028 // we're not going to refer to the member, but to what the member refers 8029 // to. 8030 if (M->getMemberDecl()->getType()->isReferenceType()) 8031 return nullptr; 8032 8033 return EvalVal(M->getBase(), refVars, ParentDecl); 8034 } 8035 8036 case Stmt::MaterializeTemporaryExprClass: 8037 if (const Expr *Result = 8038 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8039 refVars, ParentDecl)) 8040 return Result; 8041 return E; 8042 8043 default: 8044 // Check that we don't return or take the address of a reference to a 8045 // temporary. This is only useful in C++. 8046 if (!E->isTypeDependent() && E->isRValue()) 8047 return E; 8048 8049 // Everything else: we simply don't reason about them. 8050 return nullptr; 8051 } 8052 } while (true); 8053 } 8054 8055 void 8056 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 8057 SourceLocation ReturnLoc, 8058 bool isObjCMethod, 8059 const AttrVec *Attrs, 8060 const FunctionDecl *FD) { 8061 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 8062 8063 // Check if the return value is null but should not be. 8064 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 8065 (!isObjCMethod && isNonNullType(Context, lhsType))) && 8066 CheckNonNullExpr(*this, RetValExp)) 8067 Diag(ReturnLoc, diag::warn_null_ret) 8068 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 8069 8070 // C++11 [basic.stc.dynamic.allocation]p4: 8071 // If an allocation function declared with a non-throwing 8072 // exception-specification fails to allocate storage, it shall return 8073 // a null pointer. Any other allocation function that fails to allocate 8074 // storage shall indicate failure only by throwing an exception [...] 8075 if (FD) { 8076 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 8077 if (Op == OO_New || Op == OO_Array_New) { 8078 const FunctionProtoType *Proto 8079 = FD->getType()->castAs<FunctionProtoType>(); 8080 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 8081 CheckNonNullExpr(*this, RetValExp)) 8082 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 8083 << FD << getLangOpts().CPlusPlus11; 8084 } 8085 } 8086 } 8087 8088 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 8089 8090 /// Check for comparisons of floating point operands using != and ==. 8091 /// Issue a warning if these are no self-comparisons, as they are not likely 8092 /// to do what the programmer intended. 8093 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 8094 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 8095 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 8096 8097 // Special case: check for x == x (which is OK). 8098 // Do not emit warnings for such cases. 8099 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 8100 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 8101 if (DRL->getDecl() == DRR->getDecl()) 8102 return; 8103 8104 // Special case: check for comparisons against literals that can be exactly 8105 // represented by APFloat. In such cases, do not emit a warning. This 8106 // is a heuristic: often comparison against such literals are used to 8107 // detect if a value in a variable has not changed. This clearly can 8108 // lead to false negatives. 8109 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 8110 if (FLL->isExact()) 8111 return; 8112 } else 8113 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 8114 if (FLR->isExact()) 8115 return; 8116 8117 // Check for comparisons with builtin types. 8118 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 8119 if (CL->getBuiltinCallee()) 8120 return; 8121 8122 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 8123 if (CR->getBuiltinCallee()) 8124 return; 8125 8126 // Emit the diagnostic. 8127 Diag(Loc, diag::warn_floatingpoint_eq) 8128 << LHS->getSourceRange() << RHS->getSourceRange(); 8129 } 8130 8131 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 8132 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 8133 8134 namespace { 8135 8136 /// Structure recording the 'active' range of an integer-valued 8137 /// expression. 8138 struct IntRange { 8139 /// The number of bits active in the int. 8140 unsigned Width; 8141 8142 /// True if the int is known not to have negative values. 8143 bool NonNegative; 8144 8145 IntRange(unsigned Width, bool NonNegative) 8146 : Width(Width), NonNegative(NonNegative) 8147 {} 8148 8149 /// Returns the range of the bool type. 8150 static IntRange forBoolType() { 8151 return IntRange(1, true); 8152 } 8153 8154 /// Returns the range of an opaque value of the given integral type. 8155 static IntRange forValueOfType(ASTContext &C, QualType T) { 8156 return forValueOfCanonicalType(C, 8157 T->getCanonicalTypeInternal().getTypePtr()); 8158 } 8159 8160 /// Returns the range of an opaque value of a canonical integral type. 8161 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 8162 assert(T->isCanonicalUnqualified()); 8163 8164 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8165 T = VT->getElementType().getTypePtr(); 8166 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8167 T = CT->getElementType().getTypePtr(); 8168 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8169 T = AT->getValueType().getTypePtr(); 8170 8171 // For enum types, use the known bit width of the enumerators. 8172 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 8173 EnumDecl *Enum = ET->getDecl(); 8174 if (!Enum->isCompleteDefinition()) 8175 return IntRange(C.getIntWidth(QualType(T, 0)), false); 8176 8177 unsigned NumPositive = Enum->getNumPositiveBits(); 8178 unsigned NumNegative = Enum->getNumNegativeBits(); 8179 8180 if (NumNegative == 0) 8181 return IntRange(NumPositive, true/*NonNegative*/); 8182 else 8183 return IntRange(std::max(NumPositive + 1, NumNegative), 8184 false/*NonNegative*/); 8185 } 8186 8187 const BuiltinType *BT = cast<BuiltinType>(T); 8188 assert(BT->isInteger()); 8189 8190 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8191 } 8192 8193 /// Returns the "target" range of a canonical integral type, i.e. 8194 /// the range of values expressible in the type. 8195 /// 8196 /// This matches forValueOfCanonicalType except that enums have the 8197 /// full range of their type, not the range of their enumerators. 8198 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 8199 assert(T->isCanonicalUnqualified()); 8200 8201 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8202 T = VT->getElementType().getTypePtr(); 8203 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8204 T = CT->getElementType().getTypePtr(); 8205 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8206 T = AT->getValueType().getTypePtr(); 8207 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8208 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 8209 8210 const BuiltinType *BT = cast<BuiltinType>(T); 8211 assert(BT->isInteger()); 8212 8213 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8214 } 8215 8216 /// Returns the supremum of two ranges: i.e. their conservative merge. 8217 static IntRange join(IntRange L, IntRange R) { 8218 return IntRange(std::max(L.Width, R.Width), 8219 L.NonNegative && R.NonNegative); 8220 } 8221 8222 /// Returns the infinum of two ranges: i.e. their aggressive merge. 8223 static IntRange meet(IntRange L, IntRange R) { 8224 return IntRange(std::min(L.Width, R.Width), 8225 L.NonNegative || R.NonNegative); 8226 } 8227 }; 8228 8229 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 8230 if (value.isSigned() && value.isNegative()) 8231 return IntRange(value.getMinSignedBits(), false); 8232 8233 if (value.getBitWidth() > MaxWidth) 8234 value = value.trunc(MaxWidth); 8235 8236 // isNonNegative() just checks the sign bit without considering 8237 // signedness. 8238 return IntRange(value.getActiveBits(), true); 8239 } 8240 8241 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 8242 unsigned MaxWidth) { 8243 if (result.isInt()) 8244 return GetValueRange(C, result.getInt(), MaxWidth); 8245 8246 if (result.isVector()) { 8247 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 8248 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 8249 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 8250 R = IntRange::join(R, El); 8251 } 8252 return R; 8253 } 8254 8255 if (result.isComplexInt()) { 8256 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 8257 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 8258 return IntRange::join(R, I); 8259 } 8260 8261 // This can happen with lossless casts to intptr_t of "based" lvalues. 8262 // Assume it might use arbitrary bits. 8263 // FIXME: The only reason we need to pass the type in here is to get 8264 // the sign right on this one case. It would be nice if APValue 8265 // preserved this. 8266 assert(result.isLValue() || result.isAddrLabelDiff()); 8267 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 8268 } 8269 8270 QualType GetExprType(const Expr *E) { 8271 QualType Ty = E->getType(); 8272 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 8273 Ty = AtomicRHS->getValueType(); 8274 return Ty; 8275 } 8276 8277 /// Pseudo-evaluate the given integer expression, estimating the 8278 /// range of values it might take. 8279 /// 8280 /// \param MaxWidth - the width to which the value will be truncated 8281 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 8282 E = E->IgnoreParens(); 8283 8284 // Try a full evaluation first. 8285 Expr::EvalResult result; 8286 if (E->EvaluateAsRValue(result, C)) 8287 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 8288 8289 // I think we only want to look through implicit casts here; if the 8290 // user has an explicit widening cast, we should treat the value as 8291 // being of the new, wider type. 8292 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 8293 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 8294 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 8295 8296 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 8297 8298 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 8299 CE->getCastKind() == CK_BooleanToSignedIntegral; 8300 8301 // Assume that non-integer casts can span the full range of the type. 8302 if (!isIntegerCast) 8303 return OutputTypeRange; 8304 8305 IntRange SubRange 8306 = GetExprRange(C, CE->getSubExpr(), 8307 std::min(MaxWidth, OutputTypeRange.Width)); 8308 8309 // Bail out if the subexpr's range is as wide as the cast type. 8310 if (SubRange.Width >= OutputTypeRange.Width) 8311 return OutputTypeRange; 8312 8313 // Otherwise, we take the smaller width, and we're non-negative if 8314 // either the output type or the subexpr is. 8315 return IntRange(SubRange.Width, 8316 SubRange.NonNegative || OutputTypeRange.NonNegative); 8317 } 8318 8319 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 8320 // If we can fold the condition, just take that operand. 8321 bool CondResult; 8322 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 8323 return GetExprRange(C, CondResult ? CO->getTrueExpr() 8324 : CO->getFalseExpr(), 8325 MaxWidth); 8326 8327 // Otherwise, conservatively merge. 8328 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 8329 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 8330 return IntRange::join(L, R); 8331 } 8332 8333 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 8334 switch (BO->getOpcode()) { 8335 8336 // Boolean-valued operations are single-bit and positive. 8337 case BO_LAnd: 8338 case BO_LOr: 8339 case BO_LT: 8340 case BO_GT: 8341 case BO_LE: 8342 case BO_GE: 8343 case BO_EQ: 8344 case BO_NE: 8345 return IntRange::forBoolType(); 8346 8347 // The type of the assignments is the type of the LHS, so the RHS 8348 // is not necessarily the same type. 8349 case BO_MulAssign: 8350 case BO_DivAssign: 8351 case BO_RemAssign: 8352 case BO_AddAssign: 8353 case BO_SubAssign: 8354 case BO_XorAssign: 8355 case BO_OrAssign: 8356 // TODO: bitfields? 8357 return IntRange::forValueOfType(C, GetExprType(E)); 8358 8359 // Simple assignments just pass through the RHS, which will have 8360 // been coerced to the LHS type. 8361 case BO_Assign: 8362 // TODO: bitfields? 8363 return GetExprRange(C, BO->getRHS(), MaxWidth); 8364 8365 // Operations with opaque sources are black-listed. 8366 case BO_PtrMemD: 8367 case BO_PtrMemI: 8368 return IntRange::forValueOfType(C, GetExprType(E)); 8369 8370 // Bitwise-and uses the *infinum* of the two source ranges. 8371 case BO_And: 8372 case BO_AndAssign: 8373 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 8374 GetExprRange(C, BO->getRHS(), MaxWidth)); 8375 8376 // Left shift gets black-listed based on a judgement call. 8377 case BO_Shl: 8378 // ...except that we want to treat '1 << (blah)' as logically 8379 // positive. It's an important idiom. 8380 if (IntegerLiteral *I 8381 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 8382 if (I->getValue() == 1) { 8383 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 8384 return IntRange(R.Width, /*NonNegative*/ true); 8385 } 8386 } 8387 // fallthrough 8388 8389 case BO_ShlAssign: 8390 return IntRange::forValueOfType(C, GetExprType(E)); 8391 8392 // Right shift by a constant can narrow its left argument. 8393 case BO_Shr: 8394 case BO_ShrAssign: { 8395 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8396 8397 // If the shift amount is a positive constant, drop the width by 8398 // that much. 8399 llvm::APSInt shift; 8400 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 8401 shift.isNonNegative()) { 8402 unsigned zext = shift.getZExtValue(); 8403 if (zext >= L.Width) 8404 L.Width = (L.NonNegative ? 0 : 1); 8405 else 8406 L.Width -= zext; 8407 } 8408 8409 return L; 8410 } 8411 8412 // Comma acts as its right operand. 8413 case BO_Comma: 8414 return GetExprRange(C, BO->getRHS(), MaxWidth); 8415 8416 // Black-list pointer subtractions. 8417 case BO_Sub: 8418 if (BO->getLHS()->getType()->isPointerType()) 8419 return IntRange::forValueOfType(C, GetExprType(E)); 8420 break; 8421 8422 // The width of a division result is mostly determined by the size 8423 // of the LHS. 8424 case BO_Div: { 8425 // Don't 'pre-truncate' the operands. 8426 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8427 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8428 8429 // If the divisor is constant, use that. 8430 llvm::APSInt divisor; 8431 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 8432 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 8433 if (log2 >= L.Width) 8434 L.Width = (L.NonNegative ? 0 : 1); 8435 else 8436 L.Width = std::min(L.Width - log2, MaxWidth); 8437 return L; 8438 } 8439 8440 // Otherwise, just use the LHS's width. 8441 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8442 return IntRange(L.Width, L.NonNegative && R.NonNegative); 8443 } 8444 8445 // The result of a remainder can't be larger than the result of 8446 // either side. 8447 case BO_Rem: { 8448 // Don't 'pre-truncate' the operands. 8449 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8450 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8451 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8452 8453 IntRange meet = IntRange::meet(L, R); 8454 meet.Width = std::min(meet.Width, MaxWidth); 8455 return meet; 8456 } 8457 8458 // The default behavior is okay for these. 8459 case BO_Mul: 8460 case BO_Add: 8461 case BO_Xor: 8462 case BO_Or: 8463 break; 8464 } 8465 8466 // The default case is to treat the operation as if it were closed 8467 // on the narrowest type that encompasses both operands. 8468 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8469 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 8470 return IntRange::join(L, R); 8471 } 8472 8473 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 8474 switch (UO->getOpcode()) { 8475 // Boolean-valued operations are white-listed. 8476 case UO_LNot: 8477 return IntRange::forBoolType(); 8478 8479 // Operations with opaque sources are black-listed. 8480 case UO_Deref: 8481 case UO_AddrOf: // should be impossible 8482 return IntRange::forValueOfType(C, GetExprType(E)); 8483 8484 default: 8485 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 8486 } 8487 } 8488 8489 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 8490 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 8491 8492 if (const auto *BitField = E->getSourceBitField()) 8493 return IntRange(BitField->getBitWidthValue(C), 8494 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 8495 8496 return IntRange::forValueOfType(C, GetExprType(E)); 8497 } 8498 8499 IntRange GetExprRange(ASTContext &C, const Expr *E) { 8500 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 8501 } 8502 8503 /// Checks whether the given value, which currently has the given 8504 /// source semantics, has the same value when coerced through the 8505 /// target semantics. 8506 bool IsSameFloatAfterCast(const llvm::APFloat &value, 8507 const llvm::fltSemantics &Src, 8508 const llvm::fltSemantics &Tgt) { 8509 llvm::APFloat truncated = value; 8510 8511 bool ignored; 8512 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 8513 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 8514 8515 return truncated.bitwiseIsEqual(value); 8516 } 8517 8518 /// Checks whether the given value, which currently has the given 8519 /// source semantics, has the same value when coerced through the 8520 /// target semantics. 8521 /// 8522 /// The value might be a vector of floats (or a complex number). 8523 bool IsSameFloatAfterCast(const APValue &value, 8524 const llvm::fltSemantics &Src, 8525 const llvm::fltSemantics &Tgt) { 8526 if (value.isFloat()) 8527 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 8528 8529 if (value.isVector()) { 8530 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 8531 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 8532 return false; 8533 return true; 8534 } 8535 8536 assert(value.isComplexFloat()); 8537 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 8538 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 8539 } 8540 8541 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 8542 8543 bool IsZero(Sema &S, Expr *E) { 8544 // Suppress cases where we are comparing against an enum constant. 8545 if (const DeclRefExpr *DR = 8546 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 8547 if (isa<EnumConstantDecl>(DR->getDecl())) 8548 return false; 8549 8550 // Suppress cases where the '0' value is expanded from a macro. 8551 if (E->getLocStart().isMacroID()) 8552 return false; 8553 8554 llvm::APSInt Value; 8555 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 8556 } 8557 8558 bool HasEnumType(Expr *E) { 8559 // Strip off implicit integral promotions. 8560 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8561 if (ICE->getCastKind() != CK_IntegralCast && 8562 ICE->getCastKind() != CK_NoOp) 8563 break; 8564 E = ICE->getSubExpr(); 8565 } 8566 8567 return E->getType()->isEnumeralType(); 8568 } 8569 8570 bool isNonBooleanUnsignedValue(Expr *E) { 8571 // We are checking that the expression is not known to have boolean value, 8572 // is an integer type; and is either unsigned after implicit casts, 8573 // or was unsigned before implicit casts. 8574 return !E->isKnownToHaveBooleanValue() && E->getType()->isIntegerType() && 8575 (!E->getType()->isSignedIntegerType() || 8576 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 8577 } 8578 8579 bool CheckTautologicalComparisonWithZero(Sema &S, BinaryOperator *E) { 8580 // Disable warning in template instantiations. 8581 if (S.inTemplateInstantiation()) 8582 return false; 8583 8584 // bool values are handled by DiagnoseOutOfRangeComparison(). 8585 8586 BinaryOperatorKind op = E->getOpcode(); 8587 if (E->isValueDependent()) 8588 return false; 8589 8590 Expr *LHS = E->getLHS(); 8591 Expr *RHS = E->getRHS(); 8592 8593 bool Match = true; 8594 8595 if (op == BO_LT && isNonBooleanUnsignedValue(LHS) && IsZero(S, RHS)) { 8596 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8597 << "< 0" << "false" << HasEnumType(LHS) 8598 << LHS->getSourceRange() << RHS->getSourceRange(); 8599 } else if (op == BO_GE && isNonBooleanUnsignedValue(LHS) && IsZero(S, RHS)) { 8600 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8601 << ">= 0" << "true" << HasEnumType(LHS) 8602 << LHS->getSourceRange() << RHS->getSourceRange(); 8603 } else if (op == BO_GT && isNonBooleanUnsignedValue(RHS) && IsZero(S, LHS)) { 8604 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8605 << "0 >" << "false" << HasEnumType(RHS) 8606 << LHS->getSourceRange() << RHS->getSourceRange(); 8607 } else if (op == BO_LE && isNonBooleanUnsignedValue(RHS) && IsZero(S, LHS)) { 8608 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8609 << "0 <=" << "true" << HasEnumType(RHS) 8610 << LHS->getSourceRange() << RHS->getSourceRange(); 8611 } else 8612 Match = false; 8613 8614 return Match; 8615 } 8616 8617 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant, 8618 Expr *Other, const llvm::APSInt &Value, 8619 bool RhsConstant) { 8620 // Disable warning in template instantiations. 8621 if (S.inTemplateInstantiation()) 8622 return; 8623 8624 // TODO: Investigate using GetExprRange() to get tighter bounds 8625 // on the bit ranges. 8626 QualType OtherT = Other->getType(); 8627 if (const auto *AT = OtherT->getAs<AtomicType>()) 8628 OtherT = AT->getValueType(); 8629 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 8630 unsigned OtherWidth = OtherRange.Width; 8631 8632 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 8633 8634 // 0 values are handled later by CheckTautologicalComparisonWithZero(). 8635 if ((Value == 0) && (!OtherIsBooleanType)) 8636 return; 8637 8638 BinaryOperatorKind op = E->getOpcode(); 8639 bool IsTrue = true; 8640 8641 // Used for diagnostic printout. 8642 enum { 8643 LiteralConstant = 0, 8644 CXXBoolLiteralTrue, 8645 CXXBoolLiteralFalse 8646 } LiteralOrBoolConstant = LiteralConstant; 8647 8648 if (!OtherIsBooleanType) { 8649 QualType ConstantT = Constant->getType(); 8650 QualType CommonT = E->getLHS()->getType(); 8651 8652 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 8653 return; 8654 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 8655 "comparison with non-integer type"); 8656 8657 bool ConstantSigned = ConstantT->isSignedIntegerType(); 8658 bool CommonSigned = CommonT->isSignedIntegerType(); 8659 8660 bool EqualityOnly = false; 8661 8662 if (CommonSigned) { 8663 // The common type is signed, therefore no signed to unsigned conversion. 8664 if (!OtherRange.NonNegative) { 8665 // Check that the constant is representable in type OtherT. 8666 if (ConstantSigned) { 8667 if (OtherWidth >= Value.getMinSignedBits()) 8668 return; 8669 } else { // !ConstantSigned 8670 if (OtherWidth >= Value.getActiveBits() + 1) 8671 return; 8672 } 8673 } else { // !OtherSigned 8674 // Check that the constant is representable in type OtherT. 8675 // Negative values are out of range. 8676 if (ConstantSigned) { 8677 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 8678 return; 8679 } else { // !ConstantSigned 8680 if (OtherWidth >= Value.getActiveBits()) 8681 return; 8682 } 8683 } 8684 } else { // !CommonSigned 8685 if (OtherRange.NonNegative) { 8686 if (OtherWidth >= Value.getActiveBits()) 8687 return; 8688 } else { // OtherSigned 8689 assert(!ConstantSigned && 8690 "Two signed types converted to unsigned types."); 8691 // Check to see if the constant is representable in OtherT. 8692 if (OtherWidth > Value.getActiveBits()) 8693 return; 8694 // Check to see if the constant is equivalent to a negative value 8695 // cast to CommonT. 8696 if (S.Context.getIntWidth(ConstantT) == 8697 S.Context.getIntWidth(CommonT) && 8698 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 8699 return; 8700 // The constant value rests between values that OtherT can represent 8701 // after conversion. Relational comparison still works, but equality 8702 // comparisons will be tautological. 8703 EqualityOnly = true; 8704 } 8705 } 8706 8707 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 8708 8709 if (op == BO_EQ || op == BO_NE) { 8710 IsTrue = op == BO_NE; 8711 } else if (EqualityOnly) { 8712 return; 8713 } else if (RhsConstant) { 8714 if (op == BO_GT || op == BO_GE) 8715 IsTrue = !PositiveConstant; 8716 else // op == BO_LT || op == BO_LE 8717 IsTrue = PositiveConstant; 8718 } else { 8719 if (op == BO_LT || op == BO_LE) 8720 IsTrue = !PositiveConstant; 8721 else // op == BO_GT || op == BO_GE 8722 IsTrue = PositiveConstant; 8723 } 8724 } else { 8725 // Other isKnownToHaveBooleanValue 8726 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 8727 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 8728 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 8729 8730 static const struct LinkedConditions { 8731 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 8732 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 8733 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 8734 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 8735 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 8736 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 8737 8738 } TruthTable = { 8739 // Constant on LHS. | Constant on RHS. | 8740 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 8741 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 8742 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 8743 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 8744 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 8745 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 8746 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 8747 }; 8748 8749 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 8750 8751 enum ConstantValue ConstVal = Zero; 8752 if (Value.isUnsigned() || Value.isNonNegative()) { 8753 if (Value == 0) { 8754 LiteralOrBoolConstant = 8755 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 8756 ConstVal = Zero; 8757 } else if (Value == 1) { 8758 LiteralOrBoolConstant = 8759 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 8760 ConstVal = One; 8761 } else { 8762 LiteralOrBoolConstant = LiteralConstant; 8763 ConstVal = GT_One; 8764 } 8765 } else { 8766 ConstVal = LT_Zero; 8767 } 8768 8769 CompareBoolWithConstantResult CmpRes; 8770 8771 switch (op) { 8772 case BO_LT: 8773 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 8774 break; 8775 case BO_GT: 8776 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 8777 break; 8778 case BO_LE: 8779 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 8780 break; 8781 case BO_GE: 8782 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 8783 break; 8784 case BO_EQ: 8785 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 8786 break; 8787 case BO_NE: 8788 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 8789 break; 8790 default: 8791 CmpRes = Unkwn; 8792 break; 8793 } 8794 8795 if (CmpRes == AFals) { 8796 IsTrue = false; 8797 } else if (CmpRes == ATrue) { 8798 IsTrue = true; 8799 } else { 8800 return; 8801 } 8802 } 8803 8804 // If this is a comparison to an enum constant, include that 8805 // constant in the diagnostic. 8806 const EnumConstantDecl *ED = nullptr; 8807 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 8808 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 8809 8810 SmallString<64> PrettySourceValue; 8811 llvm::raw_svector_ostream OS(PrettySourceValue); 8812 if (ED) 8813 OS << '\'' << *ED << "' (" << Value << ")"; 8814 else 8815 OS << Value; 8816 8817 S.DiagRuntimeBehavior( 8818 E->getOperatorLoc(), E, 8819 S.PDiag(diag::warn_out_of_range_compare) 8820 << OS.str() << LiteralOrBoolConstant 8821 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 8822 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 8823 } 8824 8825 /// Analyze the operands of the given comparison. Implements the 8826 /// fallback case from AnalyzeComparison. 8827 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 8828 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8829 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8830 } 8831 8832 /// \brief Implements -Wsign-compare. 8833 /// 8834 /// \param E the binary operator to check for warnings 8835 void AnalyzeComparison(Sema &S, BinaryOperator *E) { 8836 // The type the comparison is being performed in. 8837 QualType T = E->getLHS()->getType(); 8838 8839 // Only analyze comparison operators where both sides have been converted to 8840 // the same type. 8841 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 8842 return AnalyzeImpConvsInComparison(S, E); 8843 8844 // Don't analyze value-dependent comparisons directly. 8845 if (E->isValueDependent()) 8846 return AnalyzeImpConvsInComparison(S, E); 8847 8848 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 8849 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 8850 8851 bool IsComparisonConstant = false; 8852 8853 // Check whether an integer constant comparison results in a value 8854 // of 'true' or 'false'. 8855 if (T->isIntegralType(S.Context)) { 8856 llvm::APSInt RHSValue; 8857 bool IsRHSIntegralLiteral = 8858 RHS->isIntegerConstantExpr(RHSValue, S.Context); 8859 llvm::APSInt LHSValue; 8860 bool IsLHSIntegralLiteral = 8861 LHS->isIntegerConstantExpr(LHSValue, S.Context); 8862 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 8863 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 8864 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 8865 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 8866 else 8867 IsComparisonConstant = 8868 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 8869 } else if (!T->hasUnsignedIntegerRepresentation()) 8870 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 8871 8872 // We don't care about value-dependent expressions or expressions 8873 // whose result is a constant. 8874 if (IsComparisonConstant) 8875 return AnalyzeImpConvsInComparison(S, E); 8876 8877 // If this is a tautological comparison, suppress -Wsign-compare. 8878 if (CheckTautologicalComparisonWithZero(S, E)) 8879 return AnalyzeImpConvsInComparison(S, E); 8880 8881 // We don't do anything special if this isn't an unsigned integral 8882 // comparison: we're only interested in integral comparisons, and 8883 // signed comparisons only happen in cases we don't care to warn about. 8884 if (!T->hasUnsignedIntegerRepresentation()) 8885 return AnalyzeImpConvsInComparison(S, E); 8886 8887 // Check to see if one of the (unmodified) operands is of different 8888 // signedness. 8889 Expr *signedOperand, *unsignedOperand; 8890 if (LHS->getType()->hasSignedIntegerRepresentation()) { 8891 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 8892 "unsigned comparison between two signed integer expressions?"); 8893 signedOperand = LHS; 8894 unsignedOperand = RHS; 8895 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 8896 signedOperand = RHS; 8897 unsignedOperand = LHS; 8898 } else { 8899 return AnalyzeImpConvsInComparison(S, E); 8900 } 8901 8902 // Otherwise, calculate the effective range of the signed operand. 8903 IntRange signedRange = GetExprRange(S.Context, signedOperand); 8904 8905 // Go ahead and analyze implicit conversions in the operands. Note 8906 // that we skip the implicit conversions on both sides. 8907 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 8908 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 8909 8910 // If the signed range is non-negative, -Wsign-compare won't fire. 8911 if (signedRange.NonNegative) 8912 return; 8913 8914 // For (in)equality comparisons, if the unsigned operand is a 8915 // constant which cannot collide with a overflowed signed operand, 8916 // then reinterpreting the signed operand as unsigned will not 8917 // change the result of the comparison. 8918 if (E->isEqualityOp()) { 8919 unsigned comparisonWidth = S.Context.getIntWidth(T); 8920 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 8921 8922 // We should never be unable to prove that the unsigned operand is 8923 // non-negative. 8924 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 8925 8926 if (unsignedRange.Width < comparisonWidth) 8927 return; 8928 } 8929 8930 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 8931 S.PDiag(diag::warn_mixed_sign_comparison) 8932 << LHS->getType() << RHS->getType() 8933 << LHS->getSourceRange() << RHS->getSourceRange()); 8934 } 8935 8936 /// Analyzes an attempt to assign the given value to a bitfield. 8937 /// 8938 /// Returns true if there was something fishy about the attempt. 8939 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 8940 SourceLocation InitLoc) { 8941 assert(Bitfield->isBitField()); 8942 if (Bitfield->isInvalidDecl()) 8943 return false; 8944 8945 // White-list bool bitfields. 8946 QualType BitfieldType = Bitfield->getType(); 8947 if (BitfieldType->isBooleanType()) 8948 return false; 8949 8950 if (BitfieldType->isEnumeralType()) { 8951 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 8952 // If the underlying enum type was not explicitly specified as an unsigned 8953 // type and the enum contain only positive values, MSVC++ will cause an 8954 // inconsistency by storing this as a signed type. 8955 if (S.getLangOpts().CPlusPlus11 && 8956 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 8957 BitfieldEnumDecl->getNumPositiveBits() > 0 && 8958 BitfieldEnumDecl->getNumNegativeBits() == 0) { 8959 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 8960 << BitfieldEnumDecl->getNameAsString(); 8961 } 8962 } 8963 8964 if (Bitfield->getType()->isBooleanType()) 8965 return false; 8966 8967 // Ignore value- or type-dependent expressions. 8968 if (Bitfield->getBitWidth()->isValueDependent() || 8969 Bitfield->getBitWidth()->isTypeDependent() || 8970 Init->isValueDependent() || 8971 Init->isTypeDependent()) 8972 return false; 8973 8974 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 8975 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 8976 8977 llvm::APSInt Value; 8978 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 8979 Expr::SE_AllowSideEffects)) { 8980 // The RHS is not constant. If the RHS has an enum type, make sure the 8981 // bitfield is wide enough to hold all the values of the enum without 8982 // truncation. 8983 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 8984 EnumDecl *ED = EnumTy->getDecl(); 8985 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 8986 8987 // Enum types are implicitly signed on Windows, so check if there are any 8988 // negative enumerators to see if the enum was intended to be signed or 8989 // not. 8990 bool SignedEnum = ED->getNumNegativeBits() > 0; 8991 8992 // Check for surprising sign changes when assigning enum values to a 8993 // bitfield of different signedness. If the bitfield is signed and we 8994 // have exactly the right number of bits to store this unsigned enum, 8995 // suggest changing the enum to an unsigned type. This typically happens 8996 // on Windows where unfixed enums always use an underlying type of 'int'. 8997 unsigned DiagID = 0; 8998 if (SignedEnum && !SignedBitfield) { 8999 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 9000 } else if (SignedBitfield && !SignedEnum && 9001 ED->getNumPositiveBits() == FieldWidth) { 9002 DiagID = diag::warn_signed_bitfield_enum_conversion; 9003 } 9004 9005 if (DiagID) { 9006 S.Diag(InitLoc, DiagID) << Bitfield << ED; 9007 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 9008 SourceRange TypeRange = 9009 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 9010 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 9011 << SignedEnum << TypeRange; 9012 } 9013 9014 // Compute the required bitwidth. If the enum has negative values, we need 9015 // one more bit than the normal number of positive bits to represent the 9016 // sign bit. 9017 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 9018 ED->getNumNegativeBits()) 9019 : ED->getNumPositiveBits(); 9020 9021 // Check the bitwidth. 9022 if (BitsNeeded > FieldWidth) { 9023 Expr *WidthExpr = Bitfield->getBitWidth(); 9024 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 9025 << Bitfield << ED; 9026 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 9027 << BitsNeeded << ED << WidthExpr->getSourceRange(); 9028 } 9029 } 9030 9031 return false; 9032 } 9033 9034 unsigned OriginalWidth = Value.getBitWidth(); 9035 9036 if (!Value.isSigned() || Value.isNegative()) 9037 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 9038 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 9039 OriginalWidth = Value.getMinSignedBits(); 9040 9041 if (OriginalWidth <= FieldWidth) 9042 return false; 9043 9044 // Compute the value which the bitfield will contain. 9045 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 9046 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 9047 9048 // Check whether the stored value is equal to the original value. 9049 TruncatedValue = TruncatedValue.extend(OriginalWidth); 9050 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 9051 return false; 9052 9053 // Special-case bitfields of width 1: booleans are naturally 0/1, and 9054 // therefore don't strictly fit into a signed bitfield of width 1. 9055 if (FieldWidth == 1 && Value == 1) 9056 return false; 9057 9058 std::string PrettyValue = Value.toString(10); 9059 std::string PrettyTrunc = TruncatedValue.toString(10); 9060 9061 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 9062 << PrettyValue << PrettyTrunc << OriginalInit->getType() 9063 << Init->getSourceRange(); 9064 9065 return true; 9066 } 9067 9068 /// Analyze the given simple or compound assignment for warning-worthy 9069 /// operations. 9070 void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 9071 // Just recurse on the LHS. 9072 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9073 9074 // We want to recurse on the RHS as normal unless we're assigning to 9075 // a bitfield. 9076 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 9077 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 9078 E->getOperatorLoc())) { 9079 // Recurse, ignoring any implicit conversions on the RHS. 9080 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 9081 E->getOperatorLoc()); 9082 } 9083 } 9084 9085 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9086 } 9087 9088 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9089 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 9090 SourceLocation CContext, unsigned diag, 9091 bool pruneControlFlow = false) { 9092 if (pruneControlFlow) { 9093 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9094 S.PDiag(diag) 9095 << SourceType << T << E->getSourceRange() 9096 << SourceRange(CContext)); 9097 return; 9098 } 9099 S.Diag(E->getExprLoc(), diag) 9100 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 9101 } 9102 9103 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9104 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 9105 unsigned diag, bool pruneControlFlow = false) { 9106 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 9107 } 9108 9109 9110 /// Diagnose an implicit cast from a floating point value to an integer value. 9111 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 9112 9113 SourceLocation CContext) { 9114 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 9115 const bool PruneWarnings = S.inTemplateInstantiation(); 9116 9117 Expr *InnerE = E->IgnoreParenImpCasts(); 9118 // We also want to warn on, e.g., "int i = -1.234" 9119 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 9120 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 9121 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 9122 9123 const bool IsLiteral = 9124 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 9125 9126 llvm::APFloat Value(0.0); 9127 bool IsConstant = 9128 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 9129 if (!IsConstant) { 9130 return DiagnoseImpCast(S, E, T, CContext, 9131 diag::warn_impcast_float_integer, PruneWarnings); 9132 } 9133 9134 bool isExact = false; 9135 9136 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 9137 T->hasUnsignedIntegerRepresentation()); 9138 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 9139 &isExact) == llvm::APFloat::opOK && 9140 isExact) { 9141 if (IsLiteral) return; 9142 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 9143 PruneWarnings); 9144 } 9145 9146 unsigned DiagID = 0; 9147 if (IsLiteral) { 9148 // Warn on floating point literal to integer. 9149 DiagID = diag::warn_impcast_literal_float_to_integer; 9150 } else if (IntegerValue == 0) { 9151 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 9152 return DiagnoseImpCast(S, E, T, CContext, 9153 diag::warn_impcast_float_integer, PruneWarnings); 9154 } 9155 // Warn on non-zero to zero conversion. 9156 DiagID = diag::warn_impcast_float_to_integer_zero; 9157 } else { 9158 if (IntegerValue.isUnsigned()) { 9159 if (!IntegerValue.isMaxValue()) { 9160 return DiagnoseImpCast(S, E, T, CContext, 9161 diag::warn_impcast_float_integer, PruneWarnings); 9162 } 9163 } else { // IntegerValue.isSigned() 9164 if (!IntegerValue.isMaxSignedValue() && 9165 !IntegerValue.isMinSignedValue()) { 9166 return DiagnoseImpCast(S, E, T, CContext, 9167 diag::warn_impcast_float_integer, PruneWarnings); 9168 } 9169 } 9170 // Warn on evaluatable floating point expression to integer conversion. 9171 DiagID = diag::warn_impcast_float_to_integer; 9172 } 9173 9174 // FIXME: Force the precision of the source value down so we don't print 9175 // digits which are usually useless (we don't really care here if we 9176 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 9177 // would automatically print the shortest representation, but it's a bit 9178 // tricky to implement. 9179 SmallString<16> PrettySourceValue; 9180 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 9181 precision = (precision * 59 + 195) / 196; 9182 Value.toString(PrettySourceValue, precision); 9183 9184 SmallString<16> PrettyTargetValue; 9185 if (IsBool) 9186 PrettyTargetValue = Value.isZero() ? "false" : "true"; 9187 else 9188 IntegerValue.toString(PrettyTargetValue); 9189 9190 if (PruneWarnings) { 9191 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9192 S.PDiag(DiagID) 9193 << E->getType() << T.getUnqualifiedType() 9194 << PrettySourceValue << PrettyTargetValue 9195 << E->getSourceRange() << SourceRange(CContext)); 9196 } else { 9197 S.Diag(E->getExprLoc(), DiagID) 9198 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 9199 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 9200 } 9201 } 9202 9203 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 9204 if (!Range.Width) return "0"; 9205 9206 llvm::APSInt ValueInRange = Value; 9207 ValueInRange.setIsSigned(!Range.NonNegative); 9208 ValueInRange = ValueInRange.trunc(Range.Width); 9209 return ValueInRange.toString(10); 9210 } 9211 9212 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 9213 if (!isa<ImplicitCastExpr>(Ex)) 9214 return false; 9215 9216 Expr *InnerE = Ex->IgnoreParenImpCasts(); 9217 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 9218 const Type *Source = 9219 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 9220 if (Target->isDependentType()) 9221 return false; 9222 9223 const BuiltinType *FloatCandidateBT = 9224 dyn_cast<BuiltinType>(ToBool ? Source : Target); 9225 const Type *BoolCandidateType = ToBool ? Target : Source; 9226 9227 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 9228 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 9229 } 9230 9231 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 9232 SourceLocation CC) { 9233 unsigned NumArgs = TheCall->getNumArgs(); 9234 for (unsigned i = 0; i < NumArgs; ++i) { 9235 Expr *CurrA = TheCall->getArg(i); 9236 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 9237 continue; 9238 9239 bool IsSwapped = ((i > 0) && 9240 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 9241 IsSwapped |= ((i < (NumArgs - 1)) && 9242 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 9243 if (IsSwapped) { 9244 // Warn on this floating-point to bool conversion. 9245 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 9246 CurrA->getType(), CC, 9247 diag::warn_impcast_floating_point_to_bool); 9248 } 9249 } 9250 } 9251 9252 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) { 9253 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 9254 E->getExprLoc())) 9255 return; 9256 9257 // Don't warn on functions which have return type nullptr_t. 9258 if (isa<CallExpr>(E)) 9259 return; 9260 9261 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 9262 const Expr::NullPointerConstantKind NullKind = 9263 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 9264 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 9265 return; 9266 9267 // Return if target type is a safe conversion. 9268 if (T->isAnyPointerType() || T->isBlockPointerType() || 9269 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 9270 return; 9271 9272 SourceLocation Loc = E->getSourceRange().getBegin(); 9273 9274 // Venture through the macro stacks to get to the source of macro arguments. 9275 // The new location is a better location than the complete location that was 9276 // passed in. 9277 while (S.SourceMgr.isMacroArgExpansion(Loc)) 9278 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); 9279 9280 while (S.SourceMgr.isMacroArgExpansion(CC)) 9281 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); 9282 9283 // __null is usually wrapped in a macro. Go up a macro if that is the case. 9284 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 9285 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 9286 Loc, S.SourceMgr, S.getLangOpts()); 9287 if (MacroName == "NULL") 9288 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 9289 } 9290 9291 // Only warn if the null and context location are in the same macro expansion. 9292 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 9293 return; 9294 9295 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 9296 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) 9297 << FixItHint::CreateReplacement(Loc, 9298 S.getFixItZeroLiteralForType(T, Loc)); 9299 } 9300 9301 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9302 ObjCArrayLiteral *ArrayLiteral); 9303 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9304 ObjCDictionaryLiteral *DictionaryLiteral); 9305 9306 /// Check a single element within a collection literal against the 9307 /// target element type. 9308 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, 9309 Expr *Element, unsigned ElementKind) { 9310 // Skip a bitcast to 'id' or qualified 'id'. 9311 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 9312 if (ICE->getCastKind() == CK_BitCast && 9313 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 9314 Element = ICE->getSubExpr(); 9315 } 9316 9317 QualType ElementType = Element->getType(); 9318 ExprResult ElementResult(Element); 9319 if (ElementType->getAs<ObjCObjectPointerType>() && 9320 S.CheckSingleAssignmentConstraints(TargetElementType, 9321 ElementResult, 9322 false, false) 9323 != Sema::Compatible) { 9324 S.Diag(Element->getLocStart(), 9325 diag::warn_objc_collection_literal_element) 9326 << ElementType << ElementKind << TargetElementType 9327 << Element->getSourceRange(); 9328 } 9329 9330 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 9331 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 9332 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 9333 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 9334 } 9335 9336 /// Check an Objective-C array literal being converted to the given 9337 /// target type. 9338 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 9339 ObjCArrayLiteral *ArrayLiteral) { 9340 if (!S.NSArrayDecl) 9341 return; 9342 9343 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9344 if (!TargetObjCPtr) 9345 return; 9346 9347 if (TargetObjCPtr->isUnspecialized() || 9348 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9349 != S.NSArrayDecl->getCanonicalDecl()) 9350 return; 9351 9352 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9353 if (TypeArgs.size() != 1) 9354 return; 9355 9356 QualType TargetElementType = TypeArgs[0]; 9357 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 9358 checkObjCCollectionLiteralElement(S, TargetElementType, 9359 ArrayLiteral->getElement(I), 9360 0); 9361 } 9362 } 9363 9364 /// Check an Objective-C dictionary literal being converted to the given 9365 /// target type. 9366 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 9367 ObjCDictionaryLiteral *DictionaryLiteral) { 9368 if (!S.NSDictionaryDecl) 9369 return; 9370 9371 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 9372 if (!TargetObjCPtr) 9373 return; 9374 9375 if (TargetObjCPtr->isUnspecialized() || 9376 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 9377 != S.NSDictionaryDecl->getCanonicalDecl()) 9378 return; 9379 9380 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 9381 if (TypeArgs.size() != 2) 9382 return; 9383 9384 QualType TargetKeyType = TypeArgs[0]; 9385 QualType TargetObjectType = TypeArgs[1]; 9386 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 9387 auto Element = DictionaryLiteral->getKeyValueElement(I); 9388 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 9389 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 9390 } 9391 } 9392 9393 // Helper function to filter out cases for constant width constant conversion. 9394 // Don't warn on char array initialization or for non-decimal values. 9395 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 9396 SourceLocation CC) { 9397 // If initializing from a constant, and the constant starts with '0', 9398 // then it is a binary, octal, or hexadecimal. Allow these constants 9399 // to fill all the bits, even if there is a sign change. 9400 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 9401 const char FirstLiteralCharacter = 9402 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 9403 if (FirstLiteralCharacter == '0') 9404 return false; 9405 } 9406 9407 // If the CC location points to a '{', and the type is char, then assume 9408 // assume it is an array initialization. 9409 if (CC.isValid() && T->isCharType()) { 9410 const char FirstContextCharacter = 9411 S.getSourceManager().getCharacterData(CC)[0]; 9412 if (FirstContextCharacter == '{') 9413 return false; 9414 } 9415 9416 return true; 9417 } 9418 9419 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 9420 SourceLocation CC, bool *ICContext = nullptr) { 9421 if (E->isTypeDependent() || E->isValueDependent()) return; 9422 9423 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 9424 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 9425 if (Source == Target) return; 9426 if (Target->isDependentType()) return; 9427 9428 // If the conversion context location is invalid don't complain. We also 9429 // don't want to emit a warning if the issue occurs from the expansion of 9430 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 9431 // delay this check as long as possible. Once we detect we are in that 9432 // scenario, we just return. 9433 if (CC.isInvalid()) 9434 return; 9435 9436 // Diagnose implicit casts to bool. 9437 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 9438 if (isa<StringLiteral>(E)) 9439 // Warn on string literal to bool. Checks for string literals in logical 9440 // and expressions, for instance, assert(0 && "error here"), are 9441 // prevented by a check in AnalyzeImplicitConversions(). 9442 return DiagnoseImpCast(S, E, T, CC, 9443 diag::warn_impcast_string_literal_to_bool); 9444 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 9445 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 9446 // This covers the literal expressions that evaluate to Objective-C 9447 // objects. 9448 return DiagnoseImpCast(S, E, T, CC, 9449 diag::warn_impcast_objective_c_literal_to_bool); 9450 } 9451 if (Source->isPointerType() || Source->canDecayToPointerType()) { 9452 // Warn on pointer to bool conversion that is always true. 9453 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 9454 SourceRange(CC)); 9455 } 9456 } 9457 9458 // Check implicit casts from Objective-C collection literals to specialized 9459 // collection types, e.g., NSArray<NSString *> *. 9460 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 9461 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 9462 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 9463 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 9464 9465 // Strip vector types. 9466 if (isa<VectorType>(Source)) { 9467 if (!isa<VectorType>(Target)) { 9468 if (S.SourceMgr.isInSystemMacro(CC)) 9469 return; 9470 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 9471 } 9472 9473 // If the vector cast is cast between two vectors of the same size, it is 9474 // a bitcast, not a conversion. 9475 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 9476 return; 9477 9478 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 9479 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 9480 } 9481 if (auto VecTy = dyn_cast<VectorType>(Target)) 9482 Target = VecTy->getElementType().getTypePtr(); 9483 9484 // Strip complex types. 9485 if (isa<ComplexType>(Source)) { 9486 if (!isa<ComplexType>(Target)) { 9487 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 9488 return; 9489 9490 return DiagnoseImpCast(S, E, T, CC, 9491 S.getLangOpts().CPlusPlus 9492 ? diag::err_impcast_complex_scalar 9493 : diag::warn_impcast_complex_scalar); 9494 } 9495 9496 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 9497 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 9498 } 9499 9500 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 9501 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 9502 9503 // If the source is floating point... 9504 if (SourceBT && SourceBT->isFloatingPoint()) { 9505 // ...and the target is floating point... 9506 if (TargetBT && TargetBT->isFloatingPoint()) { 9507 // ...then warn if we're dropping FP rank. 9508 9509 // Builtin FP kinds are ordered by increasing FP rank. 9510 if (SourceBT->getKind() > TargetBT->getKind()) { 9511 // Don't warn about float constants that are precisely 9512 // representable in the target type. 9513 Expr::EvalResult result; 9514 if (E->EvaluateAsRValue(result, S.Context)) { 9515 // Value might be a float, a float vector, or a float complex. 9516 if (IsSameFloatAfterCast(result.Val, 9517 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 9518 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 9519 return; 9520 } 9521 9522 if (S.SourceMgr.isInSystemMacro(CC)) 9523 return; 9524 9525 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 9526 } 9527 // ... or possibly if we're increasing rank, too 9528 else if (TargetBT->getKind() > SourceBT->getKind()) { 9529 if (S.SourceMgr.isInSystemMacro(CC)) 9530 return; 9531 9532 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 9533 } 9534 return; 9535 } 9536 9537 // If the target is integral, always warn. 9538 if (TargetBT && TargetBT->isInteger()) { 9539 if (S.SourceMgr.isInSystemMacro(CC)) 9540 return; 9541 9542 DiagnoseFloatingImpCast(S, E, T, CC); 9543 } 9544 9545 // Detect the case where a call result is converted from floating-point to 9546 // to bool, and the final argument to the call is converted from bool, to 9547 // discover this typo: 9548 // 9549 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 9550 // 9551 // FIXME: This is an incredibly special case; is there some more general 9552 // way to detect this class of misplaced-parentheses bug? 9553 if (Target->isBooleanType() && isa<CallExpr>(E)) { 9554 // Check last argument of function call to see if it is an 9555 // implicit cast from a type matching the type the result 9556 // is being cast to. 9557 CallExpr *CEx = cast<CallExpr>(E); 9558 if (unsigned NumArgs = CEx->getNumArgs()) { 9559 Expr *LastA = CEx->getArg(NumArgs - 1); 9560 Expr *InnerE = LastA->IgnoreParenImpCasts(); 9561 if (isa<ImplicitCastExpr>(LastA) && 9562 InnerE->getType()->isBooleanType()) { 9563 // Warn on this floating-point to bool conversion 9564 DiagnoseImpCast(S, E, T, CC, 9565 diag::warn_impcast_floating_point_to_bool); 9566 } 9567 } 9568 } 9569 return; 9570 } 9571 9572 DiagnoseNullConversion(S, E, T, CC); 9573 9574 S.DiscardMisalignedMemberAddress(Target, E); 9575 9576 if (!Source->isIntegerType() || !Target->isIntegerType()) 9577 return; 9578 9579 // TODO: remove this early return once the false positives for constant->bool 9580 // in templates, macros, etc, are reduced or removed. 9581 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 9582 return; 9583 9584 IntRange SourceRange = GetExprRange(S.Context, E); 9585 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 9586 9587 if (SourceRange.Width > TargetRange.Width) { 9588 // If the source is a constant, use a default-on diagnostic. 9589 // TODO: this should happen for bitfield stores, too. 9590 llvm::APSInt Value(32); 9591 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 9592 if (S.SourceMgr.isInSystemMacro(CC)) 9593 return; 9594 9595 std::string PrettySourceValue = Value.toString(10); 9596 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9597 9598 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9599 S.PDiag(diag::warn_impcast_integer_precision_constant) 9600 << PrettySourceValue << PrettyTargetValue 9601 << E->getType() << T << E->getSourceRange() 9602 << clang::SourceRange(CC)); 9603 return; 9604 } 9605 9606 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 9607 if (S.SourceMgr.isInSystemMacro(CC)) 9608 return; 9609 9610 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 9611 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 9612 /* pruneControlFlow */ true); 9613 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 9614 } 9615 9616 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 9617 SourceRange.NonNegative && Source->isSignedIntegerType()) { 9618 // Warn when doing a signed to signed conversion, warn if the positive 9619 // source value is exactly the width of the target type, which will 9620 // cause a negative value to be stored. 9621 9622 llvm::APSInt Value; 9623 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 9624 !S.SourceMgr.isInSystemMacro(CC)) { 9625 if (isSameWidthConstantConversion(S, E, T, CC)) { 9626 std::string PrettySourceValue = Value.toString(10); 9627 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9628 9629 S.DiagRuntimeBehavior( 9630 E->getExprLoc(), E, 9631 S.PDiag(diag::warn_impcast_integer_precision_constant) 9632 << PrettySourceValue << PrettyTargetValue << E->getType() << T 9633 << E->getSourceRange() << clang::SourceRange(CC)); 9634 return; 9635 } 9636 } 9637 9638 // Fall through for non-constants to give a sign conversion warning. 9639 } 9640 9641 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 9642 (!TargetRange.NonNegative && SourceRange.NonNegative && 9643 SourceRange.Width == TargetRange.Width)) { 9644 if (S.SourceMgr.isInSystemMacro(CC)) 9645 return; 9646 9647 unsigned DiagID = diag::warn_impcast_integer_sign; 9648 9649 // Traditionally, gcc has warned about this under -Wsign-compare. 9650 // We also want to warn about it in -Wconversion. 9651 // So if -Wconversion is off, use a completely identical diagnostic 9652 // in the sign-compare group. 9653 // The conditional-checking code will 9654 if (ICContext) { 9655 DiagID = diag::warn_impcast_integer_sign_conditional; 9656 *ICContext = true; 9657 } 9658 9659 return DiagnoseImpCast(S, E, T, CC, DiagID); 9660 } 9661 9662 // Diagnose conversions between different enumeration types. 9663 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 9664 // type, to give us better diagnostics. 9665 QualType SourceType = E->getType(); 9666 if (!S.getLangOpts().CPlusPlus) { 9667 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9668 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 9669 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 9670 SourceType = S.Context.getTypeDeclType(Enum); 9671 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 9672 } 9673 } 9674 9675 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 9676 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 9677 if (SourceEnum->getDecl()->hasNameForLinkage() && 9678 TargetEnum->getDecl()->hasNameForLinkage() && 9679 SourceEnum != TargetEnum) { 9680 if (S.SourceMgr.isInSystemMacro(CC)) 9681 return; 9682 9683 return DiagnoseImpCast(S, E, SourceType, T, CC, 9684 diag::warn_impcast_different_enum_types); 9685 } 9686 } 9687 9688 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9689 SourceLocation CC, QualType T); 9690 9691 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 9692 SourceLocation CC, bool &ICContext) { 9693 E = E->IgnoreParenImpCasts(); 9694 9695 if (isa<ConditionalOperator>(E)) 9696 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 9697 9698 AnalyzeImplicitConversions(S, E, CC); 9699 if (E->getType() != T) 9700 return CheckImplicitConversion(S, E, T, CC, &ICContext); 9701 } 9702 9703 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9704 SourceLocation CC, QualType T) { 9705 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 9706 9707 bool Suspicious = false; 9708 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 9709 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 9710 9711 // If -Wconversion would have warned about either of the candidates 9712 // for a signedness conversion to the context type... 9713 if (!Suspicious) return; 9714 9715 // ...but it's currently ignored... 9716 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 9717 return; 9718 9719 // ...then check whether it would have warned about either of the 9720 // candidates for a signedness conversion to the condition type. 9721 if (E->getType() == T) return; 9722 9723 Suspicious = false; 9724 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 9725 E->getType(), CC, &Suspicious); 9726 if (!Suspicious) 9727 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 9728 E->getType(), CC, &Suspicious); 9729 } 9730 9731 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9732 /// Input argument E is a logical expression. 9733 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 9734 if (S.getLangOpts().Bool) 9735 return; 9736 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 9737 } 9738 9739 /// AnalyzeImplicitConversions - Find and report any interesting 9740 /// implicit conversions in the given expression. There are a couple 9741 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 9742 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 9743 QualType T = OrigE->getType(); 9744 Expr *E = OrigE->IgnoreParenImpCasts(); 9745 9746 if (E->isTypeDependent() || E->isValueDependent()) 9747 return; 9748 9749 // For conditional operators, we analyze the arguments as if they 9750 // were being fed directly into the output. 9751 if (isa<ConditionalOperator>(E)) { 9752 ConditionalOperator *CO = cast<ConditionalOperator>(E); 9753 CheckConditionalOperator(S, CO, CC, T); 9754 return; 9755 } 9756 9757 // Check implicit argument conversions for function calls. 9758 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 9759 CheckImplicitArgumentConversions(S, Call, CC); 9760 9761 // Go ahead and check any implicit conversions we might have skipped. 9762 // The non-canonical typecheck is just an optimization; 9763 // CheckImplicitConversion will filter out dead implicit conversions. 9764 if (E->getType() != T) 9765 CheckImplicitConversion(S, E, T, CC); 9766 9767 // Now continue drilling into this expression. 9768 9769 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 9770 // The bound subexpressions in a PseudoObjectExpr are not reachable 9771 // as transitive children. 9772 // FIXME: Use a more uniform representation for this. 9773 for (auto *SE : POE->semantics()) 9774 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 9775 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 9776 } 9777 9778 // Skip past explicit casts. 9779 if (isa<ExplicitCastExpr>(E)) { 9780 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 9781 return AnalyzeImplicitConversions(S, E, CC); 9782 } 9783 9784 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9785 // Do a somewhat different check with comparison operators. 9786 if (BO->isComparisonOp()) 9787 return AnalyzeComparison(S, BO); 9788 9789 // And with simple assignments. 9790 if (BO->getOpcode() == BO_Assign) 9791 return AnalyzeAssignment(S, BO); 9792 } 9793 9794 // These break the otherwise-useful invariant below. Fortunately, 9795 // we don't really need to recurse into them, because any internal 9796 // expressions should have been analyzed already when they were 9797 // built into statements. 9798 if (isa<StmtExpr>(E)) return; 9799 9800 // Don't descend into unevaluated contexts. 9801 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 9802 9803 // Now just recurse over the expression's children. 9804 CC = E->getExprLoc(); 9805 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 9806 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 9807 for (Stmt *SubStmt : E->children()) { 9808 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 9809 if (!ChildExpr) 9810 continue; 9811 9812 if (IsLogicalAndOperator && 9813 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 9814 // Ignore checking string literals that are in logical and operators. 9815 // This is a common pattern for asserts. 9816 continue; 9817 AnalyzeImplicitConversions(S, ChildExpr, CC); 9818 } 9819 9820 if (BO && BO->isLogicalOp()) { 9821 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 9822 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9823 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9824 9825 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 9826 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9827 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9828 } 9829 9830 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 9831 if (U->getOpcode() == UO_LNot) 9832 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 9833 } 9834 9835 } // end anonymous namespace 9836 9837 /// Diagnose integer type and any valid implicit convertion to it. 9838 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 9839 // Taking into account implicit conversions, 9840 // allow any integer. 9841 if (!E->getType()->isIntegerType()) { 9842 S.Diag(E->getLocStart(), 9843 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 9844 return true; 9845 } 9846 // Potentially emit standard warnings for implicit conversions if enabled 9847 // using -Wconversion. 9848 CheckImplicitConversion(S, E, IntT, E->getLocStart()); 9849 return false; 9850 } 9851 9852 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 9853 // Returns true when emitting a warning about taking the address of a reference. 9854 static bool CheckForReference(Sema &SemaRef, const Expr *E, 9855 const PartialDiagnostic &PD) { 9856 E = E->IgnoreParenImpCasts(); 9857 9858 const FunctionDecl *FD = nullptr; 9859 9860 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9861 if (!DRE->getDecl()->getType()->isReferenceType()) 9862 return false; 9863 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9864 if (!M->getMemberDecl()->getType()->isReferenceType()) 9865 return false; 9866 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 9867 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 9868 return false; 9869 FD = Call->getDirectCallee(); 9870 } else { 9871 return false; 9872 } 9873 9874 SemaRef.Diag(E->getExprLoc(), PD); 9875 9876 // If possible, point to location of function. 9877 if (FD) { 9878 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 9879 } 9880 9881 return true; 9882 } 9883 9884 // Returns true if the SourceLocation is expanded from any macro body. 9885 // Returns false if the SourceLocation is invalid, is from not in a macro 9886 // expansion, or is from expanded from a top-level macro argument. 9887 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 9888 if (Loc.isInvalid()) 9889 return false; 9890 9891 while (Loc.isMacroID()) { 9892 if (SM.isMacroBodyExpansion(Loc)) 9893 return true; 9894 Loc = SM.getImmediateMacroCallerLoc(Loc); 9895 } 9896 9897 return false; 9898 } 9899 9900 /// \brief Diagnose pointers that are always non-null. 9901 /// \param E the expression containing the pointer 9902 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 9903 /// compared to a null pointer 9904 /// \param IsEqual True when the comparison is equal to a null pointer 9905 /// \param Range Extra SourceRange to highlight in the diagnostic 9906 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 9907 Expr::NullPointerConstantKind NullKind, 9908 bool IsEqual, SourceRange Range) { 9909 if (!E) 9910 return; 9911 9912 // Don't warn inside macros. 9913 if (E->getExprLoc().isMacroID()) { 9914 const SourceManager &SM = getSourceManager(); 9915 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 9916 IsInAnyMacroBody(SM, Range.getBegin())) 9917 return; 9918 } 9919 E = E->IgnoreImpCasts(); 9920 9921 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 9922 9923 if (isa<CXXThisExpr>(E)) { 9924 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 9925 : diag::warn_this_bool_conversion; 9926 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 9927 return; 9928 } 9929 9930 bool IsAddressOf = false; 9931 9932 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9933 if (UO->getOpcode() != UO_AddrOf) 9934 return; 9935 IsAddressOf = true; 9936 E = UO->getSubExpr(); 9937 } 9938 9939 if (IsAddressOf) { 9940 unsigned DiagID = IsCompare 9941 ? diag::warn_address_of_reference_null_compare 9942 : diag::warn_address_of_reference_bool_conversion; 9943 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 9944 << IsEqual; 9945 if (CheckForReference(*this, E, PD)) { 9946 return; 9947 } 9948 } 9949 9950 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 9951 bool IsParam = isa<NonNullAttr>(NonnullAttr); 9952 std::string Str; 9953 llvm::raw_string_ostream S(Str); 9954 E->printPretty(S, nullptr, getPrintingPolicy()); 9955 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 9956 : diag::warn_cast_nonnull_to_bool; 9957 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 9958 << E->getSourceRange() << Range << IsEqual; 9959 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 9960 }; 9961 9962 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 9963 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 9964 if (auto *Callee = Call->getDirectCallee()) { 9965 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 9966 ComplainAboutNonnullParamOrCall(A); 9967 return; 9968 } 9969 } 9970 } 9971 9972 // Expect to find a single Decl. Skip anything more complicated. 9973 ValueDecl *D = nullptr; 9974 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 9975 D = R->getDecl(); 9976 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9977 D = M->getMemberDecl(); 9978 } 9979 9980 // Weak Decls can be null. 9981 if (!D || D->isWeak()) 9982 return; 9983 9984 // Check for parameter decl with nonnull attribute 9985 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 9986 if (getCurFunction() && 9987 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 9988 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 9989 ComplainAboutNonnullParamOrCall(A); 9990 return; 9991 } 9992 9993 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 9994 auto ParamIter = llvm::find(FD->parameters(), PV); 9995 assert(ParamIter != FD->param_end()); 9996 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 9997 9998 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 9999 if (!NonNull->args_size()) { 10000 ComplainAboutNonnullParamOrCall(NonNull); 10001 return; 10002 } 10003 10004 for (unsigned ArgNo : NonNull->args()) { 10005 if (ArgNo == ParamNo) { 10006 ComplainAboutNonnullParamOrCall(NonNull); 10007 return; 10008 } 10009 } 10010 } 10011 } 10012 } 10013 } 10014 10015 QualType T = D->getType(); 10016 const bool IsArray = T->isArrayType(); 10017 const bool IsFunction = T->isFunctionType(); 10018 10019 // Address of function is used to silence the function warning. 10020 if (IsAddressOf && IsFunction) { 10021 return; 10022 } 10023 10024 // Found nothing. 10025 if (!IsAddressOf && !IsFunction && !IsArray) 10026 return; 10027 10028 // Pretty print the expression for the diagnostic. 10029 std::string Str; 10030 llvm::raw_string_ostream S(Str); 10031 E->printPretty(S, nullptr, getPrintingPolicy()); 10032 10033 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 10034 : diag::warn_impcast_pointer_to_bool; 10035 enum { 10036 AddressOf, 10037 FunctionPointer, 10038 ArrayPointer 10039 } DiagType; 10040 if (IsAddressOf) 10041 DiagType = AddressOf; 10042 else if (IsFunction) 10043 DiagType = FunctionPointer; 10044 else if (IsArray) 10045 DiagType = ArrayPointer; 10046 else 10047 llvm_unreachable("Could not determine diagnostic."); 10048 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 10049 << Range << IsEqual; 10050 10051 if (!IsFunction) 10052 return; 10053 10054 // Suggest '&' to silence the function warning. 10055 Diag(E->getExprLoc(), diag::note_function_warning_silence) 10056 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 10057 10058 // Check to see if '()' fixit should be emitted. 10059 QualType ReturnType; 10060 UnresolvedSet<4> NonTemplateOverloads; 10061 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 10062 if (ReturnType.isNull()) 10063 return; 10064 10065 if (IsCompare) { 10066 // There are two cases here. If there is null constant, the only suggest 10067 // for a pointer return type. If the null is 0, then suggest if the return 10068 // type is a pointer or an integer type. 10069 if (!ReturnType->isPointerType()) { 10070 if (NullKind == Expr::NPCK_ZeroExpression || 10071 NullKind == Expr::NPCK_ZeroLiteral) { 10072 if (!ReturnType->isIntegerType()) 10073 return; 10074 } else { 10075 return; 10076 } 10077 } 10078 } else { // !IsCompare 10079 // For function to bool, only suggest if the function pointer has bool 10080 // return type. 10081 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 10082 return; 10083 } 10084 Diag(E->getExprLoc(), diag::note_function_to_function_call) 10085 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 10086 } 10087 10088 /// Diagnoses "dangerous" implicit conversions within the given 10089 /// expression (which is a full expression). Implements -Wconversion 10090 /// and -Wsign-compare. 10091 /// 10092 /// \param CC the "context" location of the implicit conversion, i.e. 10093 /// the most location of the syntactic entity requiring the implicit 10094 /// conversion 10095 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 10096 // Don't diagnose in unevaluated contexts. 10097 if (isUnevaluatedContext()) 10098 return; 10099 10100 // Don't diagnose for value- or type-dependent expressions. 10101 if (E->isTypeDependent() || E->isValueDependent()) 10102 return; 10103 10104 // Check for array bounds violations in cases where the check isn't triggered 10105 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 10106 // ArraySubscriptExpr is on the RHS of a variable initialization. 10107 CheckArrayAccess(E); 10108 10109 // This is not the right CC for (e.g.) a variable initialization. 10110 AnalyzeImplicitConversions(*this, E, CC); 10111 } 10112 10113 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10114 /// Input argument E is a logical expression. 10115 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 10116 ::CheckBoolLikeConversion(*this, E, CC); 10117 } 10118 10119 /// Diagnose when expression is an integer constant expression and its evaluation 10120 /// results in integer overflow 10121 void Sema::CheckForIntOverflow (Expr *E) { 10122 // Use a work list to deal with nested struct initializers. 10123 SmallVector<Expr *, 2> Exprs(1, E); 10124 10125 do { 10126 Expr *E = Exprs.pop_back_val(); 10127 10128 if (isa<BinaryOperator>(E->IgnoreParenCasts())) { 10129 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 10130 continue; 10131 } 10132 10133 if (auto InitList = dyn_cast<InitListExpr>(E)) 10134 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 10135 10136 if (isa<ObjCBoxedExpr>(E)) 10137 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 10138 } while (!Exprs.empty()); 10139 } 10140 10141 namespace { 10142 /// \brief Visitor for expressions which looks for unsequenced operations on the 10143 /// same object. 10144 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 10145 typedef EvaluatedExprVisitor<SequenceChecker> Base; 10146 10147 /// \brief A tree of sequenced regions within an expression. Two regions are 10148 /// unsequenced if one is an ancestor or a descendent of the other. When we 10149 /// finish processing an expression with sequencing, such as a comma 10150 /// expression, we fold its tree nodes into its parent, since they are 10151 /// unsequenced with respect to nodes we will visit later. 10152 class SequenceTree { 10153 struct Value { 10154 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 10155 unsigned Parent : 31; 10156 unsigned Merged : 1; 10157 }; 10158 SmallVector<Value, 8> Values; 10159 10160 public: 10161 /// \brief A region within an expression which may be sequenced with respect 10162 /// to some other region. 10163 class Seq { 10164 explicit Seq(unsigned N) : Index(N) {} 10165 unsigned Index; 10166 friend class SequenceTree; 10167 public: 10168 Seq() : Index(0) {} 10169 }; 10170 10171 SequenceTree() { Values.push_back(Value(0)); } 10172 Seq root() const { return Seq(0); } 10173 10174 /// \brief Create a new sequence of operations, which is an unsequenced 10175 /// subset of \p Parent. This sequence of operations is sequenced with 10176 /// respect to other children of \p Parent. 10177 Seq allocate(Seq Parent) { 10178 Values.push_back(Value(Parent.Index)); 10179 return Seq(Values.size() - 1); 10180 } 10181 10182 /// \brief Merge a sequence of operations into its parent. 10183 void merge(Seq S) { 10184 Values[S.Index].Merged = true; 10185 } 10186 10187 /// \brief Determine whether two operations are unsequenced. This operation 10188 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 10189 /// should have been merged into its parent as appropriate. 10190 bool isUnsequenced(Seq Cur, Seq Old) { 10191 unsigned C = representative(Cur.Index); 10192 unsigned Target = representative(Old.Index); 10193 while (C >= Target) { 10194 if (C == Target) 10195 return true; 10196 C = Values[C].Parent; 10197 } 10198 return false; 10199 } 10200 10201 private: 10202 /// \brief Pick a representative for a sequence. 10203 unsigned representative(unsigned K) { 10204 if (Values[K].Merged) 10205 // Perform path compression as we go. 10206 return Values[K].Parent = representative(Values[K].Parent); 10207 return K; 10208 } 10209 }; 10210 10211 /// An object for which we can track unsequenced uses. 10212 typedef NamedDecl *Object; 10213 10214 /// Different flavors of object usage which we track. We only track the 10215 /// least-sequenced usage of each kind. 10216 enum UsageKind { 10217 /// A read of an object. Multiple unsequenced reads are OK. 10218 UK_Use, 10219 /// A modification of an object which is sequenced before the value 10220 /// computation of the expression, such as ++n in C++. 10221 UK_ModAsValue, 10222 /// A modification of an object which is not sequenced before the value 10223 /// computation of the expression, such as n++. 10224 UK_ModAsSideEffect, 10225 10226 UK_Count = UK_ModAsSideEffect + 1 10227 }; 10228 10229 struct Usage { 10230 Usage() : Use(nullptr), Seq() {} 10231 Expr *Use; 10232 SequenceTree::Seq Seq; 10233 }; 10234 10235 struct UsageInfo { 10236 UsageInfo() : Diagnosed(false) {} 10237 Usage Uses[UK_Count]; 10238 /// Have we issued a diagnostic for this variable already? 10239 bool Diagnosed; 10240 }; 10241 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 10242 10243 Sema &SemaRef; 10244 /// Sequenced regions within the expression. 10245 SequenceTree Tree; 10246 /// Declaration modifications and references which we have seen. 10247 UsageInfoMap UsageMap; 10248 /// The region we are currently within. 10249 SequenceTree::Seq Region; 10250 /// Filled in with declarations which were modified as a side-effect 10251 /// (that is, post-increment operations). 10252 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 10253 /// Expressions to check later. We defer checking these to reduce 10254 /// stack usage. 10255 SmallVectorImpl<Expr *> &WorkList; 10256 10257 /// RAII object wrapping the visitation of a sequenced subexpression of an 10258 /// expression. At the end of this process, the side-effects of the evaluation 10259 /// become sequenced with respect to the value computation of the result, so 10260 /// we downgrade any UK_ModAsSideEffect within the evaluation to 10261 /// UK_ModAsValue. 10262 struct SequencedSubexpression { 10263 SequencedSubexpression(SequenceChecker &Self) 10264 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 10265 Self.ModAsSideEffect = &ModAsSideEffect; 10266 } 10267 ~SequencedSubexpression() { 10268 for (auto &M : llvm::reverse(ModAsSideEffect)) { 10269 UsageInfo &U = Self.UsageMap[M.first]; 10270 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 10271 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 10272 SideEffectUsage = M.second; 10273 } 10274 Self.ModAsSideEffect = OldModAsSideEffect; 10275 } 10276 10277 SequenceChecker &Self; 10278 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 10279 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 10280 }; 10281 10282 /// RAII object wrapping the visitation of a subexpression which we might 10283 /// choose to evaluate as a constant. If any subexpression is evaluated and 10284 /// found to be non-constant, this allows us to suppress the evaluation of 10285 /// the outer expression. 10286 class EvaluationTracker { 10287 public: 10288 EvaluationTracker(SequenceChecker &Self) 10289 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 10290 Self.EvalTracker = this; 10291 } 10292 ~EvaluationTracker() { 10293 Self.EvalTracker = Prev; 10294 if (Prev) 10295 Prev->EvalOK &= EvalOK; 10296 } 10297 10298 bool evaluate(const Expr *E, bool &Result) { 10299 if (!EvalOK || E->isValueDependent()) 10300 return false; 10301 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 10302 return EvalOK; 10303 } 10304 10305 private: 10306 SequenceChecker &Self; 10307 EvaluationTracker *Prev; 10308 bool EvalOK; 10309 } *EvalTracker; 10310 10311 /// \brief Find the object which is produced by the specified expression, 10312 /// if any. 10313 Object getObject(Expr *E, bool Mod) const { 10314 E = E->IgnoreParenCasts(); 10315 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10316 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 10317 return getObject(UO->getSubExpr(), Mod); 10318 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10319 if (BO->getOpcode() == BO_Comma) 10320 return getObject(BO->getRHS(), Mod); 10321 if (Mod && BO->isAssignmentOp()) 10322 return getObject(BO->getLHS(), Mod); 10323 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10324 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 10325 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 10326 return ME->getMemberDecl(); 10327 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10328 // FIXME: If this is a reference, map through to its value. 10329 return DRE->getDecl(); 10330 return nullptr; 10331 } 10332 10333 /// \brief Note that an object was modified or used by an expression. 10334 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 10335 Usage &U = UI.Uses[UK]; 10336 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 10337 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 10338 ModAsSideEffect->push_back(std::make_pair(O, U)); 10339 U.Use = Ref; 10340 U.Seq = Region; 10341 } 10342 } 10343 /// \brief Check whether a modification or use conflicts with a prior usage. 10344 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 10345 bool IsModMod) { 10346 if (UI.Diagnosed) 10347 return; 10348 10349 const Usage &U = UI.Uses[OtherKind]; 10350 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 10351 return; 10352 10353 Expr *Mod = U.Use; 10354 Expr *ModOrUse = Ref; 10355 if (OtherKind == UK_Use) 10356 std::swap(Mod, ModOrUse); 10357 10358 SemaRef.Diag(Mod->getExprLoc(), 10359 IsModMod ? diag::warn_unsequenced_mod_mod 10360 : diag::warn_unsequenced_mod_use) 10361 << O << SourceRange(ModOrUse->getExprLoc()); 10362 UI.Diagnosed = true; 10363 } 10364 10365 void notePreUse(Object O, Expr *Use) { 10366 UsageInfo &U = UsageMap[O]; 10367 // Uses conflict with other modifications. 10368 checkUsage(O, U, Use, UK_ModAsValue, false); 10369 } 10370 void notePostUse(Object O, Expr *Use) { 10371 UsageInfo &U = UsageMap[O]; 10372 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 10373 addUsage(U, O, Use, UK_Use); 10374 } 10375 10376 void notePreMod(Object O, Expr *Mod) { 10377 UsageInfo &U = UsageMap[O]; 10378 // Modifications conflict with other modifications and with uses. 10379 checkUsage(O, U, Mod, UK_ModAsValue, true); 10380 checkUsage(O, U, Mod, UK_Use, false); 10381 } 10382 void notePostMod(Object O, Expr *Use, UsageKind UK) { 10383 UsageInfo &U = UsageMap[O]; 10384 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 10385 addUsage(U, O, Use, UK); 10386 } 10387 10388 public: 10389 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 10390 : Base(S.Context), SemaRef(S), Region(Tree.root()), 10391 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 10392 Visit(E); 10393 } 10394 10395 void VisitStmt(Stmt *S) { 10396 // Skip all statements which aren't expressions for now. 10397 } 10398 10399 void VisitExpr(Expr *E) { 10400 // By default, just recurse to evaluated subexpressions. 10401 Base::VisitStmt(E); 10402 } 10403 10404 void VisitCastExpr(CastExpr *E) { 10405 Object O = Object(); 10406 if (E->getCastKind() == CK_LValueToRValue) 10407 O = getObject(E->getSubExpr(), false); 10408 10409 if (O) 10410 notePreUse(O, E); 10411 VisitExpr(E); 10412 if (O) 10413 notePostUse(O, E); 10414 } 10415 10416 void VisitBinComma(BinaryOperator *BO) { 10417 // C++11 [expr.comma]p1: 10418 // Every value computation and side effect associated with the left 10419 // expression is sequenced before every value computation and side 10420 // effect associated with the right expression. 10421 SequenceTree::Seq LHS = Tree.allocate(Region); 10422 SequenceTree::Seq RHS = Tree.allocate(Region); 10423 SequenceTree::Seq OldRegion = Region; 10424 10425 { 10426 SequencedSubexpression SeqLHS(*this); 10427 Region = LHS; 10428 Visit(BO->getLHS()); 10429 } 10430 10431 Region = RHS; 10432 Visit(BO->getRHS()); 10433 10434 Region = OldRegion; 10435 10436 // Forget that LHS and RHS are sequenced. They are both unsequenced 10437 // with respect to other stuff. 10438 Tree.merge(LHS); 10439 Tree.merge(RHS); 10440 } 10441 10442 void VisitBinAssign(BinaryOperator *BO) { 10443 // The modification is sequenced after the value computation of the LHS 10444 // and RHS, so check it before inspecting the operands and update the 10445 // map afterwards. 10446 Object O = getObject(BO->getLHS(), true); 10447 if (!O) 10448 return VisitExpr(BO); 10449 10450 notePreMod(O, BO); 10451 10452 // C++11 [expr.ass]p7: 10453 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 10454 // only once. 10455 // 10456 // Therefore, for a compound assignment operator, O is considered used 10457 // everywhere except within the evaluation of E1 itself. 10458 if (isa<CompoundAssignOperator>(BO)) 10459 notePreUse(O, BO); 10460 10461 Visit(BO->getLHS()); 10462 10463 if (isa<CompoundAssignOperator>(BO)) 10464 notePostUse(O, BO); 10465 10466 Visit(BO->getRHS()); 10467 10468 // C++11 [expr.ass]p1: 10469 // the assignment is sequenced [...] before the value computation of the 10470 // assignment expression. 10471 // C11 6.5.16/3 has no such rule. 10472 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10473 : UK_ModAsSideEffect); 10474 } 10475 10476 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 10477 VisitBinAssign(CAO); 10478 } 10479 10480 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10481 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10482 void VisitUnaryPreIncDec(UnaryOperator *UO) { 10483 Object O = getObject(UO->getSubExpr(), true); 10484 if (!O) 10485 return VisitExpr(UO); 10486 10487 notePreMod(O, UO); 10488 Visit(UO->getSubExpr()); 10489 // C++11 [expr.pre.incr]p1: 10490 // the expression ++x is equivalent to x+=1 10491 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10492 : UK_ModAsSideEffect); 10493 } 10494 10495 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10496 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10497 void VisitUnaryPostIncDec(UnaryOperator *UO) { 10498 Object O = getObject(UO->getSubExpr(), true); 10499 if (!O) 10500 return VisitExpr(UO); 10501 10502 notePreMod(O, UO); 10503 Visit(UO->getSubExpr()); 10504 notePostMod(O, UO, UK_ModAsSideEffect); 10505 } 10506 10507 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 10508 void VisitBinLOr(BinaryOperator *BO) { 10509 // The side-effects of the LHS of an '&&' are sequenced before the 10510 // value computation of the RHS, and hence before the value computation 10511 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 10512 // as if they were unconditionally sequenced. 10513 EvaluationTracker Eval(*this); 10514 { 10515 SequencedSubexpression Sequenced(*this); 10516 Visit(BO->getLHS()); 10517 } 10518 10519 bool Result; 10520 if (Eval.evaluate(BO->getLHS(), Result)) { 10521 if (!Result) 10522 Visit(BO->getRHS()); 10523 } else { 10524 // Check for unsequenced operations in the RHS, treating it as an 10525 // entirely separate evaluation. 10526 // 10527 // FIXME: If there are operations in the RHS which are unsequenced 10528 // with respect to operations outside the RHS, and those operations 10529 // are unconditionally evaluated, diagnose them. 10530 WorkList.push_back(BO->getRHS()); 10531 } 10532 } 10533 void VisitBinLAnd(BinaryOperator *BO) { 10534 EvaluationTracker Eval(*this); 10535 { 10536 SequencedSubexpression Sequenced(*this); 10537 Visit(BO->getLHS()); 10538 } 10539 10540 bool Result; 10541 if (Eval.evaluate(BO->getLHS(), Result)) { 10542 if (Result) 10543 Visit(BO->getRHS()); 10544 } else { 10545 WorkList.push_back(BO->getRHS()); 10546 } 10547 } 10548 10549 // Only visit the condition, unless we can be sure which subexpression will 10550 // be chosen. 10551 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 10552 EvaluationTracker Eval(*this); 10553 { 10554 SequencedSubexpression Sequenced(*this); 10555 Visit(CO->getCond()); 10556 } 10557 10558 bool Result; 10559 if (Eval.evaluate(CO->getCond(), Result)) 10560 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 10561 else { 10562 WorkList.push_back(CO->getTrueExpr()); 10563 WorkList.push_back(CO->getFalseExpr()); 10564 } 10565 } 10566 10567 void VisitCallExpr(CallExpr *CE) { 10568 // C++11 [intro.execution]p15: 10569 // When calling a function [...], every value computation and side effect 10570 // associated with any argument expression, or with the postfix expression 10571 // designating the called function, is sequenced before execution of every 10572 // expression or statement in the body of the function [and thus before 10573 // the value computation of its result]. 10574 SequencedSubexpression Sequenced(*this); 10575 Base::VisitCallExpr(CE); 10576 10577 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 10578 } 10579 10580 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 10581 // This is a call, so all subexpressions are sequenced before the result. 10582 SequencedSubexpression Sequenced(*this); 10583 10584 if (!CCE->isListInitialization()) 10585 return VisitExpr(CCE); 10586 10587 // In C++11, list initializations are sequenced. 10588 SmallVector<SequenceTree::Seq, 32> Elts; 10589 SequenceTree::Seq Parent = Region; 10590 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 10591 E = CCE->arg_end(); 10592 I != E; ++I) { 10593 Region = Tree.allocate(Parent); 10594 Elts.push_back(Region); 10595 Visit(*I); 10596 } 10597 10598 // Forget that the initializers are sequenced. 10599 Region = Parent; 10600 for (unsigned I = 0; I < Elts.size(); ++I) 10601 Tree.merge(Elts[I]); 10602 } 10603 10604 void VisitInitListExpr(InitListExpr *ILE) { 10605 if (!SemaRef.getLangOpts().CPlusPlus11) 10606 return VisitExpr(ILE); 10607 10608 // In C++11, list initializations are sequenced. 10609 SmallVector<SequenceTree::Seq, 32> Elts; 10610 SequenceTree::Seq Parent = Region; 10611 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 10612 Expr *E = ILE->getInit(I); 10613 if (!E) continue; 10614 Region = Tree.allocate(Parent); 10615 Elts.push_back(Region); 10616 Visit(E); 10617 } 10618 10619 // Forget that the initializers are sequenced. 10620 Region = Parent; 10621 for (unsigned I = 0; I < Elts.size(); ++I) 10622 Tree.merge(Elts[I]); 10623 } 10624 }; 10625 } // end anonymous namespace 10626 10627 void Sema::CheckUnsequencedOperations(Expr *E) { 10628 SmallVector<Expr *, 8> WorkList; 10629 WorkList.push_back(E); 10630 while (!WorkList.empty()) { 10631 Expr *Item = WorkList.pop_back_val(); 10632 SequenceChecker(*this, Item, WorkList); 10633 } 10634 } 10635 10636 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 10637 bool IsConstexpr) { 10638 CheckImplicitConversions(E, CheckLoc); 10639 if (!E->isInstantiationDependent()) 10640 CheckUnsequencedOperations(E); 10641 if (!IsConstexpr && !E->isValueDependent()) 10642 CheckForIntOverflow(E); 10643 DiagnoseMisalignedMembers(); 10644 } 10645 10646 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 10647 FieldDecl *BitField, 10648 Expr *Init) { 10649 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 10650 } 10651 10652 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 10653 SourceLocation Loc) { 10654 if (!PType->isVariablyModifiedType()) 10655 return; 10656 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 10657 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 10658 return; 10659 } 10660 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 10661 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 10662 return; 10663 } 10664 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 10665 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 10666 return; 10667 } 10668 10669 const ArrayType *AT = S.Context.getAsArrayType(PType); 10670 if (!AT) 10671 return; 10672 10673 if (AT->getSizeModifier() != ArrayType::Star) { 10674 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 10675 return; 10676 } 10677 10678 S.Diag(Loc, diag::err_array_star_in_function_definition); 10679 } 10680 10681 /// CheckParmsForFunctionDef - Check that the parameters of the given 10682 /// function are appropriate for the definition of a function. This 10683 /// takes care of any checks that cannot be performed on the 10684 /// declaration itself, e.g., that the types of each of the function 10685 /// parameters are complete. 10686 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 10687 bool CheckParameterNames) { 10688 bool HasInvalidParm = false; 10689 for (ParmVarDecl *Param : Parameters) { 10690 // C99 6.7.5.3p4: the parameters in a parameter type list in a 10691 // function declarator that is part of a function definition of 10692 // that function shall not have incomplete type. 10693 // 10694 // This is also C++ [dcl.fct]p6. 10695 if (!Param->isInvalidDecl() && 10696 RequireCompleteType(Param->getLocation(), Param->getType(), 10697 diag::err_typecheck_decl_incomplete_type)) { 10698 Param->setInvalidDecl(); 10699 HasInvalidParm = true; 10700 } 10701 10702 // C99 6.9.1p5: If the declarator includes a parameter type list, the 10703 // declaration of each parameter shall include an identifier. 10704 if (CheckParameterNames && 10705 Param->getIdentifier() == nullptr && 10706 !Param->isImplicit() && 10707 !getLangOpts().CPlusPlus) 10708 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10709 10710 // C99 6.7.5.3p12: 10711 // If the function declarator is not part of a definition of that 10712 // function, parameters may have incomplete type and may use the [*] 10713 // notation in their sequences of declarator specifiers to specify 10714 // variable length array types. 10715 QualType PType = Param->getOriginalType(); 10716 // FIXME: This diagnostic should point the '[*]' if source-location 10717 // information is added for it. 10718 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 10719 10720 // MSVC destroys objects passed by value in the callee. Therefore a 10721 // function definition which takes such a parameter must be able to call the 10722 // object's destructor. However, we don't perform any direct access check 10723 // on the dtor. 10724 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 10725 .getCXXABI() 10726 .areArgsDestroyedLeftToRightInCallee()) { 10727 if (!Param->isInvalidDecl()) { 10728 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 10729 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 10730 if (!ClassDecl->isInvalidDecl() && 10731 !ClassDecl->hasIrrelevantDestructor() && 10732 !ClassDecl->isDependentContext()) { 10733 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10734 MarkFunctionReferenced(Param->getLocation(), Destructor); 10735 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 10736 } 10737 } 10738 } 10739 } 10740 10741 // Parameters with the pass_object_size attribute only need to be marked 10742 // constant at function definitions. Because we lack information about 10743 // whether we're on a declaration or definition when we're instantiating the 10744 // attribute, we need to check for constness here. 10745 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 10746 if (!Param->getType().isConstQualified()) 10747 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 10748 << Attr->getSpelling() << 1; 10749 } 10750 10751 return HasInvalidParm; 10752 } 10753 10754 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 10755 /// or MemberExpr. 10756 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 10757 ASTContext &Context) { 10758 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 10759 return Context.getDeclAlign(DRE->getDecl()); 10760 10761 if (const auto *ME = dyn_cast<MemberExpr>(E)) 10762 return Context.getDeclAlign(ME->getMemberDecl()); 10763 10764 return TypeAlign; 10765 } 10766 10767 /// CheckCastAlign - Implements -Wcast-align, which warns when a 10768 /// pointer cast increases the alignment requirements. 10769 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 10770 // This is actually a lot of work to potentially be doing on every 10771 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 10772 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 10773 return; 10774 10775 // Ignore dependent types. 10776 if (T->isDependentType() || Op->getType()->isDependentType()) 10777 return; 10778 10779 // Require that the destination be a pointer type. 10780 const PointerType *DestPtr = T->getAs<PointerType>(); 10781 if (!DestPtr) return; 10782 10783 // If the destination has alignment 1, we're done. 10784 QualType DestPointee = DestPtr->getPointeeType(); 10785 if (DestPointee->isIncompleteType()) return; 10786 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 10787 if (DestAlign.isOne()) return; 10788 10789 // Require that the source be a pointer type. 10790 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 10791 if (!SrcPtr) return; 10792 QualType SrcPointee = SrcPtr->getPointeeType(); 10793 10794 // Whitelist casts from cv void*. We already implicitly 10795 // whitelisted casts to cv void*, since they have alignment 1. 10796 // Also whitelist casts involving incomplete types, which implicitly 10797 // includes 'void'. 10798 if (SrcPointee->isIncompleteType()) return; 10799 10800 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 10801 10802 if (auto *CE = dyn_cast<CastExpr>(Op)) { 10803 if (CE->getCastKind() == CK_ArrayToPointerDecay) 10804 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 10805 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 10806 if (UO->getOpcode() == UO_AddrOf) 10807 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 10808 } 10809 10810 if (SrcAlign >= DestAlign) return; 10811 10812 Diag(TRange.getBegin(), diag::warn_cast_align) 10813 << Op->getType() << T 10814 << static_cast<unsigned>(SrcAlign.getQuantity()) 10815 << static_cast<unsigned>(DestAlign.getQuantity()) 10816 << TRange << Op->getSourceRange(); 10817 } 10818 10819 /// \brief Check whether this array fits the idiom of a size-one tail padded 10820 /// array member of a struct. 10821 /// 10822 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 10823 /// commonly used to emulate flexible arrays in C89 code. 10824 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 10825 const NamedDecl *ND) { 10826 if (Size != 1 || !ND) return false; 10827 10828 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 10829 if (!FD) return false; 10830 10831 // Don't consider sizes resulting from macro expansions or template argument 10832 // substitution to form C89 tail-padded arrays. 10833 10834 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 10835 while (TInfo) { 10836 TypeLoc TL = TInfo->getTypeLoc(); 10837 // Look through typedefs. 10838 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 10839 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 10840 TInfo = TDL->getTypeSourceInfo(); 10841 continue; 10842 } 10843 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 10844 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 10845 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 10846 return false; 10847 } 10848 break; 10849 } 10850 10851 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 10852 if (!RD) return false; 10853 if (RD->isUnion()) return false; 10854 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10855 if (!CRD->isStandardLayout()) return false; 10856 } 10857 10858 // See if this is the last field decl in the record. 10859 const Decl *D = FD; 10860 while ((D = D->getNextDeclInContext())) 10861 if (isa<FieldDecl>(D)) 10862 return false; 10863 return true; 10864 } 10865 10866 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 10867 const ArraySubscriptExpr *ASE, 10868 bool AllowOnePastEnd, bool IndexNegated) { 10869 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 10870 if (IndexExpr->isValueDependent()) 10871 return; 10872 10873 const Type *EffectiveType = 10874 BaseExpr->getType()->getPointeeOrArrayElementType(); 10875 BaseExpr = BaseExpr->IgnoreParenCasts(); 10876 const ConstantArrayType *ArrayTy = 10877 Context.getAsConstantArrayType(BaseExpr->getType()); 10878 if (!ArrayTy) 10879 return; 10880 10881 llvm::APSInt index; 10882 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 10883 return; 10884 if (IndexNegated) 10885 index = -index; 10886 10887 const NamedDecl *ND = nullptr; 10888 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10889 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10890 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10891 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10892 10893 if (index.isUnsigned() || !index.isNegative()) { 10894 llvm::APInt size = ArrayTy->getSize(); 10895 if (!size.isStrictlyPositive()) 10896 return; 10897 10898 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 10899 if (BaseType != EffectiveType) { 10900 // Make sure we're comparing apples to apples when comparing index to size 10901 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 10902 uint64_t array_typesize = Context.getTypeSize(BaseType); 10903 // Handle ptrarith_typesize being zero, such as when casting to void* 10904 if (!ptrarith_typesize) ptrarith_typesize = 1; 10905 if (ptrarith_typesize != array_typesize) { 10906 // There's a cast to a different size type involved 10907 uint64_t ratio = array_typesize / ptrarith_typesize; 10908 // TODO: Be smarter about handling cases where array_typesize is not a 10909 // multiple of ptrarith_typesize 10910 if (ptrarith_typesize * ratio == array_typesize) 10911 size *= llvm::APInt(size.getBitWidth(), ratio); 10912 } 10913 } 10914 10915 if (size.getBitWidth() > index.getBitWidth()) 10916 index = index.zext(size.getBitWidth()); 10917 else if (size.getBitWidth() < index.getBitWidth()) 10918 size = size.zext(index.getBitWidth()); 10919 10920 // For array subscripting the index must be less than size, but for pointer 10921 // arithmetic also allow the index (offset) to be equal to size since 10922 // computing the next address after the end of the array is legal and 10923 // commonly done e.g. in C++ iterators and range-based for loops. 10924 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 10925 return; 10926 10927 // Also don't warn for arrays of size 1 which are members of some 10928 // structure. These are often used to approximate flexible arrays in C89 10929 // code. 10930 if (IsTailPaddedMemberArray(*this, size, ND)) 10931 return; 10932 10933 // Suppress the warning if the subscript expression (as identified by the 10934 // ']' location) and the index expression are both from macro expansions 10935 // within a system header. 10936 if (ASE) { 10937 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 10938 ASE->getRBracketLoc()); 10939 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 10940 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 10941 IndexExpr->getLocStart()); 10942 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 10943 return; 10944 } 10945 } 10946 10947 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 10948 if (ASE) 10949 DiagID = diag::warn_array_index_exceeds_bounds; 10950 10951 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10952 PDiag(DiagID) << index.toString(10, true) 10953 << size.toString(10, true) 10954 << (unsigned)size.getLimitedValue(~0U) 10955 << IndexExpr->getSourceRange()); 10956 } else { 10957 unsigned DiagID = diag::warn_array_index_precedes_bounds; 10958 if (!ASE) { 10959 DiagID = diag::warn_ptr_arith_precedes_bounds; 10960 if (index.isNegative()) index = -index; 10961 } 10962 10963 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10964 PDiag(DiagID) << index.toString(10, true) 10965 << IndexExpr->getSourceRange()); 10966 } 10967 10968 if (!ND) { 10969 // Try harder to find a NamedDecl to point at in the note. 10970 while (const ArraySubscriptExpr *ASE = 10971 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 10972 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 10973 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10974 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10975 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10976 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10977 } 10978 10979 if (ND) 10980 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 10981 PDiag(diag::note_array_index_out_of_bounds) 10982 << ND->getDeclName()); 10983 } 10984 10985 void Sema::CheckArrayAccess(const Expr *expr) { 10986 int AllowOnePastEnd = 0; 10987 while (expr) { 10988 expr = expr->IgnoreParenImpCasts(); 10989 switch (expr->getStmtClass()) { 10990 case Stmt::ArraySubscriptExprClass: { 10991 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 10992 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 10993 AllowOnePastEnd > 0); 10994 return; 10995 } 10996 case Stmt::OMPArraySectionExprClass: { 10997 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 10998 if (ASE->getLowerBound()) 10999 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 11000 /*ASE=*/nullptr, AllowOnePastEnd > 0); 11001 return; 11002 } 11003 case Stmt::UnaryOperatorClass: { 11004 // Only unwrap the * and & unary operators 11005 const UnaryOperator *UO = cast<UnaryOperator>(expr); 11006 expr = UO->getSubExpr(); 11007 switch (UO->getOpcode()) { 11008 case UO_AddrOf: 11009 AllowOnePastEnd++; 11010 break; 11011 case UO_Deref: 11012 AllowOnePastEnd--; 11013 break; 11014 default: 11015 return; 11016 } 11017 break; 11018 } 11019 case Stmt::ConditionalOperatorClass: { 11020 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 11021 if (const Expr *lhs = cond->getLHS()) 11022 CheckArrayAccess(lhs); 11023 if (const Expr *rhs = cond->getRHS()) 11024 CheckArrayAccess(rhs); 11025 return; 11026 } 11027 case Stmt::CXXOperatorCallExprClass: { 11028 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 11029 for (const auto *Arg : OCE->arguments()) 11030 CheckArrayAccess(Arg); 11031 return; 11032 } 11033 default: 11034 return; 11035 } 11036 } 11037 } 11038 11039 //===--- CHECK: Objective-C retain cycles ----------------------------------// 11040 11041 namespace { 11042 struct RetainCycleOwner { 11043 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 11044 VarDecl *Variable; 11045 SourceRange Range; 11046 SourceLocation Loc; 11047 bool Indirect; 11048 11049 void setLocsFrom(Expr *e) { 11050 Loc = e->getExprLoc(); 11051 Range = e->getSourceRange(); 11052 } 11053 }; 11054 } // end anonymous namespace 11055 11056 /// Consider whether capturing the given variable can possibly lead to 11057 /// a retain cycle. 11058 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 11059 // In ARC, it's captured strongly iff the variable has __strong 11060 // lifetime. In MRR, it's captured strongly if the variable is 11061 // __block and has an appropriate type. 11062 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11063 return false; 11064 11065 owner.Variable = var; 11066 if (ref) 11067 owner.setLocsFrom(ref); 11068 return true; 11069 } 11070 11071 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 11072 while (true) { 11073 e = e->IgnoreParens(); 11074 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 11075 switch (cast->getCastKind()) { 11076 case CK_BitCast: 11077 case CK_LValueBitCast: 11078 case CK_LValueToRValue: 11079 case CK_ARCReclaimReturnedObject: 11080 e = cast->getSubExpr(); 11081 continue; 11082 11083 default: 11084 return false; 11085 } 11086 } 11087 11088 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 11089 ObjCIvarDecl *ivar = ref->getDecl(); 11090 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11091 return false; 11092 11093 // Try to find a retain cycle in the base. 11094 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 11095 return false; 11096 11097 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 11098 owner.Indirect = true; 11099 return true; 11100 } 11101 11102 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 11103 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 11104 if (!var) return false; 11105 return considerVariable(var, ref, owner); 11106 } 11107 11108 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 11109 if (member->isArrow()) return false; 11110 11111 // Don't count this as an indirect ownership. 11112 e = member->getBase(); 11113 continue; 11114 } 11115 11116 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 11117 // Only pay attention to pseudo-objects on property references. 11118 ObjCPropertyRefExpr *pre 11119 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 11120 ->IgnoreParens()); 11121 if (!pre) return false; 11122 if (pre->isImplicitProperty()) return false; 11123 ObjCPropertyDecl *property = pre->getExplicitProperty(); 11124 if (!property->isRetaining() && 11125 !(property->getPropertyIvarDecl() && 11126 property->getPropertyIvarDecl()->getType() 11127 .getObjCLifetime() == Qualifiers::OCL_Strong)) 11128 return false; 11129 11130 owner.Indirect = true; 11131 if (pre->isSuperReceiver()) { 11132 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 11133 if (!owner.Variable) 11134 return false; 11135 owner.Loc = pre->getLocation(); 11136 owner.Range = pre->getSourceRange(); 11137 return true; 11138 } 11139 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 11140 ->getSourceExpr()); 11141 continue; 11142 } 11143 11144 // Array ivars? 11145 11146 return false; 11147 } 11148 } 11149 11150 namespace { 11151 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 11152 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 11153 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 11154 Context(Context), Variable(variable), Capturer(nullptr), 11155 VarWillBeReased(false) {} 11156 ASTContext &Context; 11157 VarDecl *Variable; 11158 Expr *Capturer; 11159 bool VarWillBeReased; 11160 11161 void VisitDeclRefExpr(DeclRefExpr *ref) { 11162 if (ref->getDecl() == Variable && !Capturer) 11163 Capturer = ref; 11164 } 11165 11166 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 11167 if (Capturer) return; 11168 Visit(ref->getBase()); 11169 if (Capturer && ref->isFreeIvar()) 11170 Capturer = ref; 11171 } 11172 11173 void VisitBlockExpr(BlockExpr *block) { 11174 // Look inside nested blocks 11175 if (block->getBlockDecl()->capturesVariable(Variable)) 11176 Visit(block->getBlockDecl()->getBody()); 11177 } 11178 11179 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 11180 if (Capturer) return; 11181 if (OVE->getSourceExpr()) 11182 Visit(OVE->getSourceExpr()); 11183 } 11184 void VisitBinaryOperator(BinaryOperator *BinOp) { 11185 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 11186 return; 11187 Expr *LHS = BinOp->getLHS(); 11188 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 11189 if (DRE->getDecl() != Variable) 11190 return; 11191 if (Expr *RHS = BinOp->getRHS()) { 11192 RHS = RHS->IgnoreParenCasts(); 11193 llvm::APSInt Value; 11194 VarWillBeReased = 11195 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 11196 } 11197 } 11198 } 11199 }; 11200 } // end anonymous namespace 11201 11202 /// Check whether the given argument is a block which captures a 11203 /// variable. 11204 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 11205 assert(owner.Variable && owner.Loc.isValid()); 11206 11207 e = e->IgnoreParenCasts(); 11208 11209 // Look through [^{...} copy] and Block_copy(^{...}). 11210 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 11211 Selector Cmd = ME->getSelector(); 11212 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 11213 e = ME->getInstanceReceiver(); 11214 if (!e) 11215 return nullptr; 11216 e = e->IgnoreParenCasts(); 11217 } 11218 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 11219 if (CE->getNumArgs() == 1) { 11220 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 11221 if (Fn) { 11222 const IdentifierInfo *FnI = Fn->getIdentifier(); 11223 if (FnI && FnI->isStr("_Block_copy")) { 11224 e = CE->getArg(0)->IgnoreParenCasts(); 11225 } 11226 } 11227 } 11228 } 11229 11230 BlockExpr *block = dyn_cast<BlockExpr>(e); 11231 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 11232 return nullptr; 11233 11234 FindCaptureVisitor visitor(S.Context, owner.Variable); 11235 visitor.Visit(block->getBlockDecl()->getBody()); 11236 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 11237 } 11238 11239 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 11240 RetainCycleOwner &owner) { 11241 assert(capturer); 11242 assert(owner.Variable && owner.Loc.isValid()); 11243 11244 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 11245 << owner.Variable << capturer->getSourceRange(); 11246 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 11247 << owner.Indirect << owner.Range; 11248 } 11249 11250 /// Check for a keyword selector that starts with the word 'add' or 11251 /// 'set'. 11252 static bool isSetterLikeSelector(Selector sel) { 11253 if (sel.isUnarySelector()) return false; 11254 11255 StringRef str = sel.getNameForSlot(0); 11256 while (!str.empty() && str.front() == '_') str = str.substr(1); 11257 if (str.startswith("set")) 11258 str = str.substr(3); 11259 else if (str.startswith("add")) { 11260 // Specially whitelist 'addOperationWithBlock:'. 11261 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 11262 return false; 11263 str = str.substr(3); 11264 } 11265 else 11266 return false; 11267 11268 if (str.empty()) return true; 11269 return !isLowercase(str.front()); 11270 } 11271 11272 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 11273 ObjCMessageExpr *Message) { 11274 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 11275 Message->getReceiverInterface(), 11276 NSAPI::ClassId_NSMutableArray); 11277 if (!IsMutableArray) { 11278 return None; 11279 } 11280 11281 Selector Sel = Message->getSelector(); 11282 11283 Optional<NSAPI::NSArrayMethodKind> MKOpt = 11284 S.NSAPIObj->getNSArrayMethodKind(Sel); 11285 if (!MKOpt) { 11286 return None; 11287 } 11288 11289 NSAPI::NSArrayMethodKind MK = *MKOpt; 11290 11291 switch (MK) { 11292 case NSAPI::NSMutableArr_addObject: 11293 case NSAPI::NSMutableArr_insertObjectAtIndex: 11294 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 11295 return 0; 11296 case NSAPI::NSMutableArr_replaceObjectAtIndex: 11297 return 1; 11298 11299 default: 11300 return None; 11301 } 11302 11303 return None; 11304 } 11305 11306 static 11307 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 11308 ObjCMessageExpr *Message) { 11309 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 11310 Message->getReceiverInterface(), 11311 NSAPI::ClassId_NSMutableDictionary); 11312 if (!IsMutableDictionary) { 11313 return None; 11314 } 11315 11316 Selector Sel = Message->getSelector(); 11317 11318 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 11319 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 11320 if (!MKOpt) { 11321 return None; 11322 } 11323 11324 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 11325 11326 switch (MK) { 11327 case NSAPI::NSMutableDict_setObjectForKey: 11328 case NSAPI::NSMutableDict_setValueForKey: 11329 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 11330 return 0; 11331 11332 default: 11333 return None; 11334 } 11335 11336 return None; 11337 } 11338 11339 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 11340 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 11341 Message->getReceiverInterface(), 11342 NSAPI::ClassId_NSMutableSet); 11343 11344 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 11345 Message->getReceiverInterface(), 11346 NSAPI::ClassId_NSMutableOrderedSet); 11347 if (!IsMutableSet && !IsMutableOrderedSet) { 11348 return None; 11349 } 11350 11351 Selector Sel = Message->getSelector(); 11352 11353 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 11354 if (!MKOpt) { 11355 return None; 11356 } 11357 11358 NSAPI::NSSetMethodKind MK = *MKOpt; 11359 11360 switch (MK) { 11361 case NSAPI::NSMutableSet_addObject: 11362 case NSAPI::NSOrderedSet_setObjectAtIndex: 11363 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 11364 case NSAPI::NSOrderedSet_insertObjectAtIndex: 11365 return 0; 11366 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 11367 return 1; 11368 } 11369 11370 return None; 11371 } 11372 11373 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 11374 if (!Message->isInstanceMessage()) { 11375 return; 11376 } 11377 11378 Optional<int> ArgOpt; 11379 11380 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 11381 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 11382 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 11383 return; 11384 } 11385 11386 int ArgIndex = *ArgOpt; 11387 11388 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 11389 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 11390 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 11391 } 11392 11393 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 11394 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11395 if (ArgRE->isObjCSelfExpr()) { 11396 Diag(Message->getSourceRange().getBegin(), 11397 diag::warn_objc_circular_container) 11398 << ArgRE->getDecl()->getName() << StringRef("super"); 11399 } 11400 } 11401 } else { 11402 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 11403 11404 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 11405 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 11406 } 11407 11408 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 11409 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 11410 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 11411 ValueDecl *Decl = ReceiverRE->getDecl(); 11412 Diag(Message->getSourceRange().getBegin(), 11413 diag::warn_objc_circular_container) 11414 << Decl->getName() << Decl->getName(); 11415 if (!ArgRE->isObjCSelfExpr()) { 11416 Diag(Decl->getLocation(), 11417 diag::note_objc_circular_container_declared_here) 11418 << Decl->getName(); 11419 } 11420 } 11421 } 11422 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 11423 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 11424 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 11425 ObjCIvarDecl *Decl = IvarRE->getDecl(); 11426 Diag(Message->getSourceRange().getBegin(), 11427 diag::warn_objc_circular_container) 11428 << Decl->getName() << Decl->getName(); 11429 Diag(Decl->getLocation(), 11430 diag::note_objc_circular_container_declared_here) 11431 << Decl->getName(); 11432 } 11433 } 11434 } 11435 } 11436 } 11437 11438 /// Check a message send to see if it's likely to cause a retain cycle. 11439 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 11440 // Only check instance methods whose selector looks like a setter. 11441 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 11442 return; 11443 11444 // Try to find a variable that the receiver is strongly owned by. 11445 RetainCycleOwner owner; 11446 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 11447 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 11448 return; 11449 } else { 11450 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 11451 owner.Variable = getCurMethodDecl()->getSelfDecl(); 11452 owner.Loc = msg->getSuperLoc(); 11453 owner.Range = msg->getSuperLoc(); 11454 } 11455 11456 // Check whether the receiver is captured by any of the arguments. 11457 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 11458 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 11459 return diagnoseRetainCycle(*this, capturer, owner); 11460 } 11461 11462 /// Check a property assign to see if it's likely to cause a retain cycle. 11463 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 11464 RetainCycleOwner owner; 11465 if (!findRetainCycleOwner(*this, receiver, owner)) 11466 return; 11467 11468 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 11469 diagnoseRetainCycle(*this, capturer, owner); 11470 } 11471 11472 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 11473 RetainCycleOwner Owner; 11474 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 11475 return; 11476 11477 // Because we don't have an expression for the variable, we have to set the 11478 // location explicitly here. 11479 Owner.Loc = Var->getLocation(); 11480 Owner.Range = Var->getSourceRange(); 11481 11482 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 11483 diagnoseRetainCycle(*this, Capturer, Owner); 11484 } 11485 11486 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 11487 Expr *RHS, bool isProperty) { 11488 // Check if RHS is an Objective-C object literal, which also can get 11489 // immediately zapped in a weak reference. Note that we explicitly 11490 // allow ObjCStringLiterals, since those are designed to never really die. 11491 RHS = RHS->IgnoreParenImpCasts(); 11492 11493 // This enum needs to match with the 'select' in 11494 // warn_objc_arc_literal_assign (off-by-1). 11495 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 11496 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 11497 return false; 11498 11499 S.Diag(Loc, diag::warn_arc_literal_assign) 11500 << (unsigned) Kind 11501 << (isProperty ? 0 : 1) 11502 << RHS->getSourceRange(); 11503 11504 return true; 11505 } 11506 11507 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 11508 Qualifiers::ObjCLifetime LT, 11509 Expr *RHS, bool isProperty) { 11510 // Strip off any implicit cast added to get to the one ARC-specific. 11511 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11512 if (cast->getCastKind() == CK_ARCConsumeObject) { 11513 S.Diag(Loc, diag::warn_arc_retained_assign) 11514 << (LT == Qualifiers::OCL_ExplicitNone) 11515 << (isProperty ? 0 : 1) 11516 << RHS->getSourceRange(); 11517 return true; 11518 } 11519 RHS = cast->getSubExpr(); 11520 } 11521 11522 if (LT == Qualifiers::OCL_Weak && 11523 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 11524 return true; 11525 11526 return false; 11527 } 11528 11529 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 11530 QualType LHS, Expr *RHS) { 11531 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 11532 11533 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 11534 return false; 11535 11536 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 11537 return true; 11538 11539 return false; 11540 } 11541 11542 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 11543 Expr *LHS, Expr *RHS) { 11544 QualType LHSType; 11545 // PropertyRef on LHS type need be directly obtained from 11546 // its declaration as it has a PseudoType. 11547 ObjCPropertyRefExpr *PRE 11548 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 11549 if (PRE && !PRE->isImplicitProperty()) { 11550 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11551 if (PD) 11552 LHSType = PD->getType(); 11553 } 11554 11555 if (LHSType.isNull()) 11556 LHSType = LHS->getType(); 11557 11558 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 11559 11560 if (LT == Qualifiers::OCL_Weak) { 11561 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 11562 getCurFunction()->markSafeWeakUse(LHS); 11563 } 11564 11565 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 11566 return; 11567 11568 // FIXME. Check for other life times. 11569 if (LT != Qualifiers::OCL_None) 11570 return; 11571 11572 if (PRE) { 11573 if (PRE->isImplicitProperty()) 11574 return; 11575 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11576 if (!PD) 11577 return; 11578 11579 unsigned Attributes = PD->getPropertyAttributes(); 11580 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 11581 // when 'assign' attribute was not explicitly specified 11582 // by user, ignore it and rely on property type itself 11583 // for lifetime info. 11584 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 11585 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 11586 LHSType->isObjCRetainableType()) 11587 return; 11588 11589 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11590 if (cast->getCastKind() == CK_ARCConsumeObject) { 11591 Diag(Loc, diag::warn_arc_retained_property_assign) 11592 << RHS->getSourceRange(); 11593 return; 11594 } 11595 RHS = cast->getSubExpr(); 11596 } 11597 } 11598 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 11599 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 11600 return; 11601 } 11602 } 11603 } 11604 11605 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 11606 11607 namespace { 11608 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 11609 SourceLocation StmtLoc, 11610 const NullStmt *Body) { 11611 // Do not warn if the body is a macro that expands to nothing, e.g: 11612 // 11613 // #define CALL(x) 11614 // if (condition) 11615 // CALL(0); 11616 // 11617 if (Body->hasLeadingEmptyMacro()) 11618 return false; 11619 11620 // Get line numbers of statement and body. 11621 bool StmtLineInvalid; 11622 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 11623 &StmtLineInvalid); 11624 if (StmtLineInvalid) 11625 return false; 11626 11627 bool BodyLineInvalid; 11628 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 11629 &BodyLineInvalid); 11630 if (BodyLineInvalid) 11631 return false; 11632 11633 // Warn if null statement and body are on the same line. 11634 if (StmtLine != BodyLine) 11635 return false; 11636 11637 return true; 11638 } 11639 } // end anonymous namespace 11640 11641 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 11642 const Stmt *Body, 11643 unsigned DiagID) { 11644 // Since this is a syntactic check, don't emit diagnostic for template 11645 // instantiations, this just adds noise. 11646 if (CurrentInstantiationScope) 11647 return; 11648 11649 // The body should be a null statement. 11650 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11651 if (!NBody) 11652 return; 11653 11654 // Do the usual checks. 11655 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11656 return; 11657 11658 Diag(NBody->getSemiLoc(), DiagID); 11659 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11660 } 11661 11662 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 11663 const Stmt *PossibleBody) { 11664 assert(!CurrentInstantiationScope); // Ensured by caller 11665 11666 SourceLocation StmtLoc; 11667 const Stmt *Body; 11668 unsigned DiagID; 11669 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 11670 StmtLoc = FS->getRParenLoc(); 11671 Body = FS->getBody(); 11672 DiagID = diag::warn_empty_for_body; 11673 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 11674 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 11675 Body = WS->getBody(); 11676 DiagID = diag::warn_empty_while_body; 11677 } else 11678 return; // Neither `for' nor `while'. 11679 11680 // The body should be a null statement. 11681 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11682 if (!NBody) 11683 return; 11684 11685 // Skip expensive checks if diagnostic is disabled. 11686 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 11687 return; 11688 11689 // Do the usual checks. 11690 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11691 return; 11692 11693 // `for(...);' and `while(...);' are popular idioms, so in order to keep 11694 // noise level low, emit diagnostics only if for/while is followed by a 11695 // CompoundStmt, e.g.: 11696 // for (int i = 0; i < n; i++); 11697 // { 11698 // a(i); 11699 // } 11700 // or if for/while is followed by a statement with more indentation 11701 // than for/while itself: 11702 // for (int i = 0; i < n; i++); 11703 // a(i); 11704 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 11705 if (!ProbableTypo) { 11706 bool BodyColInvalid; 11707 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 11708 PossibleBody->getLocStart(), 11709 &BodyColInvalid); 11710 if (BodyColInvalid) 11711 return; 11712 11713 bool StmtColInvalid; 11714 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 11715 S->getLocStart(), 11716 &StmtColInvalid); 11717 if (StmtColInvalid) 11718 return; 11719 11720 if (BodyCol > StmtCol) 11721 ProbableTypo = true; 11722 } 11723 11724 if (ProbableTypo) { 11725 Diag(NBody->getSemiLoc(), DiagID); 11726 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11727 } 11728 } 11729 11730 //===--- CHECK: Warn on self move with std::move. -------------------------===// 11731 11732 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 11733 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 11734 SourceLocation OpLoc) { 11735 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 11736 return; 11737 11738 if (inTemplateInstantiation()) 11739 return; 11740 11741 // Strip parens and casts away. 11742 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11743 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11744 11745 // Check for a call expression 11746 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 11747 if (!CE || CE->getNumArgs() != 1) 11748 return; 11749 11750 // Check for a call to std::move 11751 const FunctionDecl *FD = CE->getDirectCallee(); 11752 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() || 11753 !FD->getIdentifier()->isStr("move")) 11754 return; 11755 11756 // Get argument from std::move 11757 RHSExpr = CE->getArg(0); 11758 11759 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11760 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11761 11762 // Two DeclRefExpr's, check that the decls are the same. 11763 if (LHSDeclRef && RHSDeclRef) { 11764 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11765 return; 11766 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11767 RHSDeclRef->getDecl()->getCanonicalDecl()) 11768 return; 11769 11770 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11771 << LHSExpr->getSourceRange() 11772 << RHSExpr->getSourceRange(); 11773 return; 11774 } 11775 11776 // Member variables require a different approach to check for self moves. 11777 // MemberExpr's are the same if every nested MemberExpr refers to the same 11778 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 11779 // the base Expr's are CXXThisExpr's. 11780 const Expr *LHSBase = LHSExpr; 11781 const Expr *RHSBase = RHSExpr; 11782 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 11783 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 11784 if (!LHSME || !RHSME) 11785 return; 11786 11787 while (LHSME && RHSME) { 11788 if (LHSME->getMemberDecl()->getCanonicalDecl() != 11789 RHSME->getMemberDecl()->getCanonicalDecl()) 11790 return; 11791 11792 LHSBase = LHSME->getBase(); 11793 RHSBase = RHSME->getBase(); 11794 LHSME = dyn_cast<MemberExpr>(LHSBase); 11795 RHSME = dyn_cast<MemberExpr>(RHSBase); 11796 } 11797 11798 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 11799 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 11800 if (LHSDeclRef && RHSDeclRef) { 11801 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11802 return; 11803 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11804 RHSDeclRef->getDecl()->getCanonicalDecl()) 11805 return; 11806 11807 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11808 << LHSExpr->getSourceRange() 11809 << RHSExpr->getSourceRange(); 11810 return; 11811 } 11812 11813 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 11814 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11815 << LHSExpr->getSourceRange() 11816 << RHSExpr->getSourceRange(); 11817 } 11818 11819 //===--- Layout compatibility ----------------------------------------------// 11820 11821 namespace { 11822 11823 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 11824 11825 /// \brief Check if two enumeration types are layout-compatible. 11826 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 11827 // C++11 [dcl.enum] p8: 11828 // Two enumeration types are layout-compatible if they have the same 11829 // underlying type. 11830 return ED1->isComplete() && ED2->isComplete() && 11831 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 11832 } 11833 11834 /// \brief Check if two fields are layout-compatible. 11835 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 11836 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 11837 return false; 11838 11839 if (Field1->isBitField() != Field2->isBitField()) 11840 return false; 11841 11842 if (Field1->isBitField()) { 11843 // Make sure that the bit-fields are the same length. 11844 unsigned Bits1 = Field1->getBitWidthValue(C); 11845 unsigned Bits2 = Field2->getBitWidthValue(C); 11846 11847 if (Bits1 != Bits2) 11848 return false; 11849 } 11850 11851 return true; 11852 } 11853 11854 /// \brief Check if two standard-layout structs are layout-compatible. 11855 /// (C++11 [class.mem] p17) 11856 bool isLayoutCompatibleStruct(ASTContext &C, 11857 RecordDecl *RD1, 11858 RecordDecl *RD2) { 11859 // If both records are C++ classes, check that base classes match. 11860 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 11861 // If one of records is a CXXRecordDecl we are in C++ mode, 11862 // thus the other one is a CXXRecordDecl, too. 11863 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 11864 // Check number of base classes. 11865 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 11866 return false; 11867 11868 // Check the base classes. 11869 for (CXXRecordDecl::base_class_const_iterator 11870 Base1 = D1CXX->bases_begin(), 11871 BaseEnd1 = D1CXX->bases_end(), 11872 Base2 = D2CXX->bases_begin(); 11873 Base1 != BaseEnd1; 11874 ++Base1, ++Base2) { 11875 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 11876 return false; 11877 } 11878 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 11879 // If only RD2 is a C++ class, it should have zero base classes. 11880 if (D2CXX->getNumBases() > 0) 11881 return false; 11882 } 11883 11884 // Check the fields. 11885 RecordDecl::field_iterator Field2 = RD2->field_begin(), 11886 Field2End = RD2->field_end(), 11887 Field1 = RD1->field_begin(), 11888 Field1End = RD1->field_end(); 11889 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 11890 if (!isLayoutCompatible(C, *Field1, *Field2)) 11891 return false; 11892 } 11893 if (Field1 != Field1End || Field2 != Field2End) 11894 return false; 11895 11896 return true; 11897 } 11898 11899 /// \brief Check if two standard-layout unions are layout-compatible. 11900 /// (C++11 [class.mem] p18) 11901 bool isLayoutCompatibleUnion(ASTContext &C, 11902 RecordDecl *RD1, 11903 RecordDecl *RD2) { 11904 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 11905 for (auto *Field2 : RD2->fields()) 11906 UnmatchedFields.insert(Field2); 11907 11908 for (auto *Field1 : RD1->fields()) { 11909 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 11910 I = UnmatchedFields.begin(), 11911 E = UnmatchedFields.end(); 11912 11913 for ( ; I != E; ++I) { 11914 if (isLayoutCompatible(C, Field1, *I)) { 11915 bool Result = UnmatchedFields.erase(*I); 11916 (void) Result; 11917 assert(Result); 11918 break; 11919 } 11920 } 11921 if (I == E) 11922 return false; 11923 } 11924 11925 return UnmatchedFields.empty(); 11926 } 11927 11928 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 11929 if (RD1->isUnion() != RD2->isUnion()) 11930 return false; 11931 11932 if (RD1->isUnion()) 11933 return isLayoutCompatibleUnion(C, RD1, RD2); 11934 else 11935 return isLayoutCompatibleStruct(C, RD1, RD2); 11936 } 11937 11938 /// \brief Check if two types are layout-compatible in C++11 sense. 11939 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 11940 if (T1.isNull() || T2.isNull()) 11941 return false; 11942 11943 // C++11 [basic.types] p11: 11944 // If two types T1 and T2 are the same type, then T1 and T2 are 11945 // layout-compatible types. 11946 if (C.hasSameType(T1, T2)) 11947 return true; 11948 11949 T1 = T1.getCanonicalType().getUnqualifiedType(); 11950 T2 = T2.getCanonicalType().getUnqualifiedType(); 11951 11952 const Type::TypeClass TC1 = T1->getTypeClass(); 11953 const Type::TypeClass TC2 = T2->getTypeClass(); 11954 11955 if (TC1 != TC2) 11956 return false; 11957 11958 if (TC1 == Type::Enum) { 11959 return isLayoutCompatible(C, 11960 cast<EnumType>(T1)->getDecl(), 11961 cast<EnumType>(T2)->getDecl()); 11962 } else if (TC1 == Type::Record) { 11963 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 11964 return false; 11965 11966 return isLayoutCompatible(C, 11967 cast<RecordType>(T1)->getDecl(), 11968 cast<RecordType>(T2)->getDecl()); 11969 } 11970 11971 return false; 11972 } 11973 } // end anonymous namespace 11974 11975 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 11976 11977 namespace { 11978 /// \brief Given a type tag expression find the type tag itself. 11979 /// 11980 /// \param TypeExpr Type tag expression, as it appears in user's code. 11981 /// 11982 /// \param VD Declaration of an identifier that appears in a type tag. 11983 /// 11984 /// \param MagicValue Type tag magic value. 11985 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 11986 const ValueDecl **VD, uint64_t *MagicValue) { 11987 while(true) { 11988 if (!TypeExpr) 11989 return false; 11990 11991 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 11992 11993 switch (TypeExpr->getStmtClass()) { 11994 case Stmt::UnaryOperatorClass: { 11995 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 11996 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 11997 TypeExpr = UO->getSubExpr(); 11998 continue; 11999 } 12000 return false; 12001 } 12002 12003 case Stmt::DeclRefExprClass: { 12004 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 12005 *VD = DRE->getDecl(); 12006 return true; 12007 } 12008 12009 case Stmt::IntegerLiteralClass: { 12010 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 12011 llvm::APInt MagicValueAPInt = IL->getValue(); 12012 if (MagicValueAPInt.getActiveBits() <= 64) { 12013 *MagicValue = MagicValueAPInt.getZExtValue(); 12014 return true; 12015 } else 12016 return false; 12017 } 12018 12019 case Stmt::BinaryConditionalOperatorClass: 12020 case Stmt::ConditionalOperatorClass: { 12021 const AbstractConditionalOperator *ACO = 12022 cast<AbstractConditionalOperator>(TypeExpr); 12023 bool Result; 12024 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 12025 if (Result) 12026 TypeExpr = ACO->getTrueExpr(); 12027 else 12028 TypeExpr = ACO->getFalseExpr(); 12029 continue; 12030 } 12031 return false; 12032 } 12033 12034 case Stmt::BinaryOperatorClass: { 12035 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 12036 if (BO->getOpcode() == BO_Comma) { 12037 TypeExpr = BO->getRHS(); 12038 continue; 12039 } 12040 return false; 12041 } 12042 12043 default: 12044 return false; 12045 } 12046 } 12047 } 12048 12049 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 12050 /// 12051 /// \param TypeExpr Expression that specifies a type tag. 12052 /// 12053 /// \param MagicValues Registered magic values. 12054 /// 12055 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 12056 /// kind. 12057 /// 12058 /// \param TypeInfo Information about the corresponding C type. 12059 /// 12060 /// \returns true if the corresponding C type was found. 12061 bool GetMatchingCType( 12062 const IdentifierInfo *ArgumentKind, 12063 const Expr *TypeExpr, const ASTContext &Ctx, 12064 const llvm::DenseMap<Sema::TypeTagMagicValue, 12065 Sema::TypeTagData> *MagicValues, 12066 bool &FoundWrongKind, 12067 Sema::TypeTagData &TypeInfo) { 12068 FoundWrongKind = false; 12069 12070 // Variable declaration that has type_tag_for_datatype attribute. 12071 const ValueDecl *VD = nullptr; 12072 12073 uint64_t MagicValue; 12074 12075 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 12076 return false; 12077 12078 if (VD) { 12079 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 12080 if (I->getArgumentKind() != ArgumentKind) { 12081 FoundWrongKind = true; 12082 return false; 12083 } 12084 TypeInfo.Type = I->getMatchingCType(); 12085 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 12086 TypeInfo.MustBeNull = I->getMustBeNull(); 12087 return true; 12088 } 12089 return false; 12090 } 12091 12092 if (!MagicValues) 12093 return false; 12094 12095 llvm::DenseMap<Sema::TypeTagMagicValue, 12096 Sema::TypeTagData>::const_iterator I = 12097 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 12098 if (I == MagicValues->end()) 12099 return false; 12100 12101 TypeInfo = I->second; 12102 return true; 12103 } 12104 } // end anonymous namespace 12105 12106 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 12107 uint64_t MagicValue, QualType Type, 12108 bool LayoutCompatible, 12109 bool MustBeNull) { 12110 if (!TypeTagForDatatypeMagicValues) 12111 TypeTagForDatatypeMagicValues.reset( 12112 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 12113 12114 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 12115 (*TypeTagForDatatypeMagicValues)[Magic] = 12116 TypeTagData(Type, LayoutCompatible, MustBeNull); 12117 } 12118 12119 namespace { 12120 bool IsSameCharType(QualType T1, QualType T2) { 12121 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 12122 if (!BT1) 12123 return false; 12124 12125 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 12126 if (!BT2) 12127 return false; 12128 12129 BuiltinType::Kind T1Kind = BT1->getKind(); 12130 BuiltinType::Kind T2Kind = BT2->getKind(); 12131 12132 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 12133 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 12134 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 12135 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 12136 } 12137 } // end anonymous namespace 12138 12139 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 12140 const Expr * const *ExprArgs) { 12141 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 12142 bool IsPointerAttr = Attr->getIsPointer(); 12143 12144 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 12145 bool FoundWrongKind; 12146 TypeTagData TypeInfo; 12147 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 12148 TypeTagForDatatypeMagicValues.get(), 12149 FoundWrongKind, TypeInfo)) { 12150 if (FoundWrongKind) 12151 Diag(TypeTagExpr->getExprLoc(), 12152 diag::warn_type_tag_for_datatype_wrong_kind) 12153 << TypeTagExpr->getSourceRange(); 12154 return; 12155 } 12156 12157 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 12158 if (IsPointerAttr) { 12159 // Skip implicit cast of pointer to `void *' (as a function argument). 12160 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 12161 if (ICE->getType()->isVoidPointerType() && 12162 ICE->getCastKind() == CK_BitCast) 12163 ArgumentExpr = ICE->getSubExpr(); 12164 } 12165 QualType ArgumentType = ArgumentExpr->getType(); 12166 12167 // Passing a `void*' pointer shouldn't trigger a warning. 12168 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 12169 return; 12170 12171 if (TypeInfo.MustBeNull) { 12172 // Type tag with matching void type requires a null pointer. 12173 if (!ArgumentExpr->isNullPointerConstant(Context, 12174 Expr::NPC_ValueDependentIsNotNull)) { 12175 Diag(ArgumentExpr->getExprLoc(), 12176 diag::warn_type_safety_null_pointer_required) 12177 << ArgumentKind->getName() 12178 << ArgumentExpr->getSourceRange() 12179 << TypeTagExpr->getSourceRange(); 12180 } 12181 return; 12182 } 12183 12184 QualType RequiredType = TypeInfo.Type; 12185 if (IsPointerAttr) 12186 RequiredType = Context.getPointerType(RequiredType); 12187 12188 bool mismatch = false; 12189 if (!TypeInfo.LayoutCompatible) { 12190 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 12191 12192 // C++11 [basic.fundamental] p1: 12193 // Plain char, signed char, and unsigned char are three distinct types. 12194 // 12195 // But we treat plain `char' as equivalent to `signed char' or `unsigned 12196 // char' depending on the current char signedness mode. 12197 if (mismatch) 12198 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 12199 RequiredType->getPointeeType())) || 12200 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 12201 mismatch = false; 12202 } else 12203 if (IsPointerAttr) 12204 mismatch = !isLayoutCompatible(Context, 12205 ArgumentType->getPointeeType(), 12206 RequiredType->getPointeeType()); 12207 else 12208 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 12209 12210 if (mismatch) 12211 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 12212 << ArgumentType << ArgumentKind 12213 << TypeInfo.LayoutCompatible << RequiredType 12214 << ArgumentExpr->getSourceRange() 12215 << TypeTagExpr->getSourceRange(); 12216 } 12217 12218 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 12219 CharUnits Alignment) { 12220 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 12221 } 12222 12223 void Sema::DiagnoseMisalignedMembers() { 12224 for (MisalignedMember &m : MisalignedMembers) { 12225 const NamedDecl *ND = m.RD; 12226 if (ND->getName().empty()) { 12227 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 12228 ND = TD; 12229 } 12230 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 12231 << m.MD << ND << m.E->getSourceRange(); 12232 } 12233 MisalignedMembers.clear(); 12234 } 12235 12236 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 12237 E = E->IgnoreParens(); 12238 if (!T->isPointerType() && !T->isIntegerType()) 12239 return; 12240 if (isa<UnaryOperator>(E) && 12241 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 12242 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 12243 if (isa<MemberExpr>(Op)) { 12244 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 12245 MisalignedMember(Op)); 12246 if (MA != MisalignedMembers.end() && 12247 (T->isIntegerType() || 12248 (T->isPointerType() && 12249 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment))) 12250 MisalignedMembers.erase(MA); 12251 } 12252 } 12253 } 12254 12255 void Sema::RefersToMemberWithReducedAlignment( 12256 Expr *E, 12257 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 12258 Action) { 12259 const auto *ME = dyn_cast<MemberExpr>(E); 12260 if (!ME) 12261 return; 12262 12263 // No need to check expressions with an __unaligned-qualified type. 12264 if (E->getType().getQualifiers().hasUnaligned()) 12265 return; 12266 12267 // For a chain of MemberExpr like "a.b.c.d" this list 12268 // will keep FieldDecl's like [d, c, b]. 12269 SmallVector<FieldDecl *, 4> ReverseMemberChain; 12270 const MemberExpr *TopME = nullptr; 12271 bool AnyIsPacked = false; 12272 do { 12273 QualType BaseType = ME->getBase()->getType(); 12274 if (ME->isArrow()) 12275 BaseType = BaseType->getPointeeType(); 12276 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 12277 if (RD->isInvalidDecl()) 12278 return; 12279 12280 ValueDecl *MD = ME->getMemberDecl(); 12281 auto *FD = dyn_cast<FieldDecl>(MD); 12282 // We do not care about non-data members. 12283 if (!FD || FD->isInvalidDecl()) 12284 return; 12285 12286 AnyIsPacked = 12287 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 12288 ReverseMemberChain.push_back(FD); 12289 12290 TopME = ME; 12291 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 12292 } while (ME); 12293 assert(TopME && "We did not compute a topmost MemberExpr!"); 12294 12295 // Not the scope of this diagnostic. 12296 if (!AnyIsPacked) 12297 return; 12298 12299 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 12300 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 12301 // TODO: The innermost base of the member expression may be too complicated. 12302 // For now, just disregard these cases. This is left for future 12303 // improvement. 12304 if (!DRE && !isa<CXXThisExpr>(TopBase)) 12305 return; 12306 12307 // Alignment expected by the whole expression. 12308 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 12309 12310 // No need to do anything else with this case. 12311 if (ExpectedAlignment.isOne()) 12312 return; 12313 12314 // Synthesize offset of the whole access. 12315 CharUnits Offset; 12316 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 12317 I++) { 12318 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 12319 } 12320 12321 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 12322 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 12323 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 12324 12325 // The base expression of the innermost MemberExpr may give 12326 // stronger guarantees than the class containing the member. 12327 if (DRE && !TopME->isArrow()) { 12328 const ValueDecl *VD = DRE->getDecl(); 12329 if (!VD->getType()->isReferenceType()) 12330 CompleteObjectAlignment = 12331 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 12332 } 12333 12334 // Check if the synthesized offset fulfills the alignment. 12335 if (Offset % ExpectedAlignment != 0 || 12336 // It may fulfill the offset it but the effective alignment may still be 12337 // lower than the expected expression alignment. 12338 CompleteObjectAlignment < ExpectedAlignment) { 12339 // If this happens, we want to determine a sensible culprit of this. 12340 // Intuitively, watching the chain of member expressions from right to 12341 // left, we start with the required alignment (as required by the field 12342 // type) but some packed attribute in that chain has reduced the alignment. 12343 // It may happen that another packed structure increases it again. But if 12344 // we are here such increase has not been enough. So pointing the first 12345 // FieldDecl that either is packed or else its RecordDecl is, 12346 // seems reasonable. 12347 FieldDecl *FD = nullptr; 12348 CharUnits Alignment; 12349 for (FieldDecl *FDI : ReverseMemberChain) { 12350 if (FDI->hasAttr<PackedAttr>() || 12351 FDI->getParent()->hasAttr<PackedAttr>()) { 12352 FD = FDI; 12353 Alignment = std::min( 12354 Context.getTypeAlignInChars(FD->getType()), 12355 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 12356 break; 12357 } 12358 } 12359 assert(FD && "We did not find a packed FieldDecl!"); 12360 Action(E, FD->getParent(), FD, Alignment); 12361 } 12362 } 12363 12364 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 12365 using namespace std::placeholders; 12366 RefersToMemberWithReducedAlignment( 12367 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 12368 _2, _3, _4)); 12369 } 12370 12371