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/TargetBuiltins.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 31 #include "clang/Sema/Initialization.h" 32 #include "clang/Sema/Lookup.h" 33 #include "clang/Sema/ScopeInfo.h" 34 #include "clang/Sema/Sema.h" 35 #include "clang/Sema/SemaInternal.h" 36 #include "llvm/ADT/STLExtras.h" 37 #include "llvm/ADT/SmallBitVector.h" 38 #include "llvm/ADT/SmallString.h" 39 #include "llvm/Support/ConvertUTF.h" 40 #include "llvm/Support/Format.h" 41 #include "llvm/Support/Locale.h" 42 #include "llvm/Support/raw_ostream.h" 43 44 using namespace clang; 45 using namespace sema; 46 47 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 48 unsigned ByteNo) const { 49 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 50 Context.getTargetInfo()); 51 } 52 53 /// Checks that a call expression's argument count is the desired number. 54 /// This is useful when doing custom type-checking. Returns true on error. 55 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 56 unsigned argCount = call->getNumArgs(); 57 if (argCount == desiredArgCount) return false; 58 59 if (argCount < desiredArgCount) 60 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 61 << 0 /*function call*/ << desiredArgCount << argCount 62 << call->getSourceRange(); 63 64 // Highlight all the excess arguments. 65 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 66 call->getArg(argCount - 1)->getLocEnd()); 67 68 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 69 << 0 /*function call*/ << desiredArgCount << argCount 70 << call->getArg(1)->getSourceRange(); 71 } 72 73 /// Check that the first argument to __builtin_annotation is an integer 74 /// and the second argument is a non-wide string literal. 75 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 76 if (checkArgCount(S, TheCall, 2)) 77 return true; 78 79 // First argument should be an integer. 80 Expr *ValArg = TheCall->getArg(0); 81 QualType Ty = ValArg->getType(); 82 if (!Ty->isIntegerType()) { 83 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 84 << ValArg->getSourceRange(); 85 return true; 86 } 87 88 // Second argument should be a constant string. 89 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 90 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 91 if (!Literal || !Literal->isAscii()) { 92 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 93 << StrArg->getSourceRange(); 94 return true; 95 } 96 97 TheCall->setType(Ty); 98 return false; 99 } 100 101 /// Check that the argument to __builtin_addressof is a glvalue, and set the 102 /// result type to the corresponding pointer type. 103 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 104 if (checkArgCount(S, TheCall, 1)) 105 return true; 106 107 ExprResult Arg(TheCall->getArg(0)); 108 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 109 if (ResultType.isNull()) 110 return true; 111 112 TheCall->setArg(0, Arg.get()); 113 TheCall->setType(ResultType); 114 return false; 115 } 116 117 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 118 if (checkArgCount(S, TheCall, 3)) 119 return true; 120 121 // First two arguments should be integers. 122 for (unsigned I = 0; I < 2; ++I) { 123 Expr *Arg = TheCall->getArg(I); 124 QualType Ty = Arg->getType(); 125 if (!Ty->isIntegerType()) { 126 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int) 127 << Ty << Arg->getSourceRange(); 128 return true; 129 } 130 } 131 132 // Third argument should be a pointer to a non-const integer. 133 // IRGen correctly handles volatile, restrict, and address spaces, and 134 // the other qualifiers aren't possible. 135 { 136 Expr *Arg = TheCall->getArg(2); 137 QualType Ty = Arg->getType(); 138 const auto *PtrTy = Ty->getAs<PointerType>(); 139 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 140 !PtrTy->getPointeeType().isConstQualified())) { 141 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int) 142 << Ty << Arg->getSourceRange(); 143 return true; 144 } 145 } 146 147 return false; 148 } 149 150 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 151 CallExpr *TheCall, unsigned SizeIdx, 152 unsigned DstSizeIdx) { 153 if (TheCall->getNumArgs() <= SizeIdx || 154 TheCall->getNumArgs() <= DstSizeIdx) 155 return; 156 157 const Expr *SizeArg = TheCall->getArg(SizeIdx); 158 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 159 160 llvm::APSInt Size, DstSize; 161 162 // find out if both sizes are known at compile time 163 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 164 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 165 return; 166 167 if (Size.ule(DstSize)) 168 return; 169 170 // confirmed overflow so generate the diagnostic. 171 IdentifierInfo *FnName = FDecl->getIdentifier(); 172 SourceLocation SL = TheCall->getLocStart(); 173 SourceRange SR = TheCall->getSourceRange(); 174 175 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; 176 } 177 178 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 179 if (checkArgCount(S, BuiltinCall, 2)) 180 return true; 181 182 SourceLocation BuiltinLoc = BuiltinCall->getLocStart(); 183 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 184 Expr *Call = BuiltinCall->getArg(0); 185 Expr *Chain = BuiltinCall->getArg(1); 186 187 if (Call->getStmtClass() != Stmt::CallExprClass) { 188 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 189 << Call->getSourceRange(); 190 return true; 191 } 192 193 auto CE = cast<CallExpr>(Call); 194 if (CE->getCallee()->getType()->isBlockPointerType()) { 195 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 196 << Call->getSourceRange(); 197 return true; 198 } 199 200 const Decl *TargetDecl = CE->getCalleeDecl(); 201 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 202 if (FD->getBuiltinID()) { 203 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 204 << Call->getSourceRange(); 205 return true; 206 } 207 208 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 209 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 210 << Call->getSourceRange(); 211 return true; 212 } 213 214 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 215 if (ChainResult.isInvalid()) 216 return true; 217 if (!ChainResult.get()->getType()->isPointerType()) { 218 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 219 << Chain->getSourceRange(); 220 return true; 221 } 222 223 QualType ReturnTy = CE->getCallReturnType(S.Context); 224 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 225 QualType BuiltinTy = S.Context.getFunctionType( 226 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 227 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 228 229 Builtin = 230 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 231 232 BuiltinCall->setType(CE->getType()); 233 BuiltinCall->setValueKind(CE->getValueKind()); 234 BuiltinCall->setObjectKind(CE->getObjectKind()); 235 BuiltinCall->setCallee(Builtin); 236 BuiltinCall->setArg(1, ChainResult.get()); 237 238 return false; 239 } 240 241 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 242 Scope::ScopeFlags NeededScopeFlags, 243 unsigned DiagID) { 244 // Scopes aren't available during instantiation. Fortunately, builtin 245 // functions cannot be template args so they cannot be formed through template 246 // instantiation. Therefore checking once during the parse is sufficient. 247 if (!SemaRef.ActiveTemplateInstantiations.empty()) 248 return false; 249 250 Scope *S = SemaRef.getCurScope(); 251 while (S && !S->isSEHExceptScope()) 252 S = S->getParent(); 253 if (!S || !(S->getFlags() & NeededScopeFlags)) { 254 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 255 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 256 << DRE->getDecl()->getIdentifier(); 257 return true; 258 } 259 260 return false; 261 } 262 263 static inline bool isBlockPointer(Expr *Arg) { 264 return Arg->getType()->isBlockPointerType(); 265 } 266 267 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 268 /// void*, which is a requirement of device side enqueue. 269 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 270 const BlockPointerType *BPT = 271 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 272 ArrayRef<QualType> Params = 273 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 274 unsigned ArgCounter = 0; 275 bool IllegalParams = false; 276 // Iterate through the block parameters until either one is found that is not 277 // a local void*, or the block is valid. 278 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 279 I != E; ++I, ++ArgCounter) { 280 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 281 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 282 LangAS::opencl_local) { 283 // Get the location of the error. If a block literal has been passed 284 // (BlockExpr) then we can point straight to the offending argument, 285 // else we just point to the variable reference. 286 SourceLocation ErrorLoc; 287 if (isa<BlockExpr>(BlockArg)) { 288 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 289 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart(); 290 } else if (isa<DeclRefExpr>(BlockArg)) { 291 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart(); 292 } 293 S.Diag(ErrorLoc, 294 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 295 IllegalParams = true; 296 } 297 } 298 299 return IllegalParams; 300 } 301 302 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 303 /// get_kernel_work_group_size 304 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 305 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 306 if (checkArgCount(S, TheCall, 1)) 307 return true; 308 309 Expr *BlockArg = TheCall->getArg(0); 310 if (!isBlockPointer(BlockArg)) { 311 S.Diag(BlockArg->getLocStart(), 312 diag::err_opencl_enqueue_kernel_expected_type) << "block"; 313 return true; 314 } 315 return checkOpenCLBlockArgs(S, BlockArg); 316 } 317 318 /// Diagnose integer type and any valid implicit convertion to it. 319 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 320 const QualType &IntType); 321 322 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 323 unsigned Start, unsigned End) { 324 bool IllegalParams = false; 325 for (unsigned I = Start; I <= End; ++I) 326 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 327 S.Context.getSizeType()); 328 return IllegalParams; 329 } 330 331 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 332 /// 'local void*' parameter of passed block. 333 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 334 Expr *BlockArg, 335 unsigned NumNonVarArgs) { 336 const BlockPointerType *BPT = 337 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 338 unsigned NumBlockParams = 339 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 340 unsigned TotalNumArgs = TheCall->getNumArgs(); 341 342 // For each argument passed to the block, a corresponding uint needs to 343 // be passed to describe the size of the local memory. 344 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 345 S.Diag(TheCall->getLocStart(), 346 diag::err_opencl_enqueue_kernel_local_size_args); 347 return true; 348 } 349 350 // Check that the sizes of the local memory are specified by integers. 351 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 352 TotalNumArgs - 1); 353 } 354 355 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 356 /// overload formats specified in Table 6.13.17.1. 357 /// int enqueue_kernel(queue_t queue, 358 /// kernel_enqueue_flags_t flags, 359 /// const ndrange_t ndrange, 360 /// void (^block)(void)) 361 /// int enqueue_kernel(queue_t queue, 362 /// kernel_enqueue_flags_t flags, 363 /// const ndrange_t ndrange, 364 /// uint num_events_in_wait_list, 365 /// clk_event_t *event_wait_list, 366 /// clk_event_t *event_ret, 367 /// void (^block)(void)) 368 /// int enqueue_kernel(queue_t queue, 369 /// kernel_enqueue_flags_t flags, 370 /// const ndrange_t ndrange, 371 /// void (^block)(local void*, ...), 372 /// uint size0, ...) 373 /// int enqueue_kernel(queue_t queue, 374 /// kernel_enqueue_flags_t flags, 375 /// const ndrange_t ndrange, 376 /// uint num_events_in_wait_list, 377 /// clk_event_t *event_wait_list, 378 /// clk_event_t *event_ret, 379 /// void (^block)(local void*, ...), 380 /// uint size0, ...) 381 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 382 unsigned NumArgs = TheCall->getNumArgs(); 383 384 if (NumArgs < 4) { 385 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args); 386 return true; 387 } 388 389 Expr *Arg0 = TheCall->getArg(0); 390 Expr *Arg1 = TheCall->getArg(1); 391 Expr *Arg2 = TheCall->getArg(2); 392 Expr *Arg3 = TheCall->getArg(3); 393 394 // First argument always needs to be a queue_t type. 395 if (!Arg0->getType()->isQueueT()) { 396 S.Diag(TheCall->getArg(0)->getLocStart(), 397 diag::err_opencl_enqueue_kernel_expected_type) 398 << S.Context.OCLQueueTy; 399 return true; 400 } 401 402 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 403 if (!Arg1->getType()->isIntegerType()) { 404 S.Diag(TheCall->getArg(1)->getLocStart(), 405 diag::err_opencl_enqueue_kernel_expected_type) 406 << "'kernel_enqueue_flags_t' (i.e. uint)"; 407 return true; 408 } 409 410 // Third argument is always an ndrange_t type. 411 if (!Arg2->getType()->isNDRangeT()) { 412 S.Diag(TheCall->getArg(2)->getLocStart(), 413 diag::err_opencl_enqueue_kernel_expected_type) 414 << S.Context.OCLNDRangeTy; 415 return true; 416 } 417 418 // With four arguments, there is only one form that the function could be 419 // called in: no events and no variable arguments. 420 if (NumArgs == 4) { 421 // check that the last argument is the right block type. 422 if (!isBlockPointer(Arg3)) { 423 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type) 424 << "block"; 425 return true; 426 } 427 // we have a block type, check the prototype 428 const BlockPointerType *BPT = 429 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 430 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 431 S.Diag(Arg3->getLocStart(), 432 diag::err_opencl_enqueue_kernel_blocks_no_args); 433 return true; 434 } 435 return false; 436 } 437 // we can have block + varargs. 438 if (isBlockPointer(Arg3)) 439 return (checkOpenCLBlockArgs(S, Arg3) || 440 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 441 // last two cases with either exactly 7 args or 7 args and varargs. 442 if (NumArgs >= 7) { 443 // check common block argument. 444 Expr *Arg6 = TheCall->getArg(6); 445 if (!isBlockPointer(Arg6)) { 446 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type) 447 << "block"; 448 return true; 449 } 450 if (checkOpenCLBlockArgs(S, Arg6)) 451 return true; 452 453 // Forth argument has to be any integer type. 454 if (!Arg3->getType()->isIntegerType()) { 455 S.Diag(TheCall->getArg(3)->getLocStart(), 456 diag::err_opencl_enqueue_kernel_expected_type) 457 << "integer"; 458 return true; 459 } 460 // check remaining common arguments. 461 Expr *Arg4 = TheCall->getArg(4); 462 Expr *Arg5 = TheCall->getArg(5); 463 464 // Fifth argument is always passed as a pointer to clk_event_t. 465 if (!Arg4->isNullPointerConstant(S.Context, 466 Expr::NPC_ValueDependentIsNotNull) && 467 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 468 S.Diag(TheCall->getArg(4)->getLocStart(), 469 diag::err_opencl_enqueue_kernel_expected_type) 470 << S.Context.getPointerType(S.Context.OCLClkEventTy); 471 return true; 472 } 473 474 // Sixth argument is always passed as a pointer to clk_event_t. 475 if (!Arg5->isNullPointerConstant(S.Context, 476 Expr::NPC_ValueDependentIsNotNull) && 477 !(Arg5->getType()->isPointerType() && 478 Arg5->getType()->getPointeeType()->isClkEventT())) { 479 S.Diag(TheCall->getArg(5)->getLocStart(), 480 diag::err_opencl_enqueue_kernel_expected_type) 481 << S.Context.getPointerType(S.Context.OCLClkEventTy); 482 return true; 483 } 484 485 if (NumArgs == 7) 486 return false; 487 488 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 489 } 490 491 // None of the specific case has been detected, give generic error 492 S.Diag(TheCall->getLocStart(), 493 diag::err_opencl_enqueue_kernel_incorrect_args); 494 return true; 495 } 496 497 /// Returns OpenCL access qual. 498 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 499 return D->getAttr<OpenCLAccessAttr>(); 500 } 501 502 /// Returns true if pipe element type is different from the pointer. 503 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 504 const Expr *Arg0 = Call->getArg(0); 505 // First argument type should always be pipe. 506 if (!Arg0->getType()->isPipeType()) { 507 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 508 << Call->getDirectCallee() << Arg0->getSourceRange(); 509 return true; 510 } 511 OpenCLAccessAttr *AccessQual = 512 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 513 // Validates the access qualifier is compatible with the call. 514 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 515 // read_only and write_only, and assumed to be read_only if no qualifier is 516 // specified. 517 switch (Call->getDirectCallee()->getBuiltinID()) { 518 case Builtin::BIread_pipe: 519 case Builtin::BIreserve_read_pipe: 520 case Builtin::BIcommit_read_pipe: 521 case Builtin::BIwork_group_reserve_read_pipe: 522 case Builtin::BIsub_group_reserve_read_pipe: 523 case Builtin::BIwork_group_commit_read_pipe: 524 case Builtin::BIsub_group_commit_read_pipe: 525 if (!(!AccessQual || AccessQual->isReadOnly())) { 526 S.Diag(Arg0->getLocStart(), 527 diag::err_opencl_builtin_pipe_invalid_access_modifier) 528 << "read_only" << Arg0->getSourceRange(); 529 return true; 530 } 531 break; 532 case Builtin::BIwrite_pipe: 533 case Builtin::BIreserve_write_pipe: 534 case Builtin::BIcommit_write_pipe: 535 case Builtin::BIwork_group_reserve_write_pipe: 536 case Builtin::BIsub_group_reserve_write_pipe: 537 case Builtin::BIwork_group_commit_write_pipe: 538 case Builtin::BIsub_group_commit_write_pipe: 539 if (!(AccessQual && AccessQual->isWriteOnly())) { 540 S.Diag(Arg0->getLocStart(), 541 diag::err_opencl_builtin_pipe_invalid_access_modifier) 542 << "write_only" << Arg0->getSourceRange(); 543 return true; 544 } 545 break; 546 default: 547 break; 548 } 549 return false; 550 } 551 552 /// Returns true if pipe element type is different from the pointer. 553 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 554 const Expr *Arg0 = Call->getArg(0); 555 const Expr *ArgIdx = Call->getArg(Idx); 556 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 557 const QualType EltTy = PipeTy->getElementType(); 558 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 559 // The Idx argument should be a pointer and the type of the pointer and 560 // the type of pipe element should also be the same. 561 if (!ArgTy || 562 !S.Context.hasSameType( 563 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 564 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 565 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 566 << ArgIdx->getType() << ArgIdx->getSourceRange(); 567 return true; 568 } 569 return false; 570 } 571 572 // \brief Performs semantic analysis for the read/write_pipe call. 573 // \param S Reference to the semantic analyzer. 574 // \param Call A pointer to the builtin call. 575 // \return True if a semantic error has been found, false otherwise. 576 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 577 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 578 // functions have two forms. 579 switch (Call->getNumArgs()) { 580 case 2: { 581 if (checkOpenCLPipeArg(S, Call)) 582 return true; 583 // The call with 2 arguments should be 584 // read/write_pipe(pipe T, T*). 585 // Check packet type T. 586 if (checkOpenCLPipePacketType(S, Call, 1)) 587 return true; 588 } break; 589 590 case 4: { 591 if (checkOpenCLPipeArg(S, Call)) 592 return true; 593 // The call with 4 arguments should be 594 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 595 // Check reserve_id_t. 596 if (!Call->getArg(1)->getType()->isReserveIDT()) { 597 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 598 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 599 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 600 return true; 601 } 602 603 // Check the index. 604 const Expr *Arg2 = Call->getArg(2); 605 if (!Arg2->getType()->isIntegerType() && 606 !Arg2->getType()->isUnsignedIntegerType()) { 607 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 608 << Call->getDirectCallee() << S.Context.UnsignedIntTy 609 << Arg2->getType() << Arg2->getSourceRange(); 610 return true; 611 } 612 613 // Check packet type T. 614 if (checkOpenCLPipePacketType(S, Call, 3)) 615 return true; 616 } break; 617 default: 618 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) 619 << Call->getDirectCallee() << Call->getSourceRange(); 620 return true; 621 } 622 623 return false; 624 } 625 626 // \brief Performs a semantic analysis on the {work_group_/sub_group_ 627 // /_}reserve_{read/write}_pipe 628 // \param S Reference to the semantic analyzer. 629 // \param Call The call to the builtin function to be analyzed. 630 // \return True if a semantic error was found, false otherwise. 631 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 632 if (checkArgCount(S, Call, 2)) 633 return true; 634 635 if (checkOpenCLPipeArg(S, Call)) 636 return true; 637 638 // Check the reserve size. 639 if (!Call->getArg(1)->getType()->isIntegerType() && 640 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 641 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 642 << Call->getDirectCallee() << S.Context.UnsignedIntTy 643 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 644 return true; 645 } 646 647 return false; 648 } 649 650 // \brief Performs a semantic analysis on {work_group_/sub_group_ 651 // /_}commit_{read/write}_pipe 652 // \param S Reference to the semantic analyzer. 653 // \param Call The call to the builtin function to be analyzed. 654 // \return True if a semantic error was found, false otherwise. 655 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 656 if (checkArgCount(S, Call, 2)) 657 return true; 658 659 if (checkOpenCLPipeArg(S, Call)) 660 return true; 661 662 // Check reserve_id_t. 663 if (!Call->getArg(1)->getType()->isReserveIDT()) { 664 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 665 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 666 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 667 return true; 668 } 669 670 return false; 671 } 672 673 // \brief Performs a semantic analysis on the call to built-in Pipe 674 // Query Functions. 675 // \param S Reference to the semantic analyzer. 676 // \param Call The call to the builtin function to be analyzed. 677 // \return True if a semantic error was found, false otherwise. 678 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 679 if (checkArgCount(S, Call, 1)) 680 return true; 681 682 if (!Call->getArg(0)->getType()->isPipeType()) { 683 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 684 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 685 return true; 686 } 687 688 return false; 689 } 690 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions. 691 // \brief Performs semantic analysis for the to_global/local/private call. 692 // \param S Reference to the semantic analyzer. 693 // \param BuiltinID ID of the builtin function. 694 // \param Call A pointer to the builtin call. 695 // \return True if a semantic error has been found, false otherwise. 696 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 697 CallExpr *Call) { 698 if (Call->getNumArgs() != 1) { 699 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 700 << Call->getDirectCallee() << Call->getSourceRange(); 701 return true; 702 } 703 704 auto RT = Call->getArg(0)->getType(); 705 if (!RT->isPointerType() || RT->getPointeeType() 706 .getAddressSpace() == LangAS::opencl_constant) { 707 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 708 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 709 return true; 710 } 711 712 RT = RT->getPointeeType(); 713 auto Qual = RT.getQualifiers(); 714 switch (BuiltinID) { 715 case Builtin::BIto_global: 716 Qual.setAddressSpace(LangAS::opencl_global); 717 break; 718 case Builtin::BIto_local: 719 Qual.setAddressSpace(LangAS::opencl_local); 720 break; 721 default: 722 Qual.removeAddressSpace(); 723 } 724 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 725 RT.getUnqualifiedType(), Qual))); 726 727 return false; 728 } 729 730 ExprResult 731 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 732 CallExpr *TheCall) { 733 ExprResult TheCallResult(TheCall); 734 735 // Find out if any arguments are required to be integer constant expressions. 736 unsigned ICEArguments = 0; 737 ASTContext::GetBuiltinTypeError Error; 738 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 739 if (Error != ASTContext::GE_None) 740 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 741 742 // If any arguments are required to be ICE's, check and diagnose. 743 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 744 // Skip arguments not required to be ICE's. 745 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 746 747 llvm::APSInt Result; 748 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 749 return true; 750 ICEArguments &= ~(1 << ArgNo); 751 } 752 753 switch (BuiltinID) { 754 case Builtin::BI__builtin___CFStringMakeConstantString: 755 assert(TheCall->getNumArgs() == 1 && 756 "Wrong # arguments to builtin CFStringMakeConstantString"); 757 if (CheckObjCString(TheCall->getArg(0))) 758 return ExprError(); 759 break; 760 case Builtin::BI__builtin_stdarg_start: 761 case Builtin::BI__builtin_va_start: 762 if (SemaBuiltinVAStart(TheCall)) 763 return ExprError(); 764 break; 765 case Builtin::BI__va_start: { 766 switch (Context.getTargetInfo().getTriple().getArch()) { 767 case llvm::Triple::arm: 768 case llvm::Triple::thumb: 769 if (SemaBuiltinVAStartARM(TheCall)) 770 return ExprError(); 771 break; 772 default: 773 if (SemaBuiltinVAStart(TheCall)) 774 return ExprError(); 775 break; 776 } 777 break; 778 } 779 case Builtin::BI__builtin_isgreater: 780 case Builtin::BI__builtin_isgreaterequal: 781 case Builtin::BI__builtin_isless: 782 case Builtin::BI__builtin_islessequal: 783 case Builtin::BI__builtin_islessgreater: 784 case Builtin::BI__builtin_isunordered: 785 if (SemaBuiltinUnorderedCompare(TheCall)) 786 return ExprError(); 787 break; 788 case Builtin::BI__builtin_fpclassify: 789 if (SemaBuiltinFPClassification(TheCall, 6)) 790 return ExprError(); 791 break; 792 case Builtin::BI__builtin_isfinite: 793 case Builtin::BI__builtin_isinf: 794 case Builtin::BI__builtin_isinf_sign: 795 case Builtin::BI__builtin_isnan: 796 case Builtin::BI__builtin_isnormal: 797 if (SemaBuiltinFPClassification(TheCall, 1)) 798 return ExprError(); 799 break; 800 case Builtin::BI__builtin_shufflevector: 801 return SemaBuiltinShuffleVector(TheCall); 802 // TheCall will be freed by the smart pointer here, but that's fine, since 803 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 804 case Builtin::BI__builtin_prefetch: 805 if (SemaBuiltinPrefetch(TheCall)) 806 return ExprError(); 807 break; 808 case Builtin::BI__builtin_alloca_with_align: 809 if (SemaBuiltinAllocaWithAlign(TheCall)) 810 return ExprError(); 811 break; 812 case Builtin::BI__assume: 813 case Builtin::BI__builtin_assume: 814 if (SemaBuiltinAssume(TheCall)) 815 return ExprError(); 816 break; 817 case Builtin::BI__builtin_assume_aligned: 818 if (SemaBuiltinAssumeAligned(TheCall)) 819 return ExprError(); 820 break; 821 case Builtin::BI__builtin_object_size: 822 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 823 return ExprError(); 824 break; 825 case Builtin::BI__builtin_longjmp: 826 if (SemaBuiltinLongjmp(TheCall)) 827 return ExprError(); 828 break; 829 case Builtin::BI__builtin_setjmp: 830 if (SemaBuiltinSetjmp(TheCall)) 831 return ExprError(); 832 break; 833 case Builtin::BI_setjmp: 834 case Builtin::BI_setjmpex: 835 if (checkArgCount(*this, TheCall, 1)) 836 return true; 837 break; 838 839 case Builtin::BI__builtin_classify_type: 840 if (checkArgCount(*this, TheCall, 1)) return true; 841 TheCall->setType(Context.IntTy); 842 break; 843 case Builtin::BI__builtin_constant_p: 844 if (checkArgCount(*this, TheCall, 1)) return true; 845 TheCall->setType(Context.IntTy); 846 break; 847 case Builtin::BI__sync_fetch_and_add: 848 case Builtin::BI__sync_fetch_and_add_1: 849 case Builtin::BI__sync_fetch_and_add_2: 850 case Builtin::BI__sync_fetch_and_add_4: 851 case Builtin::BI__sync_fetch_and_add_8: 852 case Builtin::BI__sync_fetch_and_add_16: 853 case Builtin::BI__sync_fetch_and_sub: 854 case Builtin::BI__sync_fetch_and_sub_1: 855 case Builtin::BI__sync_fetch_and_sub_2: 856 case Builtin::BI__sync_fetch_and_sub_4: 857 case Builtin::BI__sync_fetch_and_sub_8: 858 case Builtin::BI__sync_fetch_and_sub_16: 859 case Builtin::BI__sync_fetch_and_or: 860 case Builtin::BI__sync_fetch_and_or_1: 861 case Builtin::BI__sync_fetch_and_or_2: 862 case Builtin::BI__sync_fetch_and_or_4: 863 case Builtin::BI__sync_fetch_and_or_8: 864 case Builtin::BI__sync_fetch_and_or_16: 865 case Builtin::BI__sync_fetch_and_and: 866 case Builtin::BI__sync_fetch_and_and_1: 867 case Builtin::BI__sync_fetch_and_and_2: 868 case Builtin::BI__sync_fetch_and_and_4: 869 case Builtin::BI__sync_fetch_and_and_8: 870 case Builtin::BI__sync_fetch_and_and_16: 871 case Builtin::BI__sync_fetch_and_xor: 872 case Builtin::BI__sync_fetch_and_xor_1: 873 case Builtin::BI__sync_fetch_and_xor_2: 874 case Builtin::BI__sync_fetch_and_xor_4: 875 case Builtin::BI__sync_fetch_and_xor_8: 876 case Builtin::BI__sync_fetch_and_xor_16: 877 case Builtin::BI__sync_fetch_and_nand: 878 case Builtin::BI__sync_fetch_and_nand_1: 879 case Builtin::BI__sync_fetch_and_nand_2: 880 case Builtin::BI__sync_fetch_and_nand_4: 881 case Builtin::BI__sync_fetch_and_nand_8: 882 case Builtin::BI__sync_fetch_and_nand_16: 883 case Builtin::BI__sync_add_and_fetch: 884 case Builtin::BI__sync_add_and_fetch_1: 885 case Builtin::BI__sync_add_and_fetch_2: 886 case Builtin::BI__sync_add_and_fetch_4: 887 case Builtin::BI__sync_add_and_fetch_8: 888 case Builtin::BI__sync_add_and_fetch_16: 889 case Builtin::BI__sync_sub_and_fetch: 890 case Builtin::BI__sync_sub_and_fetch_1: 891 case Builtin::BI__sync_sub_and_fetch_2: 892 case Builtin::BI__sync_sub_and_fetch_4: 893 case Builtin::BI__sync_sub_and_fetch_8: 894 case Builtin::BI__sync_sub_and_fetch_16: 895 case Builtin::BI__sync_and_and_fetch: 896 case Builtin::BI__sync_and_and_fetch_1: 897 case Builtin::BI__sync_and_and_fetch_2: 898 case Builtin::BI__sync_and_and_fetch_4: 899 case Builtin::BI__sync_and_and_fetch_8: 900 case Builtin::BI__sync_and_and_fetch_16: 901 case Builtin::BI__sync_or_and_fetch: 902 case Builtin::BI__sync_or_and_fetch_1: 903 case Builtin::BI__sync_or_and_fetch_2: 904 case Builtin::BI__sync_or_and_fetch_4: 905 case Builtin::BI__sync_or_and_fetch_8: 906 case Builtin::BI__sync_or_and_fetch_16: 907 case Builtin::BI__sync_xor_and_fetch: 908 case Builtin::BI__sync_xor_and_fetch_1: 909 case Builtin::BI__sync_xor_and_fetch_2: 910 case Builtin::BI__sync_xor_and_fetch_4: 911 case Builtin::BI__sync_xor_and_fetch_8: 912 case Builtin::BI__sync_xor_and_fetch_16: 913 case Builtin::BI__sync_nand_and_fetch: 914 case Builtin::BI__sync_nand_and_fetch_1: 915 case Builtin::BI__sync_nand_and_fetch_2: 916 case Builtin::BI__sync_nand_and_fetch_4: 917 case Builtin::BI__sync_nand_and_fetch_8: 918 case Builtin::BI__sync_nand_and_fetch_16: 919 case Builtin::BI__sync_val_compare_and_swap: 920 case Builtin::BI__sync_val_compare_and_swap_1: 921 case Builtin::BI__sync_val_compare_and_swap_2: 922 case Builtin::BI__sync_val_compare_and_swap_4: 923 case Builtin::BI__sync_val_compare_and_swap_8: 924 case Builtin::BI__sync_val_compare_and_swap_16: 925 case Builtin::BI__sync_bool_compare_and_swap: 926 case Builtin::BI__sync_bool_compare_and_swap_1: 927 case Builtin::BI__sync_bool_compare_and_swap_2: 928 case Builtin::BI__sync_bool_compare_and_swap_4: 929 case Builtin::BI__sync_bool_compare_and_swap_8: 930 case Builtin::BI__sync_bool_compare_and_swap_16: 931 case Builtin::BI__sync_lock_test_and_set: 932 case Builtin::BI__sync_lock_test_and_set_1: 933 case Builtin::BI__sync_lock_test_and_set_2: 934 case Builtin::BI__sync_lock_test_and_set_4: 935 case Builtin::BI__sync_lock_test_and_set_8: 936 case Builtin::BI__sync_lock_test_and_set_16: 937 case Builtin::BI__sync_lock_release: 938 case Builtin::BI__sync_lock_release_1: 939 case Builtin::BI__sync_lock_release_2: 940 case Builtin::BI__sync_lock_release_4: 941 case Builtin::BI__sync_lock_release_8: 942 case Builtin::BI__sync_lock_release_16: 943 case Builtin::BI__sync_swap: 944 case Builtin::BI__sync_swap_1: 945 case Builtin::BI__sync_swap_2: 946 case Builtin::BI__sync_swap_4: 947 case Builtin::BI__sync_swap_8: 948 case Builtin::BI__sync_swap_16: 949 return SemaBuiltinAtomicOverloaded(TheCallResult); 950 case Builtin::BI__builtin_nontemporal_load: 951 case Builtin::BI__builtin_nontemporal_store: 952 return SemaBuiltinNontemporalOverloaded(TheCallResult); 953 #define BUILTIN(ID, TYPE, ATTRS) 954 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 955 case Builtin::BI##ID: \ 956 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 957 #include "clang/Basic/Builtins.def" 958 case Builtin::BI__builtin_annotation: 959 if (SemaBuiltinAnnotation(*this, TheCall)) 960 return ExprError(); 961 break; 962 case Builtin::BI__builtin_addressof: 963 if (SemaBuiltinAddressof(*this, TheCall)) 964 return ExprError(); 965 break; 966 case Builtin::BI__builtin_add_overflow: 967 case Builtin::BI__builtin_sub_overflow: 968 case Builtin::BI__builtin_mul_overflow: 969 if (SemaBuiltinOverflow(*this, TheCall)) 970 return ExprError(); 971 break; 972 case Builtin::BI__builtin_operator_new: 973 case Builtin::BI__builtin_operator_delete: 974 if (!getLangOpts().CPlusPlus) { 975 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 976 << (BuiltinID == Builtin::BI__builtin_operator_new 977 ? "__builtin_operator_new" 978 : "__builtin_operator_delete") 979 << "C++"; 980 return ExprError(); 981 } 982 // CodeGen assumes it can find the global new and delete to call, 983 // so ensure that they are declared. 984 DeclareGlobalNewDelete(); 985 break; 986 987 // check secure string manipulation functions where overflows 988 // are detectable at compile time 989 case Builtin::BI__builtin___memcpy_chk: 990 case Builtin::BI__builtin___memmove_chk: 991 case Builtin::BI__builtin___memset_chk: 992 case Builtin::BI__builtin___strlcat_chk: 993 case Builtin::BI__builtin___strlcpy_chk: 994 case Builtin::BI__builtin___strncat_chk: 995 case Builtin::BI__builtin___strncpy_chk: 996 case Builtin::BI__builtin___stpncpy_chk: 997 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 998 break; 999 case Builtin::BI__builtin___memccpy_chk: 1000 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 1001 break; 1002 case Builtin::BI__builtin___snprintf_chk: 1003 case Builtin::BI__builtin___vsnprintf_chk: 1004 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 1005 break; 1006 case Builtin::BI__builtin_call_with_static_chain: 1007 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1008 return ExprError(); 1009 break; 1010 case Builtin::BI__exception_code: 1011 case Builtin::BI_exception_code: 1012 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1013 diag::err_seh___except_block)) 1014 return ExprError(); 1015 break; 1016 case Builtin::BI__exception_info: 1017 case Builtin::BI_exception_info: 1018 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1019 diag::err_seh___except_filter)) 1020 return ExprError(); 1021 break; 1022 case Builtin::BI__GetExceptionInfo: 1023 if (checkArgCount(*this, TheCall, 1)) 1024 return ExprError(); 1025 1026 if (CheckCXXThrowOperand( 1027 TheCall->getLocStart(), 1028 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1029 TheCall)) 1030 return ExprError(); 1031 1032 TheCall->setType(Context.VoidPtrTy); 1033 break; 1034 // OpenCL v2.0, s6.13.16 - Pipe functions 1035 case Builtin::BIread_pipe: 1036 case Builtin::BIwrite_pipe: 1037 // Since those two functions are declared with var args, we need a semantic 1038 // check for the argument. 1039 if (SemaBuiltinRWPipe(*this, TheCall)) 1040 return ExprError(); 1041 TheCall->setType(Context.IntTy); 1042 break; 1043 case Builtin::BIreserve_read_pipe: 1044 case Builtin::BIreserve_write_pipe: 1045 case Builtin::BIwork_group_reserve_read_pipe: 1046 case Builtin::BIwork_group_reserve_write_pipe: 1047 case Builtin::BIsub_group_reserve_read_pipe: 1048 case Builtin::BIsub_group_reserve_write_pipe: 1049 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1050 return ExprError(); 1051 // Since return type of reserve_read/write_pipe built-in function is 1052 // reserve_id_t, which is not defined in the builtin def file , we used int 1053 // as return type and need to override the return type of these functions. 1054 TheCall->setType(Context.OCLReserveIDTy); 1055 break; 1056 case Builtin::BIcommit_read_pipe: 1057 case Builtin::BIcommit_write_pipe: 1058 case Builtin::BIwork_group_commit_read_pipe: 1059 case Builtin::BIwork_group_commit_write_pipe: 1060 case Builtin::BIsub_group_commit_read_pipe: 1061 case Builtin::BIsub_group_commit_write_pipe: 1062 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1063 return ExprError(); 1064 break; 1065 case Builtin::BIget_pipe_num_packets: 1066 case Builtin::BIget_pipe_max_packets: 1067 if (SemaBuiltinPipePackets(*this, TheCall)) 1068 return ExprError(); 1069 TheCall->setType(Context.UnsignedIntTy); 1070 break; 1071 case Builtin::BIto_global: 1072 case Builtin::BIto_local: 1073 case Builtin::BIto_private: 1074 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1075 return ExprError(); 1076 break; 1077 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1078 case Builtin::BIenqueue_kernel: 1079 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1080 return ExprError(); 1081 break; 1082 case Builtin::BIget_kernel_work_group_size: 1083 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1084 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1085 return ExprError(); 1086 break; 1087 case Builtin::BI__builtin_os_log_format: 1088 case Builtin::BI__builtin_os_log_format_buffer_size: 1089 if (SemaBuiltinOSLogFormat(TheCall)) { 1090 return ExprError(); 1091 } 1092 break; 1093 } 1094 1095 // Since the target specific builtins for each arch overlap, only check those 1096 // of the arch we are compiling for. 1097 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1098 switch (Context.getTargetInfo().getTriple().getArch()) { 1099 case llvm::Triple::arm: 1100 case llvm::Triple::armeb: 1101 case llvm::Triple::thumb: 1102 case llvm::Triple::thumbeb: 1103 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1104 return ExprError(); 1105 break; 1106 case llvm::Triple::aarch64: 1107 case llvm::Triple::aarch64_be: 1108 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1109 return ExprError(); 1110 break; 1111 case llvm::Triple::mips: 1112 case llvm::Triple::mipsel: 1113 case llvm::Triple::mips64: 1114 case llvm::Triple::mips64el: 1115 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1116 return ExprError(); 1117 break; 1118 case llvm::Triple::systemz: 1119 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1120 return ExprError(); 1121 break; 1122 case llvm::Triple::x86: 1123 case llvm::Triple::x86_64: 1124 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1125 return ExprError(); 1126 break; 1127 case llvm::Triple::ppc: 1128 case llvm::Triple::ppc64: 1129 case llvm::Triple::ppc64le: 1130 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1131 return ExprError(); 1132 break; 1133 default: 1134 break; 1135 } 1136 } 1137 1138 return TheCallResult; 1139 } 1140 1141 // Get the valid immediate range for the specified NEON type code. 1142 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1143 NeonTypeFlags Type(t); 1144 int IsQuad = ForceQuad ? true : Type.isQuad(); 1145 switch (Type.getEltType()) { 1146 case NeonTypeFlags::Int8: 1147 case NeonTypeFlags::Poly8: 1148 return shift ? 7 : (8 << IsQuad) - 1; 1149 case NeonTypeFlags::Int16: 1150 case NeonTypeFlags::Poly16: 1151 return shift ? 15 : (4 << IsQuad) - 1; 1152 case NeonTypeFlags::Int32: 1153 return shift ? 31 : (2 << IsQuad) - 1; 1154 case NeonTypeFlags::Int64: 1155 case NeonTypeFlags::Poly64: 1156 return shift ? 63 : (1 << IsQuad) - 1; 1157 case NeonTypeFlags::Poly128: 1158 return shift ? 127 : (1 << IsQuad) - 1; 1159 case NeonTypeFlags::Float16: 1160 assert(!shift && "cannot shift float types!"); 1161 return (4 << IsQuad) - 1; 1162 case NeonTypeFlags::Float32: 1163 assert(!shift && "cannot shift float types!"); 1164 return (2 << IsQuad) - 1; 1165 case NeonTypeFlags::Float64: 1166 assert(!shift && "cannot shift float types!"); 1167 return (1 << IsQuad) - 1; 1168 } 1169 llvm_unreachable("Invalid NeonTypeFlag!"); 1170 } 1171 1172 /// getNeonEltType - Return the QualType corresponding to the elements of 1173 /// the vector type specified by the NeonTypeFlags. This is used to check 1174 /// the pointer arguments for Neon load/store intrinsics. 1175 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1176 bool IsPolyUnsigned, bool IsInt64Long) { 1177 switch (Flags.getEltType()) { 1178 case NeonTypeFlags::Int8: 1179 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1180 case NeonTypeFlags::Int16: 1181 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1182 case NeonTypeFlags::Int32: 1183 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1184 case NeonTypeFlags::Int64: 1185 if (IsInt64Long) 1186 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1187 else 1188 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1189 : Context.LongLongTy; 1190 case NeonTypeFlags::Poly8: 1191 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1192 case NeonTypeFlags::Poly16: 1193 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1194 case NeonTypeFlags::Poly64: 1195 if (IsInt64Long) 1196 return Context.UnsignedLongTy; 1197 else 1198 return Context.UnsignedLongLongTy; 1199 case NeonTypeFlags::Poly128: 1200 break; 1201 case NeonTypeFlags::Float16: 1202 return Context.HalfTy; 1203 case NeonTypeFlags::Float32: 1204 return Context.FloatTy; 1205 case NeonTypeFlags::Float64: 1206 return Context.DoubleTy; 1207 } 1208 llvm_unreachable("Invalid NeonTypeFlag!"); 1209 } 1210 1211 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1212 llvm::APSInt Result; 1213 uint64_t mask = 0; 1214 unsigned TV = 0; 1215 int PtrArgNum = -1; 1216 bool HasConstPtr = false; 1217 switch (BuiltinID) { 1218 #define GET_NEON_OVERLOAD_CHECK 1219 #include "clang/Basic/arm_neon.inc" 1220 #undef GET_NEON_OVERLOAD_CHECK 1221 } 1222 1223 // For NEON intrinsics which are overloaded on vector element type, validate 1224 // the immediate which specifies which variant to emit. 1225 unsigned ImmArg = TheCall->getNumArgs()-1; 1226 if (mask) { 1227 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1228 return true; 1229 1230 TV = Result.getLimitedValue(64); 1231 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1232 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1233 << TheCall->getArg(ImmArg)->getSourceRange(); 1234 } 1235 1236 if (PtrArgNum >= 0) { 1237 // Check that pointer arguments have the specified type. 1238 Expr *Arg = TheCall->getArg(PtrArgNum); 1239 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1240 Arg = ICE->getSubExpr(); 1241 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1242 QualType RHSTy = RHS.get()->getType(); 1243 1244 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1245 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1246 Arch == llvm::Triple::aarch64_be; 1247 bool IsInt64Long = 1248 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1249 QualType EltTy = 1250 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1251 if (HasConstPtr) 1252 EltTy = EltTy.withConst(); 1253 QualType LHSTy = Context.getPointerType(EltTy); 1254 AssignConvertType ConvTy; 1255 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1256 if (RHS.isInvalid()) 1257 return true; 1258 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1259 RHS.get(), AA_Assigning)) 1260 return true; 1261 } 1262 1263 // For NEON intrinsics which take an immediate value as part of the 1264 // instruction, range check them here. 1265 unsigned i = 0, l = 0, u = 0; 1266 switch (BuiltinID) { 1267 default: 1268 return false; 1269 #define GET_NEON_IMMEDIATE_CHECK 1270 #include "clang/Basic/arm_neon.inc" 1271 #undef GET_NEON_IMMEDIATE_CHECK 1272 } 1273 1274 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1275 } 1276 1277 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1278 unsigned MaxWidth) { 1279 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1280 BuiltinID == ARM::BI__builtin_arm_ldaex || 1281 BuiltinID == ARM::BI__builtin_arm_strex || 1282 BuiltinID == ARM::BI__builtin_arm_stlex || 1283 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1284 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1285 BuiltinID == AArch64::BI__builtin_arm_strex || 1286 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1287 "unexpected ARM builtin"); 1288 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1289 BuiltinID == ARM::BI__builtin_arm_ldaex || 1290 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1291 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1292 1293 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1294 1295 // Ensure that we have the proper number of arguments. 1296 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1297 return true; 1298 1299 // Inspect the pointer argument of the atomic builtin. This should always be 1300 // a pointer type, whose element is an integral scalar or pointer type. 1301 // Because it is a pointer type, we don't have to worry about any implicit 1302 // casts here. 1303 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1304 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1305 if (PointerArgRes.isInvalid()) 1306 return true; 1307 PointerArg = PointerArgRes.get(); 1308 1309 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1310 if (!pointerType) { 1311 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1312 << PointerArg->getType() << PointerArg->getSourceRange(); 1313 return true; 1314 } 1315 1316 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1317 // task is to insert the appropriate casts into the AST. First work out just 1318 // what the appropriate type is. 1319 QualType ValType = pointerType->getPointeeType(); 1320 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1321 if (IsLdrex) 1322 AddrType.addConst(); 1323 1324 // Issue a warning if the cast is dodgy. 1325 CastKind CastNeeded = CK_NoOp; 1326 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1327 CastNeeded = CK_BitCast; 1328 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1329 << PointerArg->getType() 1330 << Context.getPointerType(AddrType) 1331 << AA_Passing << PointerArg->getSourceRange(); 1332 } 1333 1334 // Finally, do the cast and replace the argument with the corrected version. 1335 AddrType = Context.getPointerType(AddrType); 1336 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1337 if (PointerArgRes.isInvalid()) 1338 return true; 1339 PointerArg = PointerArgRes.get(); 1340 1341 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1342 1343 // In general, we allow ints, floats and pointers to be loaded and stored. 1344 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1345 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1346 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1347 << PointerArg->getType() << PointerArg->getSourceRange(); 1348 return true; 1349 } 1350 1351 // But ARM doesn't have instructions to deal with 128-bit versions. 1352 if (Context.getTypeSize(ValType) > MaxWidth) { 1353 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1354 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1355 << PointerArg->getType() << PointerArg->getSourceRange(); 1356 return true; 1357 } 1358 1359 switch (ValType.getObjCLifetime()) { 1360 case Qualifiers::OCL_None: 1361 case Qualifiers::OCL_ExplicitNone: 1362 // okay 1363 break; 1364 1365 case Qualifiers::OCL_Weak: 1366 case Qualifiers::OCL_Strong: 1367 case Qualifiers::OCL_Autoreleasing: 1368 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1369 << ValType << PointerArg->getSourceRange(); 1370 return true; 1371 } 1372 1373 if (IsLdrex) { 1374 TheCall->setType(ValType); 1375 return false; 1376 } 1377 1378 // Initialize the argument to be stored. 1379 ExprResult ValArg = TheCall->getArg(0); 1380 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1381 Context, ValType, /*consume*/ false); 1382 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1383 if (ValArg.isInvalid()) 1384 return true; 1385 TheCall->setArg(0, ValArg.get()); 1386 1387 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1388 // but the custom checker bypasses all default analysis. 1389 TheCall->setType(Context.IntTy); 1390 return false; 1391 } 1392 1393 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1394 llvm::APSInt Result; 1395 1396 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1397 BuiltinID == ARM::BI__builtin_arm_ldaex || 1398 BuiltinID == ARM::BI__builtin_arm_strex || 1399 BuiltinID == ARM::BI__builtin_arm_stlex) { 1400 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1401 } 1402 1403 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1404 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1405 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1406 } 1407 1408 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1409 BuiltinID == ARM::BI__builtin_arm_wsr64) 1410 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1411 1412 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1413 BuiltinID == ARM::BI__builtin_arm_rsrp || 1414 BuiltinID == ARM::BI__builtin_arm_wsr || 1415 BuiltinID == ARM::BI__builtin_arm_wsrp) 1416 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1417 1418 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1419 return true; 1420 1421 // For intrinsics which take an immediate value as part of the instruction, 1422 // range check them here. 1423 unsigned i = 0, l = 0, u = 0; 1424 switch (BuiltinID) { 1425 default: return false; 1426 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 1427 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 1428 case ARM::BI__builtin_arm_vcvtr_f: 1429 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 1430 case ARM::BI__builtin_arm_dmb: 1431 case ARM::BI__builtin_arm_dsb: 1432 case ARM::BI__builtin_arm_isb: 1433 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break; 1434 } 1435 1436 // FIXME: VFP Intrinsics should error if VFP not present. 1437 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1438 } 1439 1440 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1441 CallExpr *TheCall) { 1442 llvm::APSInt Result; 1443 1444 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1445 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1446 BuiltinID == AArch64::BI__builtin_arm_strex || 1447 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1448 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1449 } 1450 1451 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1452 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1453 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1454 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1455 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1456 } 1457 1458 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1459 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1460 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1461 1462 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1463 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1464 BuiltinID == AArch64::BI__builtin_arm_wsr || 1465 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1466 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1467 1468 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1469 return true; 1470 1471 // For intrinsics which take an immediate value as part of the instruction, 1472 // range check them here. 1473 unsigned i = 0, l = 0, u = 0; 1474 switch (BuiltinID) { 1475 default: return false; 1476 case AArch64::BI__builtin_arm_dmb: 1477 case AArch64::BI__builtin_arm_dsb: 1478 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1479 } 1480 1481 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1482 } 1483 1484 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1485 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1486 // ordering for DSP is unspecified. MSA is ordered by the data format used 1487 // by the underlying instruction i.e., df/m, df/n and then by size. 1488 // 1489 // FIXME: The size tests here should instead be tablegen'd along with the 1490 // definitions from include/clang/Basic/BuiltinsMips.def. 1491 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1492 // be too. 1493 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1494 unsigned i = 0, l = 0, u = 0, m = 0; 1495 switch (BuiltinID) { 1496 default: return false; 1497 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1498 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1499 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1500 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1501 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1502 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1503 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1504 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1505 // df/m field. 1506 // These intrinsics take an unsigned 3 bit immediate. 1507 case Mips::BI__builtin_msa_bclri_b: 1508 case Mips::BI__builtin_msa_bnegi_b: 1509 case Mips::BI__builtin_msa_bseti_b: 1510 case Mips::BI__builtin_msa_sat_s_b: 1511 case Mips::BI__builtin_msa_sat_u_b: 1512 case Mips::BI__builtin_msa_slli_b: 1513 case Mips::BI__builtin_msa_srai_b: 1514 case Mips::BI__builtin_msa_srari_b: 1515 case Mips::BI__builtin_msa_srli_b: 1516 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1517 case Mips::BI__builtin_msa_binsli_b: 1518 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1519 // These intrinsics take an unsigned 4 bit immediate. 1520 case Mips::BI__builtin_msa_bclri_h: 1521 case Mips::BI__builtin_msa_bnegi_h: 1522 case Mips::BI__builtin_msa_bseti_h: 1523 case Mips::BI__builtin_msa_sat_s_h: 1524 case Mips::BI__builtin_msa_sat_u_h: 1525 case Mips::BI__builtin_msa_slli_h: 1526 case Mips::BI__builtin_msa_srai_h: 1527 case Mips::BI__builtin_msa_srari_h: 1528 case Mips::BI__builtin_msa_srli_h: 1529 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1530 case Mips::BI__builtin_msa_binsli_h: 1531 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 1532 // These intrinsics take an unsigned 5 bit immedate. 1533 // The first block of intrinsics actually have an unsigned 5 bit field, 1534 // not a df/n field. 1535 case Mips::BI__builtin_msa_clei_u_b: 1536 case Mips::BI__builtin_msa_clei_u_h: 1537 case Mips::BI__builtin_msa_clei_u_w: 1538 case Mips::BI__builtin_msa_clei_u_d: 1539 case Mips::BI__builtin_msa_clti_u_b: 1540 case Mips::BI__builtin_msa_clti_u_h: 1541 case Mips::BI__builtin_msa_clti_u_w: 1542 case Mips::BI__builtin_msa_clti_u_d: 1543 case Mips::BI__builtin_msa_maxi_u_b: 1544 case Mips::BI__builtin_msa_maxi_u_h: 1545 case Mips::BI__builtin_msa_maxi_u_w: 1546 case Mips::BI__builtin_msa_maxi_u_d: 1547 case Mips::BI__builtin_msa_mini_u_b: 1548 case Mips::BI__builtin_msa_mini_u_h: 1549 case Mips::BI__builtin_msa_mini_u_w: 1550 case Mips::BI__builtin_msa_mini_u_d: 1551 case Mips::BI__builtin_msa_addvi_b: 1552 case Mips::BI__builtin_msa_addvi_h: 1553 case Mips::BI__builtin_msa_addvi_w: 1554 case Mips::BI__builtin_msa_addvi_d: 1555 case Mips::BI__builtin_msa_bclri_w: 1556 case Mips::BI__builtin_msa_bnegi_w: 1557 case Mips::BI__builtin_msa_bseti_w: 1558 case Mips::BI__builtin_msa_sat_s_w: 1559 case Mips::BI__builtin_msa_sat_u_w: 1560 case Mips::BI__builtin_msa_slli_w: 1561 case Mips::BI__builtin_msa_srai_w: 1562 case Mips::BI__builtin_msa_srari_w: 1563 case Mips::BI__builtin_msa_srli_w: 1564 case Mips::BI__builtin_msa_srlri_w: 1565 case Mips::BI__builtin_msa_subvi_b: 1566 case Mips::BI__builtin_msa_subvi_h: 1567 case Mips::BI__builtin_msa_subvi_w: 1568 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 1569 case Mips::BI__builtin_msa_binsli_w: 1570 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 1571 // These intrinsics take an unsigned 6 bit immediate. 1572 case Mips::BI__builtin_msa_bclri_d: 1573 case Mips::BI__builtin_msa_bnegi_d: 1574 case Mips::BI__builtin_msa_bseti_d: 1575 case Mips::BI__builtin_msa_sat_s_d: 1576 case Mips::BI__builtin_msa_sat_u_d: 1577 case Mips::BI__builtin_msa_slli_d: 1578 case Mips::BI__builtin_msa_srai_d: 1579 case Mips::BI__builtin_msa_srari_d: 1580 case Mips::BI__builtin_msa_srli_d: 1581 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 1582 case Mips::BI__builtin_msa_binsli_d: 1583 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 1584 // These intrinsics take a signed 5 bit immediate. 1585 case Mips::BI__builtin_msa_ceqi_b: 1586 case Mips::BI__builtin_msa_ceqi_h: 1587 case Mips::BI__builtin_msa_ceqi_w: 1588 case Mips::BI__builtin_msa_ceqi_d: 1589 case Mips::BI__builtin_msa_clti_s_b: 1590 case Mips::BI__builtin_msa_clti_s_h: 1591 case Mips::BI__builtin_msa_clti_s_w: 1592 case Mips::BI__builtin_msa_clti_s_d: 1593 case Mips::BI__builtin_msa_clei_s_b: 1594 case Mips::BI__builtin_msa_clei_s_h: 1595 case Mips::BI__builtin_msa_clei_s_w: 1596 case Mips::BI__builtin_msa_clei_s_d: 1597 case Mips::BI__builtin_msa_maxi_s_b: 1598 case Mips::BI__builtin_msa_maxi_s_h: 1599 case Mips::BI__builtin_msa_maxi_s_w: 1600 case Mips::BI__builtin_msa_maxi_s_d: 1601 case Mips::BI__builtin_msa_mini_s_b: 1602 case Mips::BI__builtin_msa_mini_s_h: 1603 case Mips::BI__builtin_msa_mini_s_w: 1604 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 1605 // These intrinsics take an unsigned 8 bit immediate. 1606 case Mips::BI__builtin_msa_andi_b: 1607 case Mips::BI__builtin_msa_nori_b: 1608 case Mips::BI__builtin_msa_ori_b: 1609 case Mips::BI__builtin_msa_shf_b: 1610 case Mips::BI__builtin_msa_shf_h: 1611 case Mips::BI__builtin_msa_shf_w: 1612 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 1613 case Mips::BI__builtin_msa_bseli_b: 1614 case Mips::BI__builtin_msa_bmnzi_b: 1615 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 1616 // df/n format 1617 // These intrinsics take an unsigned 4 bit immediate. 1618 case Mips::BI__builtin_msa_copy_s_b: 1619 case Mips::BI__builtin_msa_copy_u_b: 1620 case Mips::BI__builtin_msa_insve_b: 1621 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 1622 case Mips::BI__builtin_msa_sld_b: 1623 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 1624 // These intrinsics take an unsigned 3 bit immediate. 1625 case Mips::BI__builtin_msa_copy_s_h: 1626 case Mips::BI__builtin_msa_copy_u_h: 1627 case Mips::BI__builtin_msa_insve_h: 1628 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 1629 case Mips::BI__builtin_msa_sld_h: 1630 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 1631 // These intrinsics take an unsigned 2 bit immediate. 1632 case Mips::BI__builtin_msa_copy_s_w: 1633 case Mips::BI__builtin_msa_copy_u_w: 1634 case Mips::BI__builtin_msa_insve_w: 1635 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 1636 case Mips::BI__builtin_msa_sld_w: 1637 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 1638 // These intrinsics take an unsigned 1 bit immediate. 1639 case Mips::BI__builtin_msa_copy_s_d: 1640 case Mips::BI__builtin_msa_copy_u_d: 1641 case Mips::BI__builtin_msa_insve_d: 1642 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 1643 case Mips::BI__builtin_msa_sld_d: 1644 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 1645 // Memory offsets and immediate loads. 1646 // These intrinsics take a signed 10 bit immediate. 1647 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break; 1648 case Mips::BI__builtin_msa_ldi_h: 1649 case Mips::BI__builtin_msa_ldi_w: 1650 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 1651 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 1652 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 1653 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 1654 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 1655 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 1656 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 1657 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 1658 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 1659 } 1660 1661 if (!m) 1662 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1663 1664 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 1665 SemaBuiltinConstantArgMultiple(TheCall, i, m); 1666 } 1667 1668 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1669 unsigned i = 0, l = 0, u = 0; 1670 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 1671 BuiltinID == PPC::BI__builtin_divdeu || 1672 BuiltinID == PPC::BI__builtin_bpermd; 1673 bool IsTarget64Bit = Context.getTargetInfo() 1674 .getTypeWidth(Context 1675 .getTargetInfo() 1676 .getIntPtrType()) == 64; 1677 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 1678 BuiltinID == PPC::BI__builtin_divweu || 1679 BuiltinID == PPC::BI__builtin_divde || 1680 BuiltinID == PPC::BI__builtin_divdeu; 1681 1682 if (Is64BitBltin && !IsTarget64Bit) 1683 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 1684 << TheCall->getSourceRange(); 1685 1686 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 1687 (BuiltinID == PPC::BI__builtin_bpermd && 1688 !Context.getTargetInfo().hasFeature("bpermd"))) 1689 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 1690 << TheCall->getSourceRange(); 1691 1692 switch (BuiltinID) { 1693 default: return false; 1694 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 1695 case PPC::BI__builtin_altivec_crypto_vshasigmad: 1696 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1697 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1698 case PPC::BI__builtin_tbegin: 1699 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 1700 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 1701 case PPC::BI__builtin_tabortwc: 1702 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 1703 case PPC::BI__builtin_tabortwci: 1704 case PPC::BI__builtin_tabortdci: 1705 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 1706 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 1707 } 1708 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1709 } 1710 1711 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 1712 CallExpr *TheCall) { 1713 if (BuiltinID == SystemZ::BI__builtin_tabort) { 1714 Expr *Arg = TheCall->getArg(0); 1715 llvm::APSInt AbortCode(32); 1716 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 1717 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 1718 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 1719 << Arg->getSourceRange(); 1720 } 1721 1722 // For intrinsics which take an immediate value as part of the instruction, 1723 // range check them here. 1724 unsigned i = 0, l = 0, u = 0; 1725 switch (BuiltinID) { 1726 default: return false; 1727 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 1728 case SystemZ::BI__builtin_s390_verimb: 1729 case SystemZ::BI__builtin_s390_verimh: 1730 case SystemZ::BI__builtin_s390_verimf: 1731 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 1732 case SystemZ::BI__builtin_s390_vfaeb: 1733 case SystemZ::BI__builtin_s390_vfaeh: 1734 case SystemZ::BI__builtin_s390_vfaef: 1735 case SystemZ::BI__builtin_s390_vfaebs: 1736 case SystemZ::BI__builtin_s390_vfaehs: 1737 case SystemZ::BI__builtin_s390_vfaefs: 1738 case SystemZ::BI__builtin_s390_vfaezb: 1739 case SystemZ::BI__builtin_s390_vfaezh: 1740 case SystemZ::BI__builtin_s390_vfaezf: 1741 case SystemZ::BI__builtin_s390_vfaezbs: 1742 case SystemZ::BI__builtin_s390_vfaezhs: 1743 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 1744 case SystemZ::BI__builtin_s390_vfidb: 1745 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 1746 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1747 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 1748 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 1749 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 1750 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 1751 case SystemZ::BI__builtin_s390_vstrcb: 1752 case SystemZ::BI__builtin_s390_vstrch: 1753 case SystemZ::BI__builtin_s390_vstrcf: 1754 case SystemZ::BI__builtin_s390_vstrczb: 1755 case SystemZ::BI__builtin_s390_vstrczh: 1756 case SystemZ::BI__builtin_s390_vstrczf: 1757 case SystemZ::BI__builtin_s390_vstrcbs: 1758 case SystemZ::BI__builtin_s390_vstrchs: 1759 case SystemZ::BI__builtin_s390_vstrcfs: 1760 case SystemZ::BI__builtin_s390_vstrczbs: 1761 case SystemZ::BI__builtin_s390_vstrczhs: 1762 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 1763 } 1764 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1765 } 1766 1767 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 1768 /// This checks that the target supports __builtin_cpu_supports and 1769 /// that the string argument is constant and valid. 1770 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 1771 Expr *Arg = TheCall->getArg(0); 1772 1773 // Check if the argument is a string literal. 1774 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1775 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1776 << Arg->getSourceRange(); 1777 1778 // Check the contents of the string. 1779 StringRef Feature = 1780 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1781 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 1782 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 1783 << Arg->getSourceRange(); 1784 return false; 1785 } 1786 1787 // Check if the rounding mode is legal. 1788 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 1789 // Indicates if this instruction has rounding control or just SAE. 1790 bool HasRC = false; 1791 1792 unsigned ArgNum = 0; 1793 switch (BuiltinID) { 1794 default: 1795 return false; 1796 case X86::BI__builtin_ia32_vcvttsd2si32: 1797 case X86::BI__builtin_ia32_vcvttsd2si64: 1798 case X86::BI__builtin_ia32_vcvttsd2usi32: 1799 case X86::BI__builtin_ia32_vcvttsd2usi64: 1800 case X86::BI__builtin_ia32_vcvttss2si32: 1801 case X86::BI__builtin_ia32_vcvttss2si64: 1802 case X86::BI__builtin_ia32_vcvttss2usi32: 1803 case X86::BI__builtin_ia32_vcvttss2usi64: 1804 ArgNum = 1; 1805 break; 1806 case X86::BI__builtin_ia32_cvtps2pd512_mask: 1807 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 1808 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 1809 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 1810 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 1811 case X86::BI__builtin_ia32_cvttps2dq512_mask: 1812 case X86::BI__builtin_ia32_cvttps2qq512_mask: 1813 case X86::BI__builtin_ia32_cvttps2udq512_mask: 1814 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 1815 case X86::BI__builtin_ia32_exp2pd_mask: 1816 case X86::BI__builtin_ia32_exp2ps_mask: 1817 case X86::BI__builtin_ia32_getexppd512_mask: 1818 case X86::BI__builtin_ia32_getexpps512_mask: 1819 case X86::BI__builtin_ia32_rcp28pd_mask: 1820 case X86::BI__builtin_ia32_rcp28ps_mask: 1821 case X86::BI__builtin_ia32_rsqrt28pd_mask: 1822 case X86::BI__builtin_ia32_rsqrt28ps_mask: 1823 case X86::BI__builtin_ia32_vcomisd: 1824 case X86::BI__builtin_ia32_vcomiss: 1825 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 1826 ArgNum = 3; 1827 break; 1828 case X86::BI__builtin_ia32_cmppd512_mask: 1829 case X86::BI__builtin_ia32_cmpps512_mask: 1830 case X86::BI__builtin_ia32_cmpsd_mask: 1831 case X86::BI__builtin_ia32_cmpss_mask: 1832 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 1833 case X86::BI__builtin_ia32_getexpsd128_round_mask: 1834 case X86::BI__builtin_ia32_getexpss128_round_mask: 1835 case X86::BI__builtin_ia32_maxpd512_mask: 1836 case X86::BI__builtin_ia32_maxps512_mask: 1837 case X86::BI__builtin_ia32_maxsd_round_mask: 1838 case X86::BI__builtin_ia32_maxss_round_mask: 1839 case X86::BI__builtin_ia32_minpd512_mask: 1840 case X86::BI__builtin_ia32_minps512_mask: 1841 case X86::BI__builtin_ia32_minsd_round_mask: 1842 case X86::BI__builtin_ia32_minss_round_mask: 1843 case X86::BI__builtin_ia32_rcp28sd_round_mask: 1844 case X86::BI__builtin_ia32_rcp28ss_round_mask: 1845 case X86::BI__builtin_ia32_reducepd512_mask: 1846 case X86::BI__builtin_ia32_reduceps512_mask: 1847 case X86::BI__builtin_ia32_rndscalepd_mask: 1848 case X86::BI__builtin_ia32_rndscaleps_mask: 1849 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 1850 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 1851 ArgNum = 4; 1852 break; 1853 case X86::BI__builtin_ia32_fixupimmpd512_mask: 1854 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 1855 case X86::BI__builtin_ia32_fixupimmps512_mask: 1856 case X86::BI__builtin_ia32_fixupimmps512_maskz: 1857 case X86::BI__builtin_ia32_fixupimmsd_mask: 1858 case X86::BI__builtin_ia32_fixupimmsd_maskz: 1859 case X86::BI__builtin_ia32_fixupimmss_mask: 1860 case X86::BI__builtin_ia32_fixupimmss_maskz: 1861 case X86::BI__builtin_ia32_rangepd512_mask: 1862 case X86::BI__builtin_ia32_rangeps512_mask: 1863 case X86::BI__builtin_ia32_rangesd128_round_mask: 1864 case X86::BI__builtin_ia32_rangess128_round_mask: 1865 case X86::BI__builtin_ia32_reducesd_mask: 1866 case X86::BI__builtin_ia32_reducess_mask: 1867 case X86::BI__builtin_ia32_rndscalesd_round_mask: 1868 case X86::BI__builtin_ia32_rndscaless_round_mask: 1869 ArgNum = 5; 1870 break; 1871 case X86::BI__builtin_ia32_vcvtsd2si64: 1872 case X86::BI__builtin_ia32_vcvtsd2si32: 1873 case X86::BI__builtin_ia32_vcvtsd2usi32: 1874 case X86::BI__builtin_ia32_vcvtsd2usi64: 1875 case X86::BI__builtin_ia32_vcvtss2si32: 1876 case X86::BI__builtin_ia32_vcvtss2si64: 1877 case X86::BI__builtin_ia32_vcvtss2usi32: 1878 case X86::BI__builtin_ia32_vcvtss2usi64: 1879 ArgNum = 1; 1880 HasRC = true; 1881 break; 1882 case X86::BI__builtin_ia32_cvtsi2sd64: 1883 case X86::BI__builtin_ia32_cvtsi2ss32: 1884 case X86::BI__builtin_ia32_cvtsi2ss64: 1885 case X86::BI__builtin_ia32_cvtusi2sd64: 1886 case X86::BI__builtin_ia32_cvtusi2ss32: 1887 case X86::BI__builtin_ia32_cvtusi2ss64: 1888 ArgNum = 2; 1889 HasRC = true; 1890 break; 1891 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 1892 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 1893 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 1894 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 1895 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 1896 case X86::BI__builtin_ia32_cvtps2qq512_mask: 1897 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 1898 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 1899 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 1900 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 1901 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 1902 case X86::BI__builtin_ia32_sqrtpd512_mask: 1903 case X86::BI__builtin_ia32_sqrtps512_mask: 1904 ArgNum = 3; 1905 HasRC = true; 1906 break; 1907 case X86::BI__builtin_ia32_addpd512_mask: 1908 case X86::BI__builtin_ia32_addps512_mask: 1909 case X86::BI__builtin_ia32_divpd512_mask: 1910 case X86::BI__builtin_ia32_divps512_mask: 1911 case X86::BI__builtin_ia32_mulpd512_mask: 1912 case X86::BI__builtin_ia32_mulps512_mask: 1913 case X86::BI__builtin_ia32_subpd512_mask: 1914 case X86::BI__builtin_ia32_subps512_mask: 1915 case X86::BI__builtin_ia32_addss_round_mask: 1916 case X86::BI__builtin_ia32_addsd_round_mask: 1917 case X86::BI__builtin_ia32_divss_round_mask: 1918 case X86::BI__builtin_ia32_divsd_round_mask: 1919 case X86::BI__builtin_ia32_mulss_round_mask: 1920 case X86::BI__builtin_ia32_mulsd_round_mask: 1921 case X86::BI__builtin_ia32_subss_round_mask: 1922 case X86::BI__builtin_ia32_subsd_round_mask: 1923 case X86::BI__builtin_ia32_scalefpd512_mask: 1924 case X86::BI__builtin_ia32_scalefps512_mask: 1925 case X86::BI__builtin_ia32_scalefsd_round_mask: 1926 case X86::BI__builtin_ia32_scalefss_round_mask: 1927 case X86::BI__builtin_ia32_getmantpd512_mask: 1928 case X86::BI__builtin_ia32_getmantps512_mask: 1929 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 1930 case X86::BI__builtin_ia32_sqrtsd_round_mask: 1931 case X86::BI__builtin_ia32_sqrtss_round_mask: 1932 case X86::BI__builtin_ia32_vfmaddpd512_mask: 1933 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 1934 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 1935 case X86::BI__builtin_ia32_vfmaddps512_mask: 1936 case X86::BI__builtin_ia32_vfmaddps512_mask3: 1937 case X86::BI__builtin_ia32_vfmaddps512_maskz: 1938 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 1939 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 1940 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 1941 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 1942 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 1943 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 1944 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 1945 case X86::BI__builtin_ia32_vfmsubps512_mask3: 1946 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 1947 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 1948 case X86::BI__builtin_ia32_vfnmaddpd512_mask: 1949 case X86::BI__builtin_ia32_vfnmaddps512_mask: 1950 case X86::BI__builtin_ia32_vfnmsubpd512_mask: 1951 case X86::BI__builtin_ia32_vfnmsubpd512_mask3: 1952 case X86::BI__builtin_ia32_vfnmsubps512_mask: 1953 case X86::BI__builtin_ia32_vfnmsubps512_mask3: 1954 case X86::BI__builtin_ia32_vfmaddsd3_mask: 1955 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 1956 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 1957 case X86::BI__builtin_ia32_vfmaddss3_mask: 1958 case X86::BI__builtin_ia32_vfmaddss3_maskz: 1959 case X86::BI__builtin_ia32_vfmaddss3_mask3: 1960 ArgNum = 4; 1961 HasRC = true; 1962 break; 1963 case X86::BI__builtin_ia32_getmantsd_round_mask: 1964 case X86::BI__builtin_ia32_getmantss_round_mask: 1965 ArgNum = 5; 1966 HasRC = true; 1967 break; 1968 } 1969 1970 llvm::APSInt Result; 1971 1972 // We can't check the value of a dependent argument. 1973 Expr *Arg = TheCall->getArg(ArgNum); 1974 if (Arg->isTypeDependent() || Arg->isValueDependent()) 1975 return false; 1976 1977 // Check constant-ness first. 1978 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 1979 return true; 1980 1981 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 1982 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 1983 // combined with ROUND_NO_EXC. 1984 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 1985 Result == 8/*ROUND_NO_EXC*/ || 1986 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 1987 return false; 1988 1989 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 1990 << Arg->getSourceRange(); 1991 } 1992 1993 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1994 if (BuiltinID == X86::BI__builtin_cpu_supports) 1995 return SemaBuiltinCpuSupports(*this, TheCall); 1996 1997 if (BuiltinID == X86::BI__builtin_ms_va_start) 1998 return SemaBuiltinMSVAStart(TheCall); 1999 2000 // If the intrinsic has rounding or SAE make sure its valid. 2001 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 2002 return true; 2003 2004 // For intrinsics which take an immediate value as part of the instruction, 2005 // range check them here. 2006 int i = 0, l = 0, u = 0; 2007 switch (BuiltinID) { 2008 default: 2009 return false; 2010 case X86::BI_mm_prefetch: 2011 i = 1; l = 0; u = 3; 2012 break; 2013 case X86::BI__builtin_ia32_sha1rnds4: 2014 case X86::BI__builtin_ia32_shuf_f32x4_256_mask: 2015 case X86::BI__builtin_ia32_shuf_f64x2_256_mask: 2016 case X86::BI__builtin_ia32_shuf_i32x4_256_mask: 2017 case X86::BI__builtin_ia32_shuf_i64x2_256_mask: 2018 i = 2; l = 0; u = 3; 2019 break; 2020 case X86::BI__builtin_ia32_vpermil2pd: 2021 case X86::BI__builtin_ia32_vpermil2pd256: 2022 case X86::BI__builtin_ia32_vpermil2ps: 2023 case X86::BI__builtin_ia32_vpermil2ps256: 2024 i = 3; l = 0; u = 3; 2025 break; 2026 case X86::BI__builtin_ia32_cmpb128_mask: 2027 case X86::BI__builtin_ia32_cmpw128_mask: 2028 case X86::BI__builtin_ia32_cmpd128_mask: 2029 case X86::BI__builtin_ia32_cmpq128_mask: 2030 case X86::BI__builtin_ia32_cmpb256_mask: 2031 case X86::BI__builtin_ia32_cmpw256_mask: 2032 case X86::BI__builtin_ia32_cmpd256_mask: 2033 case X86::BI__builtin_ia32_cmpq256_mask: 2034 case X86::BI__builtin_ia32_cmpb512_mask: 2035 case X86::BI__builtin_ia32_cmpw512_mask: 2036 case X86::BI__builtin_ia32_cmpd512_mask: 2037 case X86::BI__builtin_ia32_cmpq512_mask: 2038 case X86::BI__builtin_ia32_ucmpb128_mask: 2039 case X86::BI__builtin_ia32_ucmpw128_mask: 2040 case X86::BI__builtin_ia32_ucmpd128_mask: 2041 case X86::BI__builtin_ia32_ucmpq128_mask: 2042 case X86::BI__builtin_ia32_ucmpb256_mask: 2043 case X86::BI__builtin_ia32_ucmpw256_mask: 2044 case X86::BI__builtin_ia32_ucmpd256_mask: 2045 case X86::BI__builtin_ia32_ucmpq256_mask: 2046 case X86::BI__builtin_ia32_ucmpb512_mask: 2047 case X86::BI__builtin_ia32_ucmpw512_mask: 2048 case X86::BI__builtin_ia32_ucmpd512_mask: 2049 case X86::BI__builtin_ia32_ucmpq512_mask: 2050 case X86::BI__builtin_ia32_vpcomub: 2051 case X86::BI__builtin_ia32_vpcomuw: 2052 case X86::BI__builtin_ia32_vpcomud: 2053 case X86::BI__builtin_ia32_vpcomuq: 2054 case X86::BI__builtin_ia32_vpcomb: 2055 case X86::BI__builtin_ia32_vpcomw: 2056 case X86::BI__builtin_ia32_vpcomd: 2057 case X86::BI__builtin_ia32_vpcomq: 2058 i = 2; l = 0; u = 7; 2059 break; 2060 case X86::BI__builtin_ia32_roundps: 2061 case X86::BI__builtin_ia32_roundpd: 2062 case X86::BI__builtin_ia32_roundps256: 2063 case X86::BI__builtin_ia32_roundpd256: 2064 i = 1; l = 0; u = 15; 2065 break; 2066 case X86::BI__builtin_ia32_roundss: 2067 case X86::BI__builtin_ia32_roundsd: 2068 case X86::BI__builtin_ia32_rangepd128_mask: 2069 case X86::BI__builtin_ia32_rangepd256_mask: 2070 case X86::BI__builtin_ia32_rangepd512_mask: 2071 case X86::BI__builtin_ia32_rangeps128_mask: 2072 case X86::BI__builtin_ia32_rangeps256_mask: 2073 case X86::BI__builtin_ia32_rangeps512_mask: 2074 case X86::BI__builtin_ia32_getmantsd_round_mask: 2075 case X86::BI__builtin_ia32_getmantss_round_mask: 2076 i = 2; l = 0; u = 15; 2077 break; 2078 case X86::BI__builtin_ia32_cmpps: 2079 case X86::BI__builtin_ia32_cmpss: 2080 case X86::BI__builtin_ia32_cmppd: 2081 case X86::BI__builtin_ia32_cmpsd: 2082 case X86::BI__builtin_ia32_cmpps256: 2083 case X86::BI__builtin_ia32_cmppd256: 2084 case X86::BI__builtin_ia32_cmpps128_mask: 2085 case X86::BI__builtin_ia32_cmppd128_mask: 2086 case X86::BI__builtin_ia32_cmpps256_mask: 2087 case X86::BI__builtin_ia32_cmppd256_mask: 2088 case X86::BI__builtin_ia32_cmpps512_mask: 2089 case X86::BI__builtin_ia32_cmppd512_mask: 2090 case X86::BI__builtin_ia32_cmpsd_mask: 2091 case X86::BI__builtin_ia32_cmpss_mask: 2092 i = 2; l = 0; u = 31; 2093 break; 2094 case X86::BI__builtin_ia32_xabort: 2095 i = 0; l = -128; u = 255; 2096 break; 2097 case X86::BI__builtin_ia32_pshufw: 2098 case X86::BI__builtin_ia32_aeskeygenassist128: 2099 i = 1; l = -128; u = 255; 2100 break; 2101 case X86::BI__builtin_ia32_vcvtps2ph: 2102 case X86::BI__builtin_ia32_vcvtps2ph256: 2103 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2104 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2105 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2106 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2107 case X86::BI__builtin_ia32_rndscaleps_mask: 2108 case X86::BI__builtin_ia32_rndscalepd_mask: 2109 case X86::BI__builtin_ia32_reducepd128_mask: 2110 case X86::BI__builtin_ia32_reducepd256_mask: 2111 case X86::BI__builtin_ia32_reducepd512_mask: 2112 case X86::BI__builtin_ia32_reduceps128_mask: 2113 case X86::BI__builtin_ia32_reduceps256_mask: 2114 case X86::BI__builtin_ia32_reduceps512_mask: 2115 case X86::BI__builtin_ia32_prold512_mask: 2116 case X86::BI__builtin_ia32_prolq512_mask: 2117 case X86::BI__builtin_ia32_prold128_mask: 2118 case X86::BI__builtin_ia32_prold256_mask: 2119 case X86::BI__builtin_ia32_prolq128_mask: 2120 case X86::BI__builtin_ia32_prolq256_mask: 2121 case X86::BI__builtin_ia32_prord128_mask: 2122 case X86::BI__builtin_ia32_prord256_mask: 2123 case X86::BI__builtin_ia32_prorq128_mask: 2124 case X86::BI__builtin_ia32_prorq256_mask: 2125 case X86::BI__builtin_ia32_fpclasspd128_mask: 2126 case X86::BI__builtin_ia32_fpclasspd256_mask: 2127 case X86::BI__builtin_ia32_fpclassps128_mask: 2128 case X86::BI__builtin_ia32_fpclassps256_mask: 2129 case X86::BI__builtin_ia32_fpclassps512_mask: 2130 case X86::BI__builtin_ia32_fpclasspd512_mask: 2131 case X86::BI__builtin_ia32_fpclasssd_mask: 2132 case X86::BI__builtin_ia32_fpclassss_mask: 2133 i = 1; l = 0; u = 255; 2134 break; 2135 case X86::BI__builtin_ia32_palignr: 2136 case X86::BI__builtin_ia32_insertps128: 2137 case X86::BI__builtin_ia32_dpps: 2138 case X86::BI__builtin_ia32_dppd: 2139 case X86::BI__builtin_ia32_dpps256: 2140 case X86::BI__builtin_ia32_mpsadbw128: 2141 case X86::BI__builtin_ia32_mpsadbw256: 2142 case X86::BI__builtin_ia32_pcmpistrm128: 2143 case X86::BI__builtin_ia32_pcmpistri128: 2144 case X86::BI__builtin_ia32_pcmpistria128: 2145 case X86::BI__builtin_ia32_pcmpistric128: 2146 case X86::BI__builtin_ia32_pcmpistrio128: 2147 case X86::BI__builtin_ia32_pcmpistris128: 2148 case X86::BI__builtin_ia32_pcmpistriz128: 2149 case X86::BI__builtin_ia32_pclmulqdq128: 2150 case X86::BI__builtin_ia32_vperm2f128_pd256: 2151 case X86::BI__builtin_ia32_vperm2f128_ps256: 2152 case X86::BI__builtin_ia32_vperm2f128_si256: 2153 case X86::BI__builtin_ia32_permti256: 2154 i = 2; l = -128; u = 255; 2155 break; 2156 case X86::BI__builtin_ia32_palignr128: 2157 case X86::BI__builtin_ia32_palignr256: 2158 case X86::BI__builtin_ia32_palignr512_mask: 2159 case X86::BI__builtin_ia32_vcomisd: 2160 case X86::BI__builtin_ia32_vcomiss: 2161 case X86::BI__builtin_ia32_shuf_f32x4_mask: 2162 case X86::BI__builtin_ia32_shuf_f64x2_mask: 2163 case X86::BI__builtin_ia32_shuf_i32x4_mask: 2164 case X86::BI__builtin_ia32_shuf_i64x2_mask: 2165 case X86::BI__builtin_ia32_dbpsadbw128_mask: 2166 case X86::BI__builtin_ia32_dbpsadbw256_mask: 2167 case X86::BI__builtin_ia32_dbpsadbw512_mask: 2168 i = 2; l = 0; u = 255; 2169 break; 2170 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2171 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2172 case X86::BI__builtin_ia32_fixupimmps512_mask: 2173 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2174 case X86::BI__builtin_ia32_fixupimmsd_mask: 2175 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2176 case X86::BI__builtin_ia32_fixupimmss_mask: 2177 case X86::BI__builtin_ia32_fixupimmss_maskz: 2178 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2179 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2180 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2181 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2182 case X86::BI__builtin_ia32_fixupimmps128_mask: 2183 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2184 case X86::BI__builtin_ia32_fixupimmps256_mask: 2185 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2186 case X86::BI__builtin_ia32_pternlogd512_mask: 2187 case X86::BI__builtin_ia32_pternlogd512_maskz: 2188 case X86::BI__builtin_ia32_pternlogq512_mask: 2189 case X86::BI__builtin_ia32_pternlogq512_maskz: 2190 case X86::BI__builtin_ia32_pternlogd128_mask: 2191 case X86::BI__builtin_ia32_pternlogd128_maskz: 2192 case X86::BI__builtin_ia32_pternlogd256_mask: 2193 case X86::BI__builtin_ia32_pternlogd256_maskz: 2194 case X86::BI__builtin_ia32_pternlogq128_mask: 2195 case X86::BI__builtin_ia32_pternlogq128_maskz: 2196 case X86::BI__builtin_ia32_pternlogq256_mask: 2197 case X86::BI__builtin_ia32_pternlogq256_maskz: 2198 i = 3; l = 0; u = 255; 2199 break; 2200 case X86::BI__builtin_ia32_pcmpestrm128: 2201 case X86::BI__builtin_ia32_pcmpestri128: 2202 case X86::BI__builtin_ia32_pcmpestria128: 2203 case X86::BI__builtin_ia32_pcmpestric128: 2204 case X86::BI__builtin_ia32_pcmpestrio128: 2205 case X86::BI__builtin_ia32_pcmpestris128: 2206 case X86::BI__builtin_ia32_pcmpestriz128: 2207 i = 4; l = -128; u = 255; 2208 break; 2209 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2210 case X86::BI__builtin_ia32_rndscaless_round_mask: 2211 i = 4; l = 0; u = 255; 2212 break; 2213 } 2214 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2215 } 2216 2217 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2218 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2219 /// Returns true when the format fits the function and the FormatStringInfo has 2220 /// been populated. 2221 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2222 FormatStringInfo *FSI) { 2223 FSI->HasVAListArg = Format->getFirstArg() == 0; 2224 FSI->FormatIdx = Format->getFormatIdx() - 1; 2225 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2226 2227 // The way the format attribute works in GCC, the implicit this argument 2228 // of member functions is counted. However, it doesn't appear in our own 2229 // lists, so decrement format_idx in that case. 2230 if (IsCXXMember) { 2231 if(FSI->FormatIdx == 0) 2232 return false; 2233 --FSI->FormatIdx; 2234 if (FSI->FirstDataArg != 0) 2235 --FSI->FirstDataArg; 2236 } 2237 return true; 2238 } 2239 2240 /// Checks if a the given expression evaluates to null. 2241 /// 2242 /// \brief Returns true if the value evaluates to null. 2243 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2244 // If the expression has non-null type, it doesn't evaluate to null. 2245 if (auto nullability 2246 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2247 if (*nullability == NullabilityKind::NonNull) 2248 return false; 2249 } 2250 2251 // As a special case, transparent unions initialized with zero are 2252 // considered null for the purposes of the nonnull attribute. 2253 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2254 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2255 if (const CompoundLiteralExpr *CLE = 2256 dyn_cast<CompoundLiteralExpr>(Expr)) 2257 if (const InitListExpr *ILE = 2258 dyn_cast<InitListExpr>(CLE->getInitializer())) 2259 Expr = ILE->getInit(0); 2260 } 2261 2262 bool Result; 2263 return (!Expr->isValueDependent() && 2264 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2265 !Result); 2266 } 2267 2268 static void CheckNonNullArgument(Sema &S, 2269 const Expr *ArgExpr, 2270 SourceLocation CallSiteLoc) { 2271 if (CheckNonNullExpr(S, ArgExpr)) 2272 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2273 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2274 } 2275 2276 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2277 FormatStringInfo FSI; 2278 if ((GetFormatStringType(Format) == FST_NSString) && 2279 getFormatStringInfo(Format, false, &FSI)) { 2280 Idx = FSI.FormatIdx; 2281 return true; 2282 } 2283 return false; 2284 } 2285 /// \brief Diagnose use of %s directive in an NSString which is being passed 2286 /// as formatting string to formatting method. 2287 static void 2288 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 2289 const NamedDecl *FDecl, 2290 Expr **Args, 2291 unsigned NumArgs) { 2292 unsigned Idx = 0; 2293 bool Format = false; 2294 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 2295 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 2296 Idx = 2; 2297 Format = true; 2298 } 2299 else 2300 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2301 if (S.GetFormatNSStringIdx(I, Idx)) { 2302 Format = true; 2303 break; 2304 } 2305 } 2306 if (!Format || NumArgs <= Idx) 2307 return; 2308 const Expr *FormatExpr = Args[Idx]; 2309 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2310 FormatExpr = CSCE->getSubExpr(); 2311 const StringLiteral *FormatString; 2312 if (const ObjCStringLiteral *OSL = 2313 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2314 FormatString = OSL->getString(); 2315 else 2316 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2317 if (!FormatString) 2318 return; 2319 if (S.FormatStringHasSArg(FormatString)) { 2320 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2321 << "%s" << 1 << 1; 2322 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2323 << FDecl->getDeclName(); 2324 } 2325 } 2326 2327 /// Determine whether the given type has a non-null nullability annotation. 2328 static bool isNonNullType(ASTContext &ctx, QualType type) { 2329 if (auto nullability = type->getNullability(ctx)) 2330 return *nullability == NullabilityKind::NonNull; 2331 2332 return false; 2333 } 2334 2335 static void CheckNonNullArguments(Sema &S, 2336 const NamedDecl *FDecl, 2337 const FunctionProtoType *Proto, 2338 ArrayRef<const Expr *> Args, 2339 SourceLocation CallSiteLoc) { 2340 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2341 2342 // Check the attributes attached to the method/function itself. 2343 llvm::SmallBitVector NonNullArgs; 2344 if (FDecl) { 2345 // Handle the nonnull attribute on the function/method declaration itself. 2346 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2347 if (!NonNull->args_size()) { 2348 // Easy case: all pointer arguments are nonnull. 2349 for (const auto *Arg : Args) 2350 if (S.isValidPointerAttrType(Arg->getType())) 2351 CheckNonNullArgument(S, Arg, CallSiteLoc); 2352 return; 2353 } 2354 2355 for (unsigned Val : NonNull->args()) { 2356 if (Val >= Args.size()) 2357 continue; 2358 if (NonNullArgs.empty()) 2359 NonNullArgs.resize(Args.size()); 2360 NonNullArgs.set(Val); 2361 } 2362 } 2363 } 2364 2365 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2366 // Handle the nonnull attribute on the parameters of the 2367 // function/method. 2368 ArrayRef<ParmVarDecl*> parms; 2369 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2370 parms = FD->parameters(); 2371 else 2372 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2373 2374 unsigned ParamIndex = 0; 2375 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2376 I != E; ++I, ++ParamIndex) { 2377 const ParmVarDecl *PVD = *I; 2378 if (PVD->hasAttr<NonNullAttr>() || 2379 isNonNullType(S.Context, PVD->getType())) { 2380 if (NonNullArgs.empty()) 2381 NonNullArgs.resize(Args.size()); 2382 2383 NonNullArgs.set(ParamIndex); 2384 } 2385 } 2386 } else { 2387 // If we have a non-function, non-method declaration but no 2388 // function prototype, try to dig out the function prototype. 2389 if (!Proto) { 2390 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2391 QualType type = VD->getType().getNonReferenceType(); 2392 if (auto pointerType = type->getAs<PointerType>()) 2393 type = pointerType->getPointeeType(); 2394 else if (auto blockType = type->getAs<BlockPointerType>()) 2395 type = blockType->getPointeeType(); 2396 // FIXME: data member pointers? 2397 2398 // Dig out the function prototype, if there is one. 2399 Proto = type->getAs<FunctionProtoType>(); 2400 } 2401 } 2402 2403 // Fill in non-null argument information from the nullability 2404 // information on the parameter types (if we have them). 2405 if (Proto) { 2406 unsigned Index = 0; 2407 for (auto paramType : Proto->getParamTypes()) { 2408 if (isNonNullType(S.Context, paramType)) { 2409 if (NonNullArgs.empty()) 2410 NonNullArgs.resize(Args.size()); 2411 2412 NonNullArgs.set(Index); 2413 } 2414 2415 ++Index; 2416 } 2417 } 2418 } 2419 2420 // Check for non-null arguments. 2421 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2422 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2423 if (NonNullArgs[ArgIndex]) 2424 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2425 } 2426 } 2427 2428 /// Handles the checks for format strings, non-POD arguments to vararg 2429 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 2430 /// attributes. 2431 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2432 const Expr *ThisArg, ArrayRef<const Expr *> Args, 2433 bool IsMemberFunction, SourceLocation Loc, 2434 SourceRange Range, VariadicCallType CallType) { 2435 // FIXME: We should check as much as we can in the template definition. 2436 if (CurContext->isDependentContext()) 2437 return; 2438 2439 // Printf and scanf checking. 2440 llvm::SmallBitVector CheckedVarArgs; 2441 if (FDecl) { 2442 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2443 // Only create vector if there are format attributes. 2444 CheckedVarArgs.resize(Args.size()); 2445 2446 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2447 CheckedVarArgs); 2448 } 2449 } 2450 2451 // Refuse POD arguments that weren't caught by the format string 2452 // checks above. 2453 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 2454 if (CallType != VariadicDoesNotApply && 2455 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 2456 unsigned NumParams = Proto ? Proto->getNumParams() 2457 : FDecl && isa<FunctionDecl>(FDecl) 2458 ? cast<FunctionDecl>(FDecl)->getNumParams() 2459 : FDecl && isa<ObjCMethodDecl>(FDecl) 2460 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2461 : 0; 2462 2463 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2464 // Args[ArgIdx] can be null in malformed code. 2465 if (const Expr *Arg = Args[ArgIdx]) { 2466 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 2467 checkVariadicArgument(Arg, CallType); 2468 } 2469 } 2470 } 2471 2472 if (FDecl || Proto) { 2473 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 2474 2475 // Type safety checking. 2476 if (FDecl) { 2477 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 2478 CheckArgumentWithTypeTag(I, Args.data()); 2479 } 2480 } 2481 2482 if (FD) 2483 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 2484 } 2485 2486 /// CheckConstructorCall - Check a constructor call for correctness and safety 2487 /// properties not enforced by the C type system. 2488 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 2489 ArrayRef<const Expr *> Args, 2490 const FunctionProtoType *Proto, 2491 SourceLocation Loc) { 2492 VariadicCallType CallType = 2493 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 2494 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 2495 Loc, SourceRange(), CallType); 2496 } 2497 2498 /// CheckFunctionCall - Check a direct function call for various correctness 2499 /// and safety properties not strictly enforced by the C type system. 2500 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2501 const FunctionProtoType *Proto) { 2502 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 2503 isa<CXXMethodDecl>(FDecl); 2504 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 2505 IsMemberOperatorCall; 2506 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 2507 TheCall->getCallee()); 2508 Expr** Args = TheCall->getArgs(); 2509 unsigned NumArgs = TheCall->getNumArgs(); 2510 2511 Expr *ImplicitThis = nullptr; 2512 if (IsMemberOperatorCall) { 2513 // If this is a call to a member operator, hide the first argument 2514 // from checkCall. 2515 // FIXME: Our choice of AST representation here is less than ideal. 2516 ImplicitThis = Args[0]; 2517 ++Args; 2518 --NumArgs; 2519 } else if (IsMemberFunction) 2520 ImplicitThis = 2521 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 2522 2523 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 2524 IsMemberFunction, TheCall->getRParenLoc(), 2525 TheCall->getCallee()->getSourceRange(), CallType); 2526 2527 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 2528 // None of the checks below are needed for functions that don't have 2529 // simple names (e.g., C++ conversion functions). 2530 if (!FnInfo) 2531 return false; 2532 2533 CheckAbsoluteValueFunction(TheCall, FDecl); 2534 CheckMaxUnsignedZero(TheCall, FDecl); 2535 2536 if (getLangOpts().ObjC1) 2537 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 2538 2539 unsigned CMId = FDecl->getMemoryFunctionKind(); 2540 if (CMId == 0) 2541 return false; 2542 2543 // Handle memory setting and copying functions. 2544 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 2545 CheckStrlcpycatArguments(TheCall, FnInfo); 2546 else if (CMId == Builtin::BIstrncat) 2547 CheckStrncatArguments(TheCall, FnInfo); 2548 else 2549 CheckMemaccessArguments(TheCall, CMId, FnInfo); 2550 2551 return false; 2552 } 2553 2554 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 2555 ArrayRef<const Expr *> Args) { 2556 VariadicCallType CallType = 2557 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 2558 2559 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 2560 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 2561 CallType); 2562 2563 return false; 2564 } 2565 2566 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2567 const FunctionProtoType *Proto) { 2568 QualType Ty; 2569 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 2570 Ty = V->getType().getNonReferenceType(); 2571 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 2572 Ty = F->getType().getNonReferenceType(); 2573 else 2574 return false; 2575 2576 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 2577 !Ty->isFunctionProtoType()) 2578 return false; 2579 2580 VariadicCallType CallType; 2581 if (!Proto || !Proto->isVariadic()) { 2582 CallType = VariadicDoesNotApply; 2583 } else if (Ty->isBlockPointerType()) { 2584 CallType = VariadicBlock; 2585 } else { // Ty->isFunctionPointerType() 2586 CallType = VariadicFunction; 2587 } 2588 2589 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 2590 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2591 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2592 TheCall->getCallee()->getSourceRange(), CallType); 2593 2594 return false; 2595 } 2596 2597 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2598 /// such as function pointers returned from functions. 2599 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 2600 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 2601 TheCall->getCallee()); 2602 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 2603 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2604 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2605 TheCall->getCallee()->getSourceRange(), CallType); 2606 2607 return false; 2608 } 2609 2610 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 2611 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 2612 return false; 2613 2614 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 2615 switch (Op) { 2616 case AtomicExpr::AO__c11_atomic_init: 2617 llvm_unreachable("There is no ordering argument for an init"); 2618 2619 case AtomicExpr::AO__c11_atomic_load: 2620 case AtomicExpr::AO__atomic_load_n: 2621 case AtomicExpr::AO__atomic_load: 2622 return OrderingCABI != llvm::AtomicOrderingCABI::release && 2623 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2624 2625 case AtomicExpr::AO__c11_atomic_store: 2626 case AtomicExpr::AO__atomic_store: 2627 case AtomicExpr::AO__atomic_store_n: 2628 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 2629 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 2630 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2631 2632 default: 2633 return true; 2634 } 2635 } 2636 2637 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 2638 AtomicExpr::AtomicOp Op) { 2639 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 2640 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2641 2642 // All these operations take one of the following forms: 2643 enum { 2644 // C __c11_atomic_init(A *, C) 2645 Init, 2646 // C __c11_atomic_load(A *, int) 2647 Load, 2648 // void __atomic_load(A *, CP, int) 2649 LoadCopy, 2650 // void __atomic_store(A *, CP, int) 2651 Copy, 2652 // C __c11_atomic_add(A *, M, int) 2653 Arithmetic, 2654 // C __atomic_exchange_n(A *, CP, int) 2655 Xchg, 2656 // void __atomic_exchange(A *, C *, CP, int) 2657 GNUXchg, 2658 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 2659 C11CmpXchg, 2660 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 2661 GNUCmpXchg 2662 } Form = Init; 2663 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 2664 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 2665 // where: 2666 // C is an appropriate type, 2667 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 2668 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 2669 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 2670 // the int parameters are for orderings. 2671 2672 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 2673 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 2674 AtomicExpr::AO__atomic_load, 2675 "need to update code for modified C11 atomics"); 2676 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init && 2677 Op <= AtomicExpr::AO__c11_atomic_fetch_xor; 2678 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 2679 Op == AtomicExpr::AO__atomic_store_n || 2680 Op == AtomicExpr::AO__atomic_exchange_n || 2681 Op == AtomicExpr::AO__atomic_compare_exchange_n; 2682 bool IsAddSub = false; 2683 2684 switch (Op) { 2685 case AtomicExpr::AO__c11_atomic_init: 2686 Form = Init; 2687 break; 2688 2689 case AtomicExpr::AO__c11_atomic_load: 2690 case AtomicExpr::AO__atomic_load_n: 2691 Form = Load; 2692 break; 2693 2694 case AtomicExpr::AO__atomic_load: 2695 Form = LoadCopy; 2696 break; 2697 2698 case AtomicExpr::AO__c11_atomic_store: 2699 case AtomicExpr::AO__atomic_store: 2700 case AtomicExpr::AO__atomic_store_n: 2701 Form = Copy; 2702 break; 2703 2704 case AtomicExpr::AO__c11_atomic_fetch_add: 2705 case AtomicExpr::AO__c11_atomic_fetch_sub: 2706 case AtomicExpr::AO__atomic_fetch_add: 2707 case AtomicExpr::AO__atomic_fetch_sub: 2708 case AtomicExpr::AO__atomic_add_fetch: 2709 case AtomicExpr::AO__atomic_sub_fetch: 2710 IsAddSub = true; 2711 // Fall through. 2712 case AtomicExpr::AO__c11_atomic_fetch_and: 2713 case AtomicExpr::AO__c11_atomic_fetch_or: 2714 case AtomicExpr::AO__c11_atomic_fetch_xor: 2715 case AtomicExpr::AO__atomic_fetch_and: 2716 case AtomicExpr::AO__atomic_fetch_or: 2717 case AtomicExpr::AO__atomic_fetch_xor: 2718 case AtomicExpr::AO__atomic_fetch_nand: 2719 case AtomicExpr::AO__atomic_and_fetch: 2720 case AtomicExpr::AO__atomic_or_fetch: 2721 case AtomicExpr::AO__atomic_xor_fetch: 2722 case AtomicExpr::AO__atomic_nand_fetch: 2723 Form = Arithmetic; 2724 break; 2725 2726 case AtomicExpr::AO__c11_atomic_exchange: 2727 case AtomicExpr::AO__atomic_exchange_n: 2728 Form = Xchg; 2729 break; 2730 2731 case AtomicExpr::AO__atomic_exchange: 2732 Form = GNUXchg; 2733 break; 2734 2735 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 2736 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 2737 Form = C11CmpXchg; 2738 break; 2739 2740 case AtomicExpr::AO__atomic_compare_exchange: 2741 case AtomicExpr::AO__atomic_compare_exchange_n: 2742 Form = GNUCmpXchg; 2743 break; 2744 } 2745 2746 // Check we have the right number of arguments. 2747 if (TheCall->getNumArgs() < NumArgs[Form]) { 2748 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 2749 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2750 << TheCall->getCallee()->getSourceRange(); 2751 return ExprError(); 2752 } else if (TheCall->getNumArgs() > NumArgs[Form]) { 2753 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(), 2754 diag::err_typecheck_call_too_many_args) 2755 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2756 << TheCall->getCallee()->getSourceRange(); 2757 return ExprError(); 2758 } 2759 2760 // Inspect the first argument of the atomic operation. 2761 Expr *Ptr = TheCall->getArg(0); 2762 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 2763 if (ConvertedPtr.isInvalid()) 2764 return ExprError(); 2765 2766 Ptr = ConvertedPtr.get(); 2767 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 2768 if (!pointerType) { 2769 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 2770 << Ptr->getType() << Ptr->getSourceRange(); 2771 return ExprError(); 2772 } 2773 2774 // For a __c11 builtin, this should be a pointer to an _Atomic type. 2775 QualType AtomTy = pointerType->getPointeeType(); // 'A' 2776 QualType ValType = AtomTy; // 'C' 2777 if (IsC11) { 2778 if (!AtomTy->isAtomicType()) { 2779 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 2780 << Ptr->getType() << Ptr->getSourceRange(); 2781 return ExprError(); 2782 } 2783 if (AtomTy.isConstQualified()) { 2784 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 2785 << Ptr->getType() << Ptr->getSourceRange(); 2786 return ExprError(); 2787 } 2788 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 2789 } else if (Form != Load && Form != LoadCopy) { 2790 if (ValType.isConstQualified()) { 2791 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 2792 << Ptr->getType() << Ptr->getSourceRange(); 2793 return ExprError(); 2794 } 2795 } 2796 2797 // For an arithmetic operation, the implied arithmetic must be well-formed. 2798 if (Form == Arithmetic) { 2799 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 2800 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 2801 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2802 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2803 return ExprError(); 2804 } 2805 if (!IsAddSub && !ValType->isIntegerType()) { 2806 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 2807 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2808 return ExprError(); 2809 } 2810 if (IsC11 && ValType->isPointerType() && 2811 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 2812 diag::err_incomplete_type)) { 2813 return ExprError(); 2814 } 2815 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 2816 // For __atomic_*_n operations, the value type must be a scalar integral or 2817 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 2818 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2819 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2820 return ExprError(); 2821 } 2822 2823 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 2824 !AtomTy->isScalarType()) { 2825 // For GNU atomics, require a trivially-copyable type. This is not part of 2826 // the GNU atomics specification, but we enforce it for sanity. 2827 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 2828 << Ptr->getType() << Ptr->getSourceRange(); 2829 return ExprError(); 2830 } 2831 2832 switch (ValType.getObjCLifetime()) { 2833 case Qualifiers::OCL_None: 2834 case Qualifiers::OCL_ExplicitNone: 2835 // okay 2836 break; 2837 2838 case Qualifiers::OCL_Weak: 2839 case Qualifiers::OCL_Strong: 2840 case Qualifiers::OCL_Autoreleasing: 2841 // FIXME: Can this happen? By this point, ValType should be known 2842 // to be trivially copyable. 2843 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 2844 << ValType << Ptr->getSourceRange(); 2845 return ExprError(); 2846 } 2847 2848 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 2849 // volatile-ness of the pointee-type inject itself into the result or the 2850 // other operands. Similarly atomic_load can take a pointer to a const 'A'. 2851 ValType.removeLocalVolatile(); 2852 ValType.removeLocalConst(); 2853 QualType ResultType = ValType; 2854 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init) 2855 ResultType = Context.VoidTy; 2856 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 2857 ResultType = Context.BoolTy; 2858 2859 // The type of a parameter passed 'by value'. In the GNU atomics, such 2860 // arguments are actually passed as pointers. 2861 QualType ByValType = ValType; // 'CP' 2862 if (!IsC11 && !IsN) 2863 ByValType = Ptr->getType(); 2864 2865 // The first argument --- the pointer --- has a fixed type; we 2866 // deduce the types of the rest of the arguments accordingly. Walk 2867 // the remaining arguments, converting them to the deduced value type. 2868 for (unsigned i = 1; i != NumArgs[Form]; ++i) { 2869 QualType Ty; 2870 if (i < NumVals[Form] + 1) { 2871 switch (i) { 2872 case 1: 2873 // The second argument is the non-atomic operand. For arithmetic, this 2874 // is always passed by value, and for a compare_exchange it is always 2875 // passed by address. For the rest, GNU uses by-address and C11 uses 2876 // by-value. 2877 assert(Form != Load); 2878 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 2879 Ty = ValType; 2880 else if (Form == Copy || Form == Xchg) 2881 Ty = ByValType; 2882 else if (Form == Arithmetic) 2883 Ty = Context.getPointerDiffType(); 2884 else { 2885 Expr *ValArg = TheCall->getArg(i); 2886 // Treat this argument as _Nonnull as we want to show a warning if 2887 // NULL is passed into it. 2888 CheckNonNullArgument(*this, ValArg, DRE->getLocStart()); 2889 unsigned AS = 0; 2890 // Keep address space of non-atomic pointer type. 2891 if (const PointerType *PtrTy = 2892 ValArg->getType()->getAs<PointerType>()) { 2893 AS = PtrTy->getPointeeType().getAddressSpace(); 2894 } 2895 Ty = Context.getPointerType( 2896 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 2897 } 2898 break; 2899 case 2: 2900 // The third argument to compare_exchange / GNU exchange is a 2901 // (pointer to a) desired value. 2902 Ty = ByValType; 2903 break; 2904 case 3: 2905 // The fourth argument to GNU compare_exchange is a 'weak' flag. 2906 Ty = Context.BoolTy; 2907 break; 2908 } 2909 } else { 2910 // The order(s) are always converted to int. 2911 Ty = Context.IntTy; 2912 } 2913 2914 InitializedEntity Entity = 2915 InitializedEntity::InitializeParameter(Context, Ty, false); 2916 ExprResult Arg = TheCall->getArg(i); 2917 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 2918 if (Arg.isInvalid()) 2919 return true; 2920 TheCall->setArg(i, Arg.get()); 2921 } 2922 2923 // Permute the arguments into a 'consistent' order. 2924 SmallVector<Expr*, 5> SubExprs; 2925 SubExprs.push_back(Ptr); 2926 switch (Form) { 2927 case Init: 2928 // Note, AtomicExpr::getVal1() has a special case for this atomic. 2929 SubExprs.push_back(TheCall->getArg(1)); // Val1 2930 break; 2931 case Load: 2932 SubExprs.push_back(TheCall->getArg(1)); // Order 2933 break; 2934 case LoadCopy: 2935 case Copy: 2936 case Arithmetic: 2937 case Xchg: 2938 SubExprs.push_back(TheCall->getArg(2)); // Order 2939 SubExprs.push_back(TheCall->getArg(1)); // Val1 2940 break; 2941 case GNUXchg: 2942 // Note, AtomicExpr::getVal2() has a special case for this atomic. 2943 SubExprs.push_back(TheCall->getArg(3)); // Order 2944 SubExprs.push_back(TheCall->getArg(1)); // Val1 2945 SubExprs.push_back(TheCall->getArg(2)); // Val2 2946 break; 2947 case C11CmpXchg: 2948 SubExprs.push_back(TheCall->getArg(3)); // Order 2949 SubExprs.push_back(TheCall->getArg(1)); // Val1 2950 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 2951 SubExprs.push_back(TheCall->getArg(2)); // Val2 2952 break; 2953 case GNUCmpXchg: 2954 SubExprs.push_back(TheCall->getArg(4)); // Order 2955 SubExprs.push_back(TheCall->getArg(1)); // Val1 2956 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 2957 SubExprs.push_back(TheCall->getArg(2)); // Val2 2958 SubExprs.push_back(TheCall->getArg(3)); // Weak 2959 break; 2960 } 2961 2962 if (SubExprs.size() >= 2 && Form != Init) { 2963 llvm::APSInt Result(32); 2964 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 2965 !isValidOrderingForOp(Result.getSExtValue(), Op)) 2966 Diag(SubExprs[1]->getLocStart(), 2967 diag::warn_atomic_op_has_invalid_memory_order) 2968 << SubExprs[1]->getSourceRange(); 2969 } 2970 2971 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 2972 SubExprs, ResultType, Op, 2973 TheCall->getRParenLoc()); 2974 2975 if ((Op == AtomicExpr::AO__c11_atomic_load || 2976 (Op == AtomicExpr::AO__c11_atomic_store)) && 2977 Context.AtomicUsesUnsupportedLibcall(AE)) 2978 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) << 2979 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1); 2980 2981 return AE; 2982 } 2983 2984 /// checkBuiltinArgument - Given a call to a builtin function, perform 2985 /// normal type-checking on the given argument, updating the call in 2986 /// place. This is useful when a builtin function requires custom 2987 /// type-checking for some of its arguments but not necessarily all of 2988 /// them. 2989 /// 2990 /// Returns true on error. 2991 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 2992 FunctionDecl *Fn = E->getDirectCallee(); 2993 assert(Fn && "builtin call without direct callee!"); 2994 2995 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 2996 InitializedEntity Entity = 2997 InitializedEntity::InitializeParameter(S.Context, Param); 2998 2999 ExprResult Arg = E->getArg(0); 3000 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 3001 if (Arg.isInvalid()) 3002 return true; 3003 3004 E->setArg(ArgIndex, Arg.get()); 3005 return false; 3006 } 3007 3008 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 3009 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 3010 /// type of its first argument. The main ActOnCallExpr routines have already 3011 /// promoted the types of arguments because all of these calls are prototyped as 3012 /// void(...). 3013 /// 3014 /// This function goes through and does final semantic checking for these 3015 /// builtins, 3016 ExprResult 3017 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3018 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3019 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3020 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3021 3022 // Ensure that we have at least one argument to do type inference from. 3023 if (TheCall->getNumArgs() < 1) { 3024 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3025 << 0 << 1 << TheCall->getNumArgs() 3026 << TheCall->getCallee()->getSourceRange(); 3027 return ExprError(); 3028 } 3029 3030 // Inspect the first argument of the atomic builtin. This should always be 3031 // a pointer type, whose element is an integral scalar or pointer type. 3032 // Because it is a pointer type, we don't have to worry about any implicit 3033 // casts here. 3034 // FIXME: We don't allow floating point scalars as input. 3035 Expr *FirstArg = TheCall->getArg(0); 3036 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3037 if (FirstArgResult.isInvalid()) 3038 return ExprError(); 3039 FirstArg = FirstArgResult.get(); 3040 TheCall->setArg(0, FirstArg); 3041 3042 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3043 if (!pointerType) { 3044 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3045 << FirstArg->getType() << FirstArg->getSourceRange(); 3046 return ExprError(); 3047 } 3048 3049 QualType ValType = pointerType->getPointeeType(); 3050 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3051 !ValType->isBlockPointerType()) { 3052 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3053 << FirstArg->getType() << FirstArg->getSourceRange(); 3054 return ExprError(); 3055 } 3056 3057 switch (ValType.getObjCLifetime()) { 3058 case Qualifiers::OCL_None: 3059 case Qualifiers::OCL_ExplicitNone: 3060 // okay 3061 break; 3062 3063 case Qualifiers::OCL_Weak: 3064 case Qualifiers::OCL_Strong: 3065 case Qualifiers::OCL_Autoreleasing: 3066 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3067 << ValType << FirstArg->getSourceRange(); 3068 return ExprError(); 3069 } 3070 3071 // Strip any qualifiers off ValType. 3072 ValType = ValType.getUnqualifiedType(); 3073 3074 // The majority of builtins return a value, but a few have special return 3075 // types, so allow them to override appropriately below. 3076 QualType ResultType = ValType; 3077 3078 // We need to figure out which concrete builtin this maps onto. For example, 3079 // __sync_fetch_and_add with a 2 byte object turns into 3080 // __sync_fetch_and_add_2. 3081 #define BUILTIN_ROW(x) \ 3082 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3083 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3084 3085 static const unsigned BuiltinIndices[][5] = { 3086 BUILTIN_ROW(__sync_fetch_and_add), 3087 BUILTIN_ROW(__sync_fetch_and_sub), 3088 BUILTIN_ROW(__sync_fetch_and_or), 3089 BUILTIN_ROW(__sync_fetch_and_and), 3090 BUILTIN_ROW(__sync_fetch_and_xor), 3091 BUILTIN_ROW(__sync_fetch_and_nand), 3092 3093 BUILTIN_ROW(__sync_add_and_fetch), 3094 BUILTIN_ROW(__sync_sub_and_fetch), 3095 BUILTIN_ROW(__sync_and_and_fetch), 3096 BUILTIN_ROW(__sync_or_and_fetch), 3097 BUILTIN_ROW(__sync_xor_and_fetch), 3098 BUILTIN_ROW(__sync_nand_and_fetch), 3099 3100 BUILTIN_ROW(__sync_val_compare_and_swap), 3101 BUILTIN_ROW(__sync_bool_compare_and_swap), 3102 BUILTIN_ROW(__sync_lock_test_and_set), 3103 BUILTIN_ROW(__sync_lock_release), 3104 BUILTIN_ROW(__sync_swap) 3105 }; 3106 #undef BUILTIN_ROW 3107 3108 // Determine the index of the size. 3109 unsigned SizeIndex; 3110 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3111 case 1: SizeIndex = 0; break; 3112 case 2: SizeIndex = 1; break; 3113 case 4: SizeIndex = 2; break; 3114 case 8: SizeIndex = 3; break; 3115 case 16: SizeIndex = 4; break; 3116 default: 3117 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3118 << FirstArg->getType() << FirstArg->getSourceRange(); 3119 return ExprError(); 3120 } 3121 3122 // Each of these builtins has one pointer argument, followed by some number of 3123 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3124 // that we ignore. Find out which row of BuiltinIndices to read from as well 3125 // as the number of fixed args. 3126 unsigned BuiltinID = FDecl->getBuiltinID(); 3127 unsigned BuiltinIndex, NumFixed = 1; 3128 bool WarnAboutSemanticsChange = false; 3129 switch (BuiltinID) { 3130 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3131 case Builtin::BI__sync_fetch_and_add: 3132 case Builtin::BI__sync_fetch_and_add_1: 3133 case Builtin::BI__sync_fetch_and_add_2: 3134 case Builtin::BI__sync_fetch_and_add_4: 3135 case Builtin::BI__sync_fetch_and_add_8: 3136 case Builtin::BI__sync_fetch_and_add_16: 3137 BuiltinIndex = 0; 3138 break; 3139 3140 case Builtin::BI__sync_fetch_and_sub: 3141 case Builtin::BI__sync_fetch_and_sub_1: 3142 case Builtin::BI__sync_fetch_and_sub_2: 3143 case Builtin::BI__sync_fetch_and_sub_4: 3144 case Builtin::BI__sync_fetch_and_sub_8: 3145 case Builtin::BI__sync_fetch_and_sub_16: 3146 BuiltinIndex = 1; 3147 break; 3148 3149 case Builtin::BI__sync_fetch_and_or: 3150 case Builtin::BI__sync_fetch_and_or_1: 3151 case Builtin::BI__sync_fetch_and_or_2: 3152 case Builtin::BI__sync_fetch_and_or_4: 3153 case Builtin::BI__sync_fetch_and_or_8: 3154 case Builtin::BI__sync_fetch_and_or_16: 3155 BuiltinIndex = 2; 3156 break; 3157 3158 case Builtin::BI__sync_fetch_and_and: 3159 case Builtin::BI__sync_fetch_and_and_1: 3160 case Builtin::BI__sync_fetch_and_and_2: 3161 case Builtin::BI__sync_fetch_and_and_4: 3162 case Builtin::BI__sync_fetch_and_and_8: 3163 case Builtin::BI__sync_fetch_and_and_16: 3164 BuiltinIndex = 3; 3165 break; 3166 3167 case Builtin::BI__sync_fetch_and_xor: 3168 case Builtin::BI__sync_fetch_and_xor_1: 3169 case Builtin::BI__sync_fetch_and_xor_2: 3170 case Builtin::BI__sync_fetch_and_xor_4: 3171 case Builtin::BI__sync_fetch_and_xor_8: 3172 case Builtin::BI__sync_fetch_and_xor_16: 3173 BuiltinIndex = 4; 3174 break; 3175 3176 case Builtin::BI__sync_fetch_and_nand: 3177 case Builtin::BI__sync_fetch_and_nand_1: 3178 case Builtin::BI__sync_fetch_and_nand_2: 3179 case Builtin::BI__sync_fetch_and_nand_4: 3180 case Builtin::BI__sync_fetch_and_nand_8: 3181 case Builtin::BI__sync_fetch_and_nand_16: 3182 BuiltinIndex = 5; 3183 WarnAboutSemanticsChange = true; 3184 break; 3185 3186 case Builtin::BI__sync_add_and_fetch: 3187 case Builtin::BI__sync_add_and_fetch_1: 3188 case Builtin::BI__sync_add_and_fetch_2: 3189 case Builtin::BI__sync_add_and_fetch_4: 3190 case Builtin::BI__sync_add_and_fetch_8: 3191 case Builtin::BI__sync_add_and_fetch_16: 3192 BuiltinIndex = 6; 3193 break; 3194 3195 case Builtin::BI__sync_sub_and_fetch: 3196 case Builtin::BI__sync_sub_and_fetch_1: 3197 case Builtin::BI__sync_sub_and_fetch_2: 3198 case Builtin::BI__sync_sub_and_fetch_4: 3199 case Builtin::BI__sync_sub_and_fetch_8: 3200 case Builtin::BI__sync_sub_and_fetch_16: 3201 BuiltinIndex = 7; 3202 break; 3203 3204 case Builtin::BI__sync_and_and_fetch: 3205 case Builtin::BI__sync_and_and_fetch_1: 3206 case Builtin::BI__sync_and_and_fetch_2: 3207 case Builtin::BI__sync_and_and_fetch_4: 3208 case Builtin::BI__sync_and_and_fetch_8: 3209 case Builtin::BI__sync_and_and_fetch_16: 3210 BuiltinIndex = 8; 3211 break; 3212 3213 case Builtin::BI__sync_or_and_fetch: 3214 case Builtin::BI__sync_or_and_fetch_1: 3215 case Builtin::BI__sync_or_and_fetch_2: 3216 case Builtin::BI__sync_or_and_fetch_4: 3217 case Builtin::BI__sync_or_and_fetch_8: 3218 case Builtin::BI__sync_or_and_fetch_16: 3219 BuiltinIndex = 9; 3220 break; 3221 3222 case Builtin::BI__sync_xor_and_fetch: 3223 case Builtin::BI__sync_xor_and_fetch_1: 3224 case Builtin::BI__sync_xor_and_fetch_2: 3225 case Builtin::BI__sync_xor_and_fetch_4: 3226 case Builtin::BI__sync_xor_and_fetch_8: 3227 case Builtin::BI__sync_xor_and_fetch_16: 3228 BuiltinIndex = 10; 3229 break; 3230 3231 case Builtin::BI__sync_nand_and_fetch: 3232 case Builtin::BI__sync_nand_and_fetch_1: 3233 case Builtin::BI__sync_nand_and_fetch_2: 3234 case Builtin::BI__sync_nand_and_fetch_4: 3235 case Builtin::BI__sync_nand_and_fetch_8: 3236 case Builtin::BI__sync_nand_and_fetch_16: 3237 BuiltinIndex = 11; 3238 WarnAboutSemanticsChange = true; 3239 break; 3240 3241 case Builtin::BI__sync_val_compare_and_swap: 3242 case Builtin::BI__sync_val_compare_and_swap_1: 3243 case Builtin::BI__sync_val_compare_and_swap_2: 3244 case Builtin::BI__sync_val_compare_and_swap_4: 3245 case Builtin::BI__sync_val_compare_and_swap_8: 3246 case Builtin::BI__sync_val_compare_and_swap_16: 3247 BuiltinIndex = 12; 3248 NumFixed = 2; 3249 break; 3250 3251 case Builtin::BI__sync_bool_compare_and_swap: 3252 case Builtin::BI__sync_bool_compare_and_swap_1: 3253 case Builtin::BI__sync_bool_compare_and_swap_2: 3254 case Builtin::BI__sync_bool_compare_and_swap_4: 3255 case Builtin::BI__sync_bool_compare_and_swap_8: 3256 case Builtin::BI__sync_bool_compare_and_swap_16: 3257 BuiltinIndex = 13; 3258 NumFixed = 2; 3259 ResultType = Context.BoolTy; 3260 break; 3261 3262 case Builtin::BI__sync_lock_test_and_set: 3263 case Builtin::BI__sync_lock_test_and_set_1: 3264 case Builtin::BI__sync_lock_test_and_set_2: 3265 case Builtin::BI__sync_lock_test_and_set_4: 3266 case Builtin::BI__sync_lock_test_and_set_8: 3267 case Builtin::BI__sync_lock_test_and_set_16: 3268 BuiltinIndex = 14; 3269 break; 3270 3271 case Builtin::BI__sync_lock_release: 3272 case Builtin::BI__sync_lock_release_1: 3273 case Builtin::BI__sync_lock_release_2: 3274 case Builtin::BI__sync_lock_release_4: 3275 case Builtin::BI__sync_lock_release_8: 3276 case Builtin::BI__sync_lock_release_16: 3277 BuiltinIndex = 15; 3278 NumFixed = 0; 3279 ResultType = Context.VoidTy; 3280 break; 3281 3282 case Builtin::BI__sync_swap: 3283 case Builtin::BI__sync_swap_1: 3284 case Builtin::BI__sync_swap_2: 3285 case Builtin::BI__sync_swap_4: 3286 case Builtin::BI__sync_swap_8: 3287 case Builtin::BI__sync_swap_16: 3288 BuiltinIndex = 16; 3289 break; 3290 } 3291 3292 // Now that we know how many fixed arguments we expect, first check that we 3293 // have at least that many. 3294 if (TheCall->getNumArgs() < 1+NumFixed) { 3295 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3296 << 0 << 1+NumFixed << TheCall->getNumArgs() 3297 << TheCall->getCallee()->getSourceRange(); 3298 return ExprError(); 3299 } 3300 3301 if (WarnAboutSemanticsChange) { 3302 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 3303 << TheCall->getCallee()->getSourceRange(); 3304 } 3305 3306 // Get the decl for the concrete builtin from this, we can tell what the 3307 // concrete integer type we should convert to is. 3308 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 3309 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 3310 FunctionDecl *NewBuiltinDecl; 3311 if (NewBuiltinID == BuiltinID) 3312 NewBuiltinDecl = FDecl; 3313 else { 3314 // Perform builtin lookup to avoid redeclaring it. 3315 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3316 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3317 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3318 assert(Res.getFoundDecl()); 3319 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3320 if (!NewBuiltinDecl) 3321 return ExprError(); 3322 } 3323 3324 // The first argument --- the pointer --- has a fixed type; we 3325 // deduce the types of the rest of the arguments accordingly. Walk 3326 // the remaining arguments, converting them to the deduced value type. 3327 for (unsigned i = 0; i != NumFixed; ++i) { 3328 ExprResult Arg = TheCall->getArg(i+1); 3329 3330 // GCC does an implicit conversion to the pointer or integer ValType. This 3331 // can fail in some cases (1i -> int**), check for this error case now. 3332 // Initialize the argument. 3333 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3334 ValType, /*consume*/ false); 3335 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3336 if (Arg.isInvalid()) 3337 return ExprError(); 3338 3339 // Okay, we have something that *can* be converted to the right type. Check 3340 // to see if there is a potentially weird extension going on here. This can 3341 // happen when you do an atomic operation on something like an char* and 3342 // pass in 42. The 42 gets converted to char. This is even more strange 3343 // for things like 45.123 -> char, etc. 3344 // FIXME: Do this check. 3345 TheCall->setArg(i+1, Arg.get()); 3346 } 3347 3348 ASTContext& Context = this->getASTContext(); 3349 3350 // Create a new DeclRefExpr to refer to the new decl. 3351 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3352 Context, 3353 DRE->getQualifierLoc(), 3354 SourceLocation(), 3355 NewBuiltinDecl, 3356 /*enclosing*/ false, 3357 DRE->getLocation(), 3358 Context.BuiltinFnTy, 3359 DRE->getValueKind()); 3360 3361 // Set the callee in the CallExpr. 3362 // FIXME: This loses syntactic information. 3363 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3364 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3365 CK_BuiltinFnToFnPtr); 3366 TheCall->setCallee(PromotedCall.get()); 3367 3368 // Change the result type of the call to match the original value type. This 3369 // is arbitrary, but the codegen for these builtins ins design to handle it 3370 // gracefully. 3371 TheCall->setType(ResultType); 3372 3373 return TheCallResult; 3374 } 3375 3376 /// SemaBuiltinNontemporalOverloaded - We have a call to 3377 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 3378 /// overloaded function based on the pointer type of its last argument. 3379 /// 3380 /// This function goes through and does final semantic checking for these 3381 /// builtins. 3382 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 3383 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3384 DeclRefExpr *DRE = 3385 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3386 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3387 unsigned BuiltinID = FDecl->getBuiltinID(); 3388 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 3389 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 3390 "Unexpected nontemporal load/store builtin!"); 3391 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 3392 unsigned numArgs = isStore ? 2 : 1; 3393 3394 // Ensure that we have the proper number of arguments. 3395 if (checkArgCount(*this, TheCall, numArgs)) 3396 return ExprError(); 3397 3398 // Inspect the last argument of the nontemporal builtin. This should always 3399 // be a pointer type, from which we imply the type of the memory access. 3400 // Because it is a pointer type, we don't have to worry about any implicit 3401 // casts here. 3402 Expr *PointerArg = TheCall->getArg(numArgs - 1); 3403 ExprResult PointerArgResult = 3404 DefaultFunctionArrayLvalueConversion(PointerArg); 3405 3406 if (PointerArgResult.isInvalid()) 3407 return ExprError(); 3408 PointerArg = PointerArgResult.get(); 3409 TheCall->setArg(numArgs - 1, PointerArg); 3410 3411 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3412 if (!pointerType) { 3413 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 3414 << PointerArg->getType() << PointerArg->getSourceRange(); 3415 return ExprError(); 3416 } 3417 3418 QualType ValType = pointerType->getPointeeType(); 3419 3420 // Strip any qualifiers off ValType. 3421 ValType = ValType.getUnqualifiedType(); 3422 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3423 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 3424 !ValType->isVectorType()) { 3425 Diag(DRE->getLocStart(), 3426 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 3427 << PointerArg->getType() << PointerArg->getSourceRange(); 3428 return ExprError(); 3429 } 3430 3431 if (!isStore) { 3432 TheCall->setType(ValType); 3433 return TheCallResult; 3434 } 3435 3436 ExprResult ValArg = TheCall->getArg(0); 3437 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3438 Context, ValType, /*consume*/ false); 3439 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3440 if (ValArg.isInvalid()) 3441 return ExprError(); 3442 3443 TheCall->setArg(0, ValArg.get()); 3444 TheCall->setType(Context.VoidTy); 3445 return TheCallResult; 3446 } 3447 3448 /// CheckObjCString - Checks that the argument to the builtin 3449 /// CFString constructor is correct 3450 /// Note: It might also make sense to do the UTF-16 conversion here (would 3451 /// simplify the backend). 3452 bool Sema::CheckObjCString(Expr *Arg) { 3453 Arg = Arg->IgnoreParenCasts(); 3454 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 3455 3456 if (!Literal || !Literal->isAscii()) { 3457 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 3458 << Arg->getSourceRange(); 3459 return true; 3460 } 3461 3462 if (Literal->containsNonAsciiOrNull()) { 3463 StringRef String = Literal->getString(); 3464 unsigned NumBytes = String.size(); 3465 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 3466 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 3467 llvm::UTF16 *ToPtr = &ToBuf[0]; 3468 3469 llvm::ConversionResult Result = 3470 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 3471 ToPtr + NumBytes, llvm::strictConversion); 3472 // Check for conversion failure. 3473 if (Result != llvm::conversionOK) 3474 Diag(Arg->getLocStart(), 3475 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 3476 } 3477 return false; 3478 } 3479 3480 /// CheckObjCString - Checks that the format string argument to the os_log() 3481 /// and os_trace() functions is correct, and converts it to const char *. 3482 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 3483 Arg = Arg->IgnoreParenCasts(); 3484 auto *Literal = dyn_cast<StringLiteral>(Arg); 3485 if (!Literal) { 3486 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 3487 Literal = ObjcLiteral->getString(); 3488 } 3489 } 3490 3491 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 3492 return ExprError( 3493 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 3494 << Arg->getSourceRange()); 3495 } 3496 3497 ExprResult Result(Literal); 3498 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 3499 InitializedEntity Entity = 3500 InitializedEntity::InitializeParameter(Context, ResultTy, false); 3501 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 3502 return Result; 3503 } 3504 3505 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 3506 /// for validity. Emit an error and return true on failure; return false 3507 /// on success. 3508 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) { 3509 Expr *Fn = TheCall->getCallee(); 3510 if (TheCall->getNumArgs() > 2) { 3511 Diag(TheCall->getArg(2)->getLocStart(), 3512 diag::err_typecheck_call_too_many_args) 3513 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3514 << Fn->getSourceRange() 3515 << SourceRange(TheCall->getArg(2)->getLocStart(), 3516 (*(TheCall->arg_end()-1))->getLocEnd()); 3517 return true; 3518 } 3519 3520 if (TheCall->getNumArgs() < 2) { 3521 return Diag(TheCall->getLocEnd(), 3522 diag::err_typecheck_call_too_few_args_at_least) 3523 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 3524 } 3525 3526 // Type-check the first argument normally. 3527 if (checkBuiltinArgument(*this, TheCall, 0)) 3528 return true; 3529 3530 // Determine whether the current function is variadic or not. 3531 BlockScopeInfo *CurBlock = getCurBlock(); 3532 bool isVariadic; 3533 if (CurBlock) 3534 isVariadic = CurBlock->TheDecl->isVariadic(); 3535 else if (FunctionDecl *FD = getCurFunctionDecl()) 3536 isVariadic = FD->isVariadic(); 3537 else 3538 isVariadic = getCurMethodDecl()->isVariadic(); 3539 3540 if (!isVariadic) { 3541 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 3542 return true; 3543 } 3544 3545 // Verify that the second argument to the builtin is the last argument of the 3546 // current function or method. 3547 bool SecondArgIsLastNamedArgument = false; 3548 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 3549 3550 // These are valid if SecondArgIsLastNamedArgument is false after the next 3551 // block. 3552 QualType Type; 3553 SourceLocation ParamLoc; 3554 bool IsCRegister = false; 3555 3556 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 3557 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 3558 // FIXME: This isn't correct for methods (results in bogus warning). 3559 // Get the last formal in the current function. 3560 const ParmVarDecl *LastArg; 3561 if (CurBlock) 3562 LastArg = CurBlock->TheDecl->parameters().back(); 3563 else if (FunctionDecl *FD = getCurFunctionDecl()) 3564 LastArg = FD->parameters().back(); 3565 else 3566 LastArg = getCurMethodDecl()->parameters().back(); 3567 SecondArgIsLastNamedArgument = PV == LastArg; 3568 3569 Type = PV->getType(); 3570 ParamLoc = PV->getLocation(); 3571 IsCRegister = 3572 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 3573 } 3574 } 3575 3576 if (!SecondArgIsLastNamedArgument) 3577 Diag(TheCall->getArg(1)->getLocStart(), 3578 diag::warn_second_arg_of_va_start_not_last_named_param); 3579 else if (IsCRegister || Type->isReferenceType() || 3580 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 3581 // Promotable integers are UB, but enumerations need a bit of 3582 // extra checking to see what their promotable type actually is. 3583 if (!Type->isPromotableIntegerType()) 3584 return false; 3585 if (!Type->isEnumeralType()) 3586 return true; 3587 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 3588 return !(ED && 3589 Context.typesAreCompatible(ED->getPromotionType(), Type)); 3590 }()) { 3591 unsigned Reason = 0; 3592 if (Type->isReferenceType()) Reason = 1; 3593 else if (IsCRegister) Reason = 2; 3594 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 3595 Diag(ParamLoc, diag::note_parameter_type) << Type; 3596 } 3597 3598 TheCall->setType(Context.VoidTy); 3599 return false; 3600 } 3601 3602 /// Check the arguments to '__builtin_va_start' for validity, and that 3603 /// it was called from a function of the native ABI. 3604 /// Emit an error and return true on failure; return false on success. 3605 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 3606 // On x86-64 Unix, don't allow this in Win64 ABI functions. 3607 // On x64 Windows, don't allow this in System V ABI functions. 3608 // (Yes, that means there's no corresponding way to support variadic 3609 // System V ABI functions on Windows.) 3610 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) { 3611 unsigned OS = Context.getTargetInfo().getTriple().getOS(); 3612 clang::CallingConv CC = CC_C; 3613 if (const FunctionDecl *FD = getCurFunctionDecl()) 3614 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3615 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) || 3616 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64)) 3617 return Diag(TheCall->getCallee()->getLocStart(), 3618 diag::err_va_start_used_in_wrong_abi_function) 3619 << (OS != llvm::Triple::Win32); 3620 } 3621 return SemaBuiltinVAStartImpl(TheCall); 3622 } 3623 3624 /// Check the arguments to '__builtin_ms_va_start' for validity, and that 3625 /// it was called from a Win64 ABI function. 3626 /// Emit an error and return true on failure; return false on success. 3627 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) { 3628 // This only makes sense for x86-64. 3629 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3630 Expr *Callee = TheCall->getCallee(); 3631 if (TT.getArch() != llvm::Triple::x86_64) 3632 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt); 3633 // Don't allow this in System V ABI functions. 3634 clang::CallingConv CC = CC_C; 3635 if (const FunctionDecl *FD = getCurFunctionDecl()) 3636 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3637 if (CC == CC_X86_64SysV || 3638 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64)) 3639 return Diag(Callee->getLocStart(), 3640 diag::err_ms_va_start_used_in_sysv_function); 3641 return SemaBuiltinVAStartImpl(TheCall); 3642 } 3643 3644 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) { 3645 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 3646 // const char *named_addr); 3647 3648 Expr *Func = Call->getCallee(); 3649 3650 if (Call->getNumArgs() < 3) 3651 return Diag(Call->getLocEnd(), 3652 diag::err_typecheck_call_too_few_args_at_least) 3653 << 0 /*function call*/ << 3 << Call->getNumArgs(); 3654 3655 // Determine whether the current function is variadic or not. 3656 bool IsVariadic; 3657 if (BlockScopeInfo *CurBlock = getCurBlock()) 3658 IsVariadic = CurBlock->TheDecl->isVariadic(); 3659 else if (FunctionDecl *FD = getCurFunctionDecl()) 3660 IsVariadic = FD->isVariadic(); 3661 else if (ObjCMethodDecl *MD = getCurMethodDecl()) 3662 IsVariadic = MD->isVariadic(); 3663 else 3664 llvm_unreachable("unexpected statement type"); 3665 3666 if (!IsVariadic) { 3667 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 3668 return true; 3669 } 3670 3671 // Type-check the first argument normally. 3672 if (checkBuiltinArgument(*this, Call, 0)) 3673 return true; 3674 3675 const struct { 3676 unsigned ArgNo; 3677 QualType Type; 3678 } ArgumentTypes[] = { 3679 { 1, Context.getPointerType(Context.CharTy.withConst()) }, 3680 { 2, Context.getSizeType() }, 3681 }; 3682 3683 for (const auto &AT : ArgumentTypes) { 3684 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens(); 3685 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType()) 3686 continue; 3687 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible) 3688 << Arg->getType() << AT.Type << 1 /* different class */ 3689 << 0 /* qualifier difference */ << 3 /* parameter mismatch */ 3690 << AT.ArgNo + 1 << Arg->getType() << AT.Type; 3691 } 3692 3693 return false; 3694 } 3695 3696 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 3697 /// friends. This is declared to take (...), so we have to check everything. 3698 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 3699 if (TheCall->getNumArgs() < 2) 3700 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3701 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 3702 if (TheCall->getNumArgs() > 2) 3703 return Diag(TheCall->getArg(2)->getLocStart(), 3704 diag::err_typecheck_call_too_many_args) 3705 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3706 << SourceRange(TheCall->getArg(2)->getLocStart(), 3707 (*(TheCall->arg_end()-1))->getLocEnd()); 3708 3709 ExprResult OrigArg0 = TheCall->getArg(0); 3710 ExprResult OrigArg1 = TheCall->getArg(1); 3711 3712 // Do standard promotions between the two arguments, returning their common 3713 // type. 3714 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 3715 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 3716 return true; 3717 3718 // Make sure any conversions are pushed back into the call; this is 3719 // type safe since unordered compare builtins are declared as "_Bool 3720 // foo(...)". 3721 TheCall->setArg(0, OrigArg0.get()); 3722 TheCall->setArg(1, OrigArg1.get()); 3723 3724 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 3725 return false; 3726 3727 // If the common type isn't a real floating type, then the arguments were 3728 // invalid for this operation. 3729 if (Res.isNull() || !Res->isRealFloatingType()) 3730 return Diag(OrigArg0.get()->getLocStart(), 3731 diag::err_typecheck_call_invalid_ordered_compare) 3732 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 3733 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 3734 3735 return false; 3736 } 3737 3738 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 3739 /// __builtin_isnan and friends. This is declared to take (...), so we have 3740 /// to check everything. We expect the last argument to be a floating point 3741 /// value. 3742 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 3743 if (TheCall->getNumArgs() < NumArgs) 3744 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3745 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 3746 if (TheCall->getNumArgs() > NumArgs) 3747 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 3748 diag::err_typecheck_call_too_many_args) 3749 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 3750 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 3751 (*(TheCall->arg_end()-1))->getLocEnd()); 3752 3753 Expr *OrigArg = TheCall->getArg(NumArgs-1); 3754 3755 if (OrigArg->isTypeDependent()) 3756 return false; 3757 3758 // This operation requires a non-_Complex floating-point number. 3759 if (!OrigArg->getType()->isRealFloatingType()) 3760 return Diag(OrigArg->getLocStart(), 3761 diag::err_typecheck_call_invalid_unary_fp) 3762 << OrigArg->getType() << OrigArg->getSourceRange(); 3763 3764 // If this is an implicit conversion from float -> float or double, remove it. 3765 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 3766 // Only remove standard FloatCasts, leaving other casts inplace 3767 if (Cast->getCastKind() == CK_FloatingCast) { 3768 Expr *CastArg = Cast->getSubExpr(); 3769 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 3770 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 3771 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) && 3772 "promotion from float to either float or double is the only expected cast here"); 3773 Cast->setSubExpr(nullptr); 3774 TheCall->setArg(NumArgs-1, CastArg); 3775 } 3776 } 3777 } 3778 3779 return false; 3780 } 3781 3782 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 3783 // This is declared to take (...), so we have to check everything. 3784 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 3785 if (TheCall->getNumArgs() < 2) 3786 return ExprError(Diag(TheCall->getLocEnd(), 3787 diag::err_typecheck_call_too_few_args_at_least) 3788 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3789 << TheCall->getSourceRange()); 3790 3791 // Determine which of the following types of shufflevector we're checking: 3792 // 1) unary, vector mask: (lhs, mask) 3793 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 3794 QualType resType = TheCall->getArg(0)->getType(); 3795 unsigned numElements = 0; 3796 3797 if (!TheCall->getArg(0)->isTypeDependent() && 3798 !TheCall->getArg(1)->isTypeDependent()) { 3799 QualType LHSType = TheCall->getArg(0)->getType(); 3800 QualType RHSType = TheCall->getArg(1)->getType(); 3801 3802 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 3803 return ExprError(Diag(TheCall->getLocStart(), 3804 diag::err_shufflevector_non_vector) 3805 << SourceRange(TheCall->getArg(0)->getLocStart(), 3806 TheCall->getArg(1)->getLocEnd())); 3807 3808 numElements = LHSType->getAs<VectorType>()->getNumElements(); 3809 unsigned numResElements = TheCall->getNumArgs() - 2; 3810 3811 // Check to see if we have a call with 2 vector arguments, the unary shuffle 3812 // with mask. If so, verify that RHS is an integer vector type with the 3813 // same number of elts as lhs. 3814 if (TheCall->getNumArgs() == 2) { 3815 if (!RHSType->hasIntegerRepresentation() || 3816 RHSType->getAs<VectorType>()->getNumElements() != numElements) 3817 return ExprError(Diag(TheCall->getLocStart(), 3818 diag::err_shufflevector_incompatible_vector) 3819 << SourceRange(TheCall->getArg(1)->getLocStart(), 3820 TheCall->getArg(1)->getLocEnd())); 3821 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 3822 return ExprError(Diag(TheCall->getLocStart(), 3823 diag::err_shufflevector_incompatible_vector) 3824 << SourceRange(TheCall->getArg(0)->getLocStart(), 3825 TheCall->getArg(1)->getLocEnd())); 3826 } else if (numElements != numResElements) { 3827 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 3828 resType = Context.getVectorType(eltType, numResElements, 3829 VectorType::GenericVector); 3830 } 3831 } 3832 3833 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 3834 if (TheCall->getArg(i)->isTypeDependent() || 3835 TheCall->getArg(i)->isValueDependent()) 3836 continue; 3837 3838 llvm::APSInt Result(32); 3839 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 3840 return ExprError(Diag(TheCall->getLocStart(), 3841 diag::err_shufflevector_nonconstant_argument) 3842 << TheCall->getArg(i)->getSourceRange()); 3843 3844 // Allow -1 which will be translated to undef in the IR. 3845 if (Result.isSigned() && Result.isAllOnesValue()) 3846 continue; 3847 3848 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 3849 return ExprError(Diag(TheCall->getLocStart(), 3850 diag::err_shufflevector_argument_too_large) 3851 << TheCall->getArg(i)->getSourceRange()); 3852 } 3853 3854 SmallVector<Expr*, 32> exprs; 3855 3856 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 3857 exprs.push_back(TheCall->getArg(i)); 3858 TheCall->setArg(i, nullptr); 3859 } 3860 3861 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 3862 TheCall->getCallee()->getLocStart(), 3863 TheCall->getRParenLoc()); 3864 } 3865 3866 /// SemaConvertVectorExpr - Handle __builtin_convertvector 3867 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 3868 SourceLocation BuiltinLoc, 3869 SourceLocation RParenLoc) { 3870 ExprValueKind VK = VK_RValue; 3871 ExprObjectKind OK = OK_Ordinary; 3872 QualType DstTy = TInfo->getType(); 3873 QualType SrcTy = E->getType(); 3874 3875 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 3876 return ExprError(Diag(BuiltinLoc, 3877 diag::err_convertvector_non_vector) 3878 << E->getSourceRange()); 3879 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 3880 return ExprError(Diag(BuiltinLoc, 3881 diag::err_convertvector_non_vector_type)); 3882 3883 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 3884 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 3885 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 3886 if (SrcElts != DstElts) 3887 return ExprError(Diag(BuiltinLoc, 3888 diag::err_convertvector_incompatible_vector) 3889 << E->getSourceRange()); 3890 } 3891 3892 return new (Context) 3893 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 3894 } 3895 3896 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 3897 // This is declared to take (const void*, ...) and can take two 3898 // optional constant int args. 3899 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 3900 unsigned NumArgs = TheCall->getNumArgs(); 3901 3902 if (NumArgs > 3) 3903 return Diag(TheCall->getLocEnd(), 3904 diag::err_typecheck_call_too_many_args_at_most) 3905 << 0 /*function call*/ << 3 << NumArgs 3906 << TheCall->getSourceRange(); 3907 3908 // Argument 0 is checked for us and the remaining arguments must be 3909 // constant integers. 3910 for (unsigned i = 1; i != NumArgs; ++i) 3911 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 3912 return true; 3913 3914 return false; 3915 } 3916 3917 /// SemaBuiltinAssume - Handle __assume (MS Extension). 3918 // __assume does not evaluate its arguments, and should warn if its argument 3919 // has side effects. 3920 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 3921 Expr *Arg = TheCall->getArg(0); 3922 if (Arg->isInstantiationDependent()) return false; 3923 3924 if (Arg->HasSideEffects(Context)) 3925 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 3926 << Arg->getSourceRange() 3927 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 3928 3929 return false; 3930 } 3931 3932 /// Handle __builtin_alloca_with_align. This is declared 3933 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 3934 /// than 8. 3935 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 3936 // The alignment must be a constant integer. 3937 Expr *Arg = TheCall->getArg(1); 3938 3939 // We can't check the value of a dependent argument. 3940 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 3941 if (const auto *UE = 3942 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 3943 if (UE->getKind() == UETT_AlignOf) 3944 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 3945 << Arg->getSourceRange(); 3946 3947 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 3948 3949 if (!Result.isPowerOf2()) 3950 return Diag(TheCall->getLocStart(), 3951 diag::err_alignment_not_power_of_two) 3952 << Arg->getSourceRange(); 3953 3954 if (Result < Context.getCharWidth()) 3955 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 3956 << (unsigned)Context.getCharWidth() 3957 << Arg->getSourceRange(); 3958 3959 if (Result > INT32_MAX) 3960 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 3961 << INT32_MAX 3962 << Arg->getSourceRange(); 3963 } 3964 3965 return false; 3966 } 3967 3968 /// Handle __builtin_assume_aligned. This is declared 3969 /// as (const void*, size_t, ...) and can take one optional constant int arg. 3970 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 3971 unsigned NumArgs = TheCall->getNumArgs(); 3972 3973 if (NumArgs > 3) 3974 return Diag(TheCall->getLocEnd(), 3975 diag::err_typecheck_call_too_many_args_at_most) 3976 << 0 /*function call*/ << 3 << NumArgs 3977 << TheCall->getSourceRange(); 3978 3979 // The alignment must be a constant integer. 3980 Expr *Arg = TheCall->getArg(1); 3981 3982 // We can't check the value of a dependent argument. 3983 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 3984 llvm::APSInt Result; 3985 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 3986 return true; 3987 3988 if (!Result.isPowerOf2()) 3989 return Diag(TheCall->getLocStart(), 3990 diag::err_alignment_not_power_of_two) 3991 << Arg->getSourceRange(); 3992 } 3993 3994 if (NumArgs > 2) { 3995 ExprResult Arg(TheCall->getArg(2)); 3996 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3997 Context.getSizeType(), false); 3998 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3999 if (Arg.isInvalid()) return true; 4000 TheCall->setArg(2, Arg.get()); 4001 } 4002 4003 return false; 4004 } 4005 4006 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 4007 unsigned BuiltinID = 4008 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 4009 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 4010 4011 unsigned NumArgs = TheCall->getNumArgs(); 4012 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 4013 if (NumArgs < NumRequiredArgs) { 4014 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4015 << 0 /* function call */ << NumRequiredArgs << NumArgs 4016 << TheCall->getSourceRange(); 4017 } 4018 if (NumArgs >= NumRequiredArgs + 0x100) { 4019 return Diag(TheCall->getLocEnd(), 4020 diag::err_typecheck_call_too_many_args_at_most) 4021 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 4022 << TheCall->getSourceRange(); 4023 } 4024 unsigned i = 0; 4025 4026 // For formatting call, check buffer arg. 4027 if (!IsSizeCall) { 4028 ExprResult Arg(TheCall->getArg(i)); 4029 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4030 Context, Context.VoidPtrTy, false); 4031 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4032 if (Arg.isInvalid()) 4033 return true; 4034 TheCall->setArg(i, Arg.get()); 4035 i++; 4036 } 4037 4038 // Check string literal arg. 4039 unsigned FormatIdx = i; 4040 { 4041 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4042 if (Arg.isInvalid()) 4043 return true; 4044 TheCall->setArg(i, Arg.get()); 4045 i++; 4046 } 4047 4048 // Make sure variadic args are scalar. 4049 unsigned FirstDataArg = i; 4050 while (i < NumArgs) { 4051 ExprResult Arg = DefaultVariadicArgumentPromotion( 4052 TheCall->getArg(i), VariadicFunction, nullptr); 4053 if (Arg.isInvalid()) 4054 return true; 4055 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4056 if (ArgSize.getQuantity() >= 0x100) { 4057 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4058 << i << (int)ArgSize.getQuantity() << 0xff 4059 << TheCall->getSourceRange(); 4060 } 4061 TheCall->setArg(i, Arg.get()); 4062 i++; 4063 } 4064 4065 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4066 // call to avoid duplicate diagnostics. 4067 if (!IsSizeCall) { 4068 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4069 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4070 bool Success = CheckFormatArguments( 4071 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4072 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4073 CheckedVarArgs); 4074 if (!Success) 4075 return true; 4076 } 4077 4078 if (IsSizeCall) { 4079 TheCall->setType(Context.getSizeType()); 4080 } else { 4081 TheCall->setType(Context.VoidPtrTy); 4082 } 4083 return false; 4084 } 4085 4086 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4087 /// TheCall is a constant expression. 4088 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4089 llvm::APSInt &Result) { 4090 Expr *Arg = TheCall->getArg(ArgNum); 4091 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4092 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4093 4094 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4095 4096 if (!Arg->isIntegerConstantExpr(Result, Context)) 4097 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 4098 << FDecl->getDeclName() << Arg->getSourceRange(); 4099 4100 return false; 4101 } 4102 4103 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 4104 /// TheCall is a constant expression in the range [Low, High]. 4105 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 4106 int Low, int High) { 4107 llvm::APSInt Result; 4108 4109 // We can't check the value of a dependent argument. 4110 Expr *Arg = TheCall->getArg(ArgNum); 4111 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4112 return false; 4113 4114 // Check constant-ness first. 4115 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4116 return true; 4117 4118 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 4119 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 4120 << Low << High << Arg->getSourceRange(); 4121 4122 return false; 4123 } 4124 4125 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 4126 /// TheCall is a constant expression is a multiple of Num.. 4127 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 4128 unsigned Num) { 4129 llvm::APSInt Result; 4130 4131 // We can't check the value of a dependent argument. 4132 Expr *Arg = TheCall->getArg(ArgNum); 4133 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4134 return false; 4135 4136 // Check constant-ness first. 4137 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4138 return true; 4139 4140 if (Result.getSExtValue() % Num != 0) 4141 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 4142 << Num << Arg->getSourceRange(); 4143 4144 return false; 4145 } 4146 4147 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 4148 /// TheCall is an ARM/AArch64 special register string literal. 4149 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 4150 int ArgNum, unsigned ExpectedFieldNum, 4151 bool AllowName) { 4152 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 4153 BuiltinID == ARM::BI__builtin_arm_wsr64 || 4154 BuiltinID == ARM::BI__builtin_arm_rsr || 4155 BuiltinID == ARM::BI__builtin_arm_rsrp || 4156 BuiltinID == ARM::BI__builtin_arm_wsr || 4157 BuiltinID == ARM::BI__builtin_arm_wsrp; 4158 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 4159 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 4160 BuiltinID == AArch64::BI__builtin_arm_rsr || 4161 BuiltinID == AArch64::BI__builtin_arm_rsrp || 4162 BuiltinID == AArch64::BI__builtin_arm_wsr || 4163 BuiltinID == AArch64::BI__builtin_arm_wsrp; 4164 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 4165 4166 // We can't check the value of a dependent argument. 4167 Expr *Arg = TheCall->getArg(ArgNum); 4168 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4169 return false; 4170 4171 // Check if the argument is a string literal. 4172 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4173 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 4174 << Arg->getSourceRange(); 4175 4176 // Check the type of special register given. 4177 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4178 SmallVector<StringRef, 6> Fields; 4179 Reg.split(Fields, ":"); 4180 4181 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 4182 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4183 << Arg->getSourceRange(); 4184 4185 // If the string is the name of a register then we cannot check that it is 4186 // valid here but if the string is of one the forms described in ACLE then we 4187 // can check that the supplied fields are integers and within the valid 4188 // ranges. 4189 if (Fields.size() > 1) { 4190 bool FiveFields = Fields.size() == 5; 4191 4192 bool ValidString = true; 4193 if (IsARMBuiltin) { 4194 ValidString &= Fields[0].startswith_lower("cp") || 4195 Fields[0].startswith_lower("p"); 4196 if (ValidString) 4197 Fields[0] = 4198 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 4199 4200 ValidString &= Fields[2].startswith_lower("c"); 4201 if (ValidString) 4202 Fields[2] = Fields[2].drop_front(1); 4203 4204 if (FiveFields) { 4205 ValidString &= Fields[3].startswith_lower("c"); 4206 if (ValidString) 4207 Fields[3] = Fields[3].drop_front(1); 4208 } 4209 } 4210 4211 SmallVector<int, 5> Ranges; 4212 if (FiveFields) 4213 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 4214 else 4215 Ranges.append({15, 7, 15}); 4216 4217 for (unsigned i=0; i<Fields.size(); ++i) { 4218 int IntField; 4219 ValidString &= !Fields[i].getAsInteger(10, IntField); 4220 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 4221 } 4222 4223 if (!ValidString) 4224 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4225 << Arg->getSourceRange(); 4226 4227 } else if (IsAArch64Builtin && Fields.size() == 1) { 4228 // If the register name is one of those that appear in the condition below 4229 // and the special register builtin being used is one of the write builtins, 4230 // then we require that the argument provided for writing to the register 4231 // is an integer constant expression. This is because it will be lowered to 4232 // an MSR (immediate) instruction, so we need to know the immediate at 4233 // compile time. 4234 if (TheCall->getNumArgs() != 2) 4235 return false; 4236 4237 std::string RegLower = Reg.lower(); 4238 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 4239 RegLower != "pan" && RegLower != "uao") 4240 return false; 4241 4242 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4243 } 4244 4245 return false; 4246 } 4247 4248 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 4249 /// This checks that the target supports __builtin_longjmp and 4250 /// that val is a constant 1. 4251 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 4252 if (!Context.getTargetInfo().hasSjLjLowering()) 4253 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 4254 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4255 4256 Expr *Arg = TheCall->getArg(1); 4257 llvm::APSInt Result; 4258 4259 // TODO: This is less than ideal. Overload this to take a value. 4260 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4261 return true; 4262 4263 if (Result != 1) 4264 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 4265 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 4266 4267 return false; 4268 } 4269 4270 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 4271 /// This checks that the target supports __builtin_setjmp. 4272 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 4273 if (!Context.getTargetInfo().hasSjLjLowering()) 4274 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 4275 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4276 return false; 4277 } 4278 4279 namespace { 4280 class UncoveredArgHandler { 4281 enum { Unknown = -1, AllCovered = -2 }; 4282 signed FirstUncoveredArg; 4283 SmallVector<const Expr *, 4> DiagnosticExprs; 4284 4285 public: 4286 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { } 4287 4288 bool hasUncoveredArg() const { 4289 return (FirstUncoveredArg >= 0); 4290 } 4291 4292 unsigned getUncoveredArg() const { 4293 assert(hasUncoveredArg() && "no uncovered argument"); 4294 return FirstUncoveredArg; 4295 } 4296 4297 void setAllCovered() { 4298 // A string has been found with all arguments covered, so clear out 4299 // the diagnostics. 4300 DiagnosticExprs.clear(); 4301 FirstUncoveredArg = AllCovered; 4302 } 4303 4304 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 4305 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 4306 4307 // Don't update if a previous string covers all arguments. 4308 if (FirstUncoveredArg == AllCovered) 4309 return; 4310 4311 // UncoveredArgHandler tracks the highest uncovered argument index 4312 // and with it all the strings that match this index. 4313 if (NewFirstUncoveredArg == FirstUncoveredArg) 4314 DiagnosticExprs.push_back(StrExpr); 4315 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 4316 DiagnosticExprs.clear(); 4317 DiagnosticExprs.push_back(StrExpr); 4318 FirstUncoveredArg = NewFirstUncoveredArg; 4319 } 4320 } 4321 4322 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 4323 }; 4324 4325 enum StringLiteralCheckType { 4326 SLCT_NotALiteral, 4327 SLCT_UncheckedLiteral, 4328 SLCT_CheckedLiteral 4329 }; 4330 } // end anonymous namespace 4331 4332 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 4333 BinaryOperatorKind BinOpKind, 4334 bool AddendIsRight) { 4335 unsigned BitWidth = Offset.getBitWidth(); 4336 unsigned AddendBitWidth = Addend.getBitWidth(); 4337 // There might be negative interim results. 4338 if (Addend.isUnsigned()) { 4339 Addend = Addend.zext(++AddendBitWidth); 4340 Addend.setIsSigned(true); 4341 } 4342 // Adjust the bit width of the APSInts. 4343 if (AddendBitWidth > BitWidth) { 4344 Offset = Offset.sext(AddendBitWidth); 4345 BitWidth = AddendBitWidth; 4346 } else if (BitWidth > AddendBitWidth) { 4347 Addend = Addend.sext(BitWidth); 4348 } 4349 4350 bool Ov = false; 4351 llvm::APSInt ResOffset = Offset; 4352 if (BinOpKind == BO_Add) 4353 ResOffset = Offset.sadd_ov(Addend, Ov); 4354 else { 4355 assert(AddendIsRight && BinOpKind == BO_Sub && 4356 "operator must be add or sub with addend on the right"); 4357 ResOffset = Offset.ssub_ov(Addend, Ov); 4358 } 4359 4360 // We add an offset to a pointer here so we should support an offset as big as 4361 // possible. 4362 if (Ov) { 4363 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big"); 4364 Offset = Offset.sext(2 * BitWidth); 4365 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 4366 return; 4367 } 4368 4369 Offset = ResOffset; 4370 } 4371 4372 namespace { 4373 // This is a wrapper class around StringLiteral to support offsetted string 4374 // literals as format strings. It takes the offset into account when returning 4375 // the string and its length or the source locations to display notes correctly. 4376 class FormatStringLiteral { 4377 const StringLiteral *FExpr; 4378 int64_t Offset; 4379 4380 public: 4381 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 4382 : FExpr(fexpr), Offset(Offset) {} 4383 4384 StringRef getString() const { 4385 return FExpr->getString().drop_front(Offset); 4386 } 4387 4388 unsigned getByteLength() const { 4389 return FExpr->getByteLength() - getCharByteWidth() * Offset; 4390 } 4391 unsigned getLength() const { return FExpr->getLength() - Offset; } 4392 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 4393 4394 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 4395 4396 QualType getType() const { return FExpr->getType(); } 4397 4398 bool isAscii() const { return FExpr->isAscii(); } 4399 bool isWide() const { return FExpr->isWide(); } 4400 bool isUTF8() const { return FExpr->isUTF8(); } 4401 bool isUTF16() const { return FExpr->isUTF16(); } 4402 bool isUTF32() const { return FExpr->isUTF32(); } 4403 bool isPascal() const { return FExpr->isPascal(); } 4404 4405 SourceLocation getLocationOfByte( 4406 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 4407 const TargetInfo &Target, unsigned *StartToken = nullptr, 4408 unsigned *StartTokenByteOffset = nullptr) const { 4409 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 4410 StartToken, StartTokenByteOffset); 4411 } 4412 4413 SourceLocation getLocStart() const LLVM_READONLY { 4414 return FExpr->getLocStart().getLocWithOffset(Offset); 4415 } 4416 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 4417 }; 4418 } // end anonymous namespace 4419 4420 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 4421 const Expr *OrigFormatExpr, 4422 ArrayRef<const Expr *> Args, 4423 bool HasVAListArg, unsigned format_idx, 4424 unsigned firstDataArg, 4425 Sema::FormatStringType Type, 4426 bool inFunctionCall, 4427 Sema::VariadicCallType CallType, 4428 llvm::SmallBitVector &CheckedVarArgs, 4429 UncoveredArgHandler &UncoveredArg); 4430 4431 // Determine if an expression is a string literal or constant string. 4432 // If this function returns false on the arguments to a function expecting a 4433 // format string, we will usually need to emit a warning. 4434 // True string literals are then checked by CheckFormatString. 4435 static StringLiteralCheckType 4436 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 4437 bool HasVAListArg, unsigned format_idx, 4438 unsigned firstDataArg, Sema::FormatStringType Type, 4439 Sema::VariadicCallType CallType, bool InFunctionCall, 4440 llvm::SmallBitVector &CheckedVarArgs, 4441 UncoveredArgHandler &UncoveredArg, 4442 llvm::APSInt Offset) { 4443 tryAgain: 4444 assert(Offset.isSigned() && "invalid offset"); 4445 4446 if (E->isTypeDependent() || E->isValueDependent()) 4447 return SLCT_NotALiteral; 4448 4449 E = E->IgnoreParenCasts(); 4450 4451 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 4452 // Technically -Wformat-nonliteral does not warn about this case. 4453 // The behavior of printf and friends in this case is implementation 4454 // dependent. Ideally if the format string cannot be null then 4455 // it should have a 'nonnull' attribute in the function prototype. 4456 return SLCT_UncheckedLiteral; 4457 4458 switch (E->getStmtClass()) { 4459 case Stmt::BinaryConditionalOperatorClass: 4460 case Stmt::ConditionalOperatorClass: { 4461 // The expression is a literal if both sub-expressions were, and it was 4462 // completely checked only if both sub-expressions were checked. 4463 const AbstractConditionalOperator *C = 4464 cast<AbstractConditionalOperator>(E); 4465 4466 // Determine whether it is necessary to check both sub-expressions, for 4467 // example, because the condition expression is a constant that can be 4468 // evaluated at compile time. 4469 bool CheckLeft = true, CheckRight = true; 4470 4471 bool Cond; 4472 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 4473 if (Cond) 4474 CheckRight = false; 4475 else 4476 CheckLeft = false; 4477 } 4478 4479 // We need to maintain the offsets for the right and the left hand side 4480 // separately to check if every possible indexed expression is a valid 4481 // string literal. They might have different offsets for different string 4482 // literals in the end. 4483 StringLiteralCheckType Left; 4484 if (!CheckLeft) 4485 Left = SLCT_UncheckedLiteral; 4486 else { 4487 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 4488 HasVAListArg, format_idx, firstDataArg, 4489 Type, CallType, InFunctionCall, 4490 CheckedVarArgs, UncoveredArg, Offset); 4491 if (Left == SLCT_NotALiteral || !CheckRight) { 4492 return Left; 4493 } 4494 } 4495 4496 StringLiteralCheckType Right = 4497 checkFormatStringExpr(S, C->getFalseExpr(), Args, 4498 HasVAListArg, format_idx, firstDataArg, 4499 Type, CallType, InFunctionCall, CheckedVarArgs, 4500 UncoveredArg, Offset); 4501 4502 return (CheckLeft && Left < Right) ? Left : Right; 4503 } 4504 4505 case Stmt::ImplicitCastExprClass: { 4506 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4507 goto tryAgain; 4508 } 4509 4510 case Stmt::OpaqueValueExprClass: 4511 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 4512 E = src; 4513 goto tryAgain; 4514 } 4515 return SLCT_NotALiteral; 4516 4517 case Stmt::PredefinedExprClass: 4518 // While __func__, etc., are technically not string literals, they 4519 // cannot contain format specifiers and thus are not a security 4520 // liability. 4521 return SLCT_UncheckedLiteral; 4522 4523 case Stmt::DeclRefExprClass: { 4524 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 4525 4526 // As an exception, do not flag errors for variables binding to 4527 // const string literals. 4528 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 4529 bool isConstant = false; 4530 QualType T = DR->getType(); 4531 4532 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 4533 isConstant = AT->getElementType().isConstant(S.Context); 4534 } else if (const PointerType *PT = T->getAs<PointerType>()) { 4535 isConstant = T.isConstant(S.Context) && 4536 PT->getPointeeType().isConstant(S.Context); 4537 } else if (T->isObjCObjectPointerType()) { 4538 // In ObjC, there is usually no "const ObjectPointer" type, 4539 // so don't check if the pointee type is constant. 4540 isConstant = T.isConstant(S.Context); 4541 } 4542 4543 if (isConstant) { 4544 if (const Expr *Init = VD->getAnyInitializer()) { 4545 // Look through initializers like const char c[] = { "foo" } 4546 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4547 if (InitList->isStringLiteralInit()) 4548 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 4549 } 4550 return checkFormatStringExpr(S, Init, Args, 4551 HasVAListArg, format_idx, 4552 firstDataArg, Type, CallType, 4553 /*InFunctionCall*/ false, CheckedVarArgs, 4554 UncoveredArg, Offset); 4555 } 4556 } 4557 4558 // For vprintf* functions (i.e., HasVAListArg==true), we add a 4559 // special check to see if the format string is a function parameter 4560 // of the function calling the printf function. If the function 4561 // has an attribute indicating it is a printf-like function, then we 4562 // should suppress warnings concerning non-literals being used in a call 4563 // to a vprintf function. For example: 4564 // 4565 // void 4566 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 4567 // va_list ap; 4568 // va_start(ap, fmt); 4569 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 4570 // ... 4571 // } 4572 if (HasVAListArg) { 4573 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 4574 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 4575 int PVIndex = PV->getFunctionScopeIndex() + 1; 4576 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 4577 // adjust for implicit parameter 4578 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4579 if (MD->isInstance()) 4580 ++PVIndex; 4581 // We also check if the formats are compatible. 4582 // We can't pass a 'scanf' string to a 'printf' function. 4583 if (PVIndex == PVFormat->getFormatIdx() && 4584 Type == S.GetFormatStringType(PVFormat)) 4585 return SLCT_UncheckedLiteral; 4586 } 4587 } 4588 } 4589 } 4590 } 4591 4592 return SLCT_NotALiteral; 4593 } 4594 4595 case Stmt::CallExprClass: 4596 case Stmt::CXXMemberCallExprClass: { 4597 const CallExpr *CE = cast<CallExpr>(E); 4598 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 4599 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 4600 unsigned ArgIndex = FA->getFormatIdx(); 4601 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4602 if (MD->isInstance()) 4603 --ArgIndex; 4604 const Expr *Arg = CE->getArg(ArgIndex - 1); 4605 4606 return checkFormatStringExpr(S, Arg, Args, 4607 HasVAListArg, format_idx, firstDataArg, 4608 Type, CallType, InFunctionCall, 4609 CheckedVarArgs, UncoveredArg, Offset); 4610 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 4611 unsigned BuiltinID = FD->getBuiltinID(); 4612 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 4613 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 4614 const Expr *Arg = CE->getArg(0); 4615 return checkFormatStringExpr(S, Arg, Args, 4616 HasVAListArg, format_idx, 4617 firstDataArg, Type, CallType, 4618 InFunctionCall, CheckedVarArgs, 4619 UncoveredArg, Offset); 4620 } 4621 } 4622 } 4623 4624 return SLCT_NotALiteral; 4625 } 4626 case Stmt::ObjCMessageExprClass: { 4627 const auto *ME = cast<ObjCMessageExpr>(E); 4628 if (const auto *ND = ME->getMethodDecl()) { 4629 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 4630 unsigned ArgIndex = FA->getFormatIdx(); 4631 const Expr *Arg = ME->getArg(ArgIndex - 1); 4632 return checkFormatStringExpr( 4633 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 4634 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 4635 } 4636 } 4637 4638 return SLCT_NotALiteral; 4639 } 4640 case Stmt::ObjCStringLiteralClass: 4641 case Stmt::StringLiteralClass: { 4642 const StringLiteral *StrE = nullptr; 4643 4644 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 4645 StrE = ObjCFExpr->getString(); 4646 else 4647 StrE = cast<StringLiteral>(E); 4648 4649 if (StrE) { 4650 if (Offset.isNegative() || Offset > StrE->getLength()) { 4651 // TODO: It would be better to have an explicit warning for out of 4652 // bounds literals. 4653 return SLCT_NotALiteral; 4654 } 4655 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 4656 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 4657 firstDataArg, Type, InFunctionCall, CallType, 4658 CheckedVarArgs, UncoveredArg); 4659 return SLCT_CheckedLiteral; 4660 } 4661 4662 return SLCT_NotALiteral; 4663 } 4664 case Stmt::BinaryOperatorClass: { 4665 llvm::APSInt LResult; 4666 llvm::APSInt RResult; 4667 4668 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 4669 4670 // A string literal + an int offset is still a string literal. 4671 if (BinOp->isAdditiveOp()) { 4672 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 4673 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 4674 4675 if (LIsInt != RIsInt) { 4676 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 4677 4678 if (LIsInt) { 4679 if (BinOpKind == BO_Add) { 4680 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 4681 E = BinOp->getRHS(); 4682 goto tryAgain; 4683 } 4684 } else { 4685 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 4686 E = BinOp->getLHS(); 4687 goto tryAgain; 4688 } 4689 } 4690 } 4691 4692 return SLCT_NotALiteral; 4693 } 4694 case Stmt::UnaryOperatorClass: { 4695 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 4696 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 4697 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) { 4698 llvm::APSInt IndexResult; 4699 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 4700 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 4701 E = ASE->getBase(); 4702 goto tryAgain; 4703 } 4704 } 4705 4706 return SLCT_NotALiteral; 4707 } 4708 4709 default: 4710 return SLCT_NotALiteral; 4711 } 4712 } 4713 4714 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 4715 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 4716 .Case("scanf", FST_Scanf) 4717 .Cases("printf", "printf0", FST_Printf) 4718 .Cases("NSString", "CFString", FST_NSString) 4719 .Case("strftime", FST_Strftime) 4720 .Case("strfmon", FST_Strfmon) 4721 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 4722 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 4723 .Case("os_trace", FST_OSLog) 4724 .Case("os_log", FST_OSLog) 4725 .Default(FST_Unknown); 4726 } 4727 4728 /// CheckFormatArguments - Check calls to printf and scanf (and similar 4729 /// functions) for correct use of format strings. 4730 /// Returns true if a format string has been fully checked. 4731 bool Sema::CheckFormatArguments(const FormatAttr *Format, 4732 ArrayRef<const Expr *> Args, 4733 bool IsCXXMember, 4734 VariadicCallType CallType, 4735 SourceLocation Loc, SourceRange Range, 4736 llvm::SmallBitVector &CheckedVarArgs) { 4737 FormatStringInfo FSI; 4738 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 4739 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 4740 FSI.FirstDataArg, GetFormatStringType(Format), 4741 CallType, Loc, Range, CheckedVarArgs); 4742 return false; 4743 } 4744 4745 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 4746 bool HasVAListArg, unsigned format_idx, 4747 unsigned firstDataArg, FormatStringType Type, 4748 VariadicCallType CallType, 4749 SourceLocation Loc, SourceRange Range, 4750 llvm::SmallBitVector &CheckedVarArgs) { 4751 // CHECK: printf/scanf-like function is called with no format string. 4752 if (format_idx >= Args.size()) { 4753 Diag(Loc, diag::warn_missing_format_string) << Range; 4754 return false; 4755 } 4756 4757 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 4758 4759 // CHECK: format string is not a string literal. 4760 // 4761 // Dynamically generated format strings are difficult to 4762 // automatically vet at compile time. Requiring that format strings 4763 // are string literals: (1) permits the checking of format strings by 4764 // the compiler and thereby (2) can practically remove the source of 4765 // many format string exploits. 4766 4767 // Format string can be either ObjC string (e.g. @"%d") or 4768 // C string (e.g. "%d") 4769 // ObjC string uses the same format specifiers as C string, so we can use 4770 // the same format string checking logic for both ObjC and C strings. 4771 UncoveredArgHandler UncoveredArg; 4772 StringLiteralCheckType CT = 4773 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 4774 format_idx, firstDataArg, Type, CallType, 4775 /*IsFunctionCall*/ true, CheckedVarArgs, 4776 UncoveredArg, 4777 /*no string offset*/ llvm::APSInt(64, false) = 0); 4778 4779 // Generate a diagnostic where an uncovered argument is detected. 4780 if (UncoveredArg.hasUncoveredArg()) { 4781 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 4782 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 4783 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 4784 } 4785 4786 if (CT != SLCT_NotALiteral) 4787 // Literal format string found, check done! 4788 return CT == SLCT_CheckedLiteral; 4789 4790 // Strftime is particular as it always uses a single 'time' argument, 4791 // so it is safe to pass a non-literal string. 4792 if (Type == FST_Strftime) 4793 return false; 4794 4795 // Do not emit diag when the string param is a macro expansion and the 4796 // format is either NSString or CFString. This is a hack to prevent 4797 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 4798 // which are usually used in place of NS and CF string literals. 4799 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 4800 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 4801 return false; 4802 4803 // If there are no arguments specified, warn with -Wformat-security, otherwise 4804 // warn only with -Wformat-nonliteral. 4805 if (Args.size() == firstDataArg) { 4806 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 4807 << OrigFormatExpr->getSourceRange(); 4808 switch (Type) { 4809 default: 4810 break; 4811 case FST_Kprintf: 4812 case FST_FreeBSDKPrintf: 4813 case FST_Printf: 4814 Diag(FormatLoc, diag::note_format_security_fixit) 4815 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 4816 break; 4817 case FST_NSString: 4818 Diag(FormatLoc, diag::note_format_security_fixit) 4819 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 4820 break; 4821 } 4822 } else { 4823 Diag(FormatLoc, diag::warn_format_nonliteral) 4824 << OrigFormatExpr->getSourceRange(); 4825 } 4826 return false; 4827 } 4828 4829 namespace { 4830 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 4831 protected: 4832 Sema &S; 4833 const FormatStringLiteral *FExpr; 4834 const Expr *OrigFormatExpr; 4835 const Sema::FormatStringType FSType; 4836 const unsigned FirstDataArg; 4837 const unsigned NumDataArgs; 4838 const char *Beg; // Start of format string. 4839 const bool HasVAListArg; 4840 ArrayRef<const Expr *> Args; 4841 unsigned FormatIdx; 4842 llvm::SmallBitVector CoveredArgs; 4843 bool usesPositionalArgs; 4844 bool atFirstArg; 4845 bool inFunctionCall; 4846 Sema::VariadicCallType CallType; 4847 llvm::SmallBitVector &CheckedVarArgs; 4848 UncoveredArgHandler &UncoveredArg; 4849 4850 public: 4851 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 4852 const Expr *origFormatExpr, 4853 const Sema::FormatStringType type, unsigned firstDataArg, 4854 unsigned numDataArgs, const char *beg, bool hasVAListArg, 4855 ArrayRef<const Expr *> Args, unsigned formatIdx, 4856 bool inFunctionCall, Sema::VariadicCallType callType, 4857 llvm::SmallBitVector &CheckedVarArgs, 4858 UncoveredArgHandler &UncoveredArg) 4859 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 4860 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 4861 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 4862 usesPositionalArgs(false), atFirstArg(true), 4863 inFunctionCall(inFunctionCall), CallType(callType), 4864 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 4865 CoveredArgs.resize(numDataArgs); 4866 CoveredArgs.reset(); 4867 } 4868 4869 void DoneProcessing(); 4870 4871 void HandleIncompleteSpecifier(const char *startSpecifier, 4872 unsigned specifierLen) override; 4873 4874 void HandleInvalidLengthModifier( 4875 const analyze_format_string::FormatSpecifier &FS, 4876 const analyze_format_string::ConversionSpecifier &CS, 4877 const char *startSpecifier, unsigned specifierLen, 4878 unsigned DiagID); 4879 4880 void HandleNonStandardLengthModifier( 4881 const analyze_format_string::FormatSpecifier &FS, 4882 const char *startSpecifier, unsigned specifierLen); 4883 4884 void HandleNonStandardConversionSpecifier( 4885 const analyze_format_string::ConversionSpecifier &CS, 4886 const char *startSpecifier, unsigned specifierLen); 4887 4888 void HandlePosition(const char *startPos, unsigned posLen) override; 4889 4890 void HandleInvalidPosition(const char *startSpecifier, 4891 unsigned specifierLen, 4892 analyze_format_string::PositionContext p) override; 4893 4894 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 4895 4896 void HandleNullChar(const char *nullCharacter) override; 4897 4898 template <typename Range> 4899 static void 4900 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 4901 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 4902 bool IsStringLocation, Range StringRange, 4903 ArrayRef<FixItHint> Fixit = None); 4904 4905 protected: 4906 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 4907 const char *startSpec, 4908 unsigned specifierLen, 4909 const char *csStart, unsigned csLen); 4910 4911 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 4912 const char *startSpec, 4913 unsigned specifierLen); 4914 4915 SourceRange getFormatStringRange(); 4916 CharSourceRange getSpecifierRange(const char *startSpecifier, 4917 unsigned specifierLen); 4918 SourceLocation getLocationOfByte(const char *x); 4919 4920 const Expr *getDataArg(unsigned i) const; 4921 4922 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 4923 const analyze_format_string::ConversionSpecifier &CS, 4924 const char *startSpecifier, unsigned specifierLen, 4925 unsigned argIndex); 4926 4927 template <typename Range> 4928 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 4929 bool IsStringLocation, Range StringRange, 4930 ArrayRef<FixItHint> Fixit = None); 4931 }; 4932 } // end anonymous namespace 4933 4934 SourceRange CheckFormatHandler::getFormatStringRange() { 4935 return OrigFormatExpr->getSourceRange(); 4936 } 4937 4938 CharSourceRange CheckFormatHandler:: 4939 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 4940 SourceLocation Start = getLocationOfByte(startSpecifier); 4941 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 4942 4943 // Advance the end SourceLocation by one due to half-open ranges. 4944 End = End.getLocWithOffset(1); 4945 4946 return CharSourceRange::getCharRange(Start, End); 4947 } 4948 4949 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 4950 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 4951 S.getLangOpts(), S.Context.getTargetInfo()); 4952 } 4953 4954 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 4955 unsigned specifierLen){ 4956 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 4957 getLocationOfByte(startSpecifier), 4958 /*IsStringLocation*/true, 4959 getSpecifierRange(startSpecifier, specifierLen)); 4960 } 4961 4962 void CheckFormatHandler::HandleInvalidLengthModifier( 4963 const analyze_format_string::FormatSpecifier &FS, 4964 const analyze_format_string::ConversionSpecifier &CS, 4965 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 4966 using namespace analyze_format_string; 4967 4968 const LengthModifier &LM = FS.getLengthModifier(); 4969 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 4970 4971 // See if we know how to fix this length modifier. 4972 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 4973 if (FixedLM) { 4974 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 4975 getLocationOfByte(LM.getStart()), 4976 /*IsStringLocation*/true, 4977 getSpecifierRange(startSpecifier, specifierLen)); 4978 4979 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 4980 << FixedLM->toString() 4981 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 4982 4983 } else { 4984 FixItHint Hint; 4985 if (DiagID == diag::warn_format_nonsensical_length) 4986 Hint = FixItHint::CreateRemoval(LMRange); 4987 4988 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 4989 getLocationOfByte(LM.getStart()), 4990 /*IsStringLocation*/true, 4991 getSpecifierRange(startSpecifier, specifierLen), 4992 Hint); 4993 } 4994 } 4995 4996 void CheckFormatHandler::HandleNonStandardLengthModifier( 4997 const analyze_format_string::FormatSpecifier &FS, 4998 const char *startSpecifier, unsigned specifierLen) { 4999 using namespace analyze_format_string; 5000 5001 const LengthModifier &LM = FS.getLengthModifier(); 5002 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5003 5004 // See if we know how to fix this length modifier. 5005 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5006 if (FixedLM) { 5007 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5008 << LM.toString() << 0, 5009 getLocationOfByte(LM.getStart()), 5010 /*IsStringLocation*/true, 5011 getSpecifierRange(startSpecifier, specifierLen)); 5012 5013 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5014 << FixedLM->toString() 5015 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5016 5017 } else { 5018 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5019 << LM.toString() << 0, 5020 getLocationOfByte(LM.getStart()), 5021 /*IsStringLocation*/true, 5022 getSpecifierRange(startSpecifier, specifierLen)); 5023 } 5024 } 5025 5026 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5027 const analyze_format_string::ConversionSpecifier &CS, 5028 const char *startSpecifier, unsigned specifierLen) { 5029 using namespace analyze_format_string; 5030 5031 // See if we know how to fix this conversion specifier. 5032 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5033 if (FixedCS) { 5034 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5035 << CS.toString() << /*conversion specifier*/1, 5036 getLocationOfByte(CS.getStart()), 5037 /*IsStringLocation*/true, 5038 getSpecifierRange(startSpecifier, specifierLen)); 5039 5040 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5041 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5042 << FixedCS->toString() 5043 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5044 } else { 5045 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5046 << CS.toString() << /*conversion specifier*/1, 5047 getLocationOfByte(CS.getStart()), 5048 /*IsStringLocation*/true, 5049 getSpecifierRange(startSpecifier, specifierLen)); 5050 } 5051 } 5052 5053 void CheckFormatHandler::HandlePosition(const char *startPos, 5054 unsigned posLen) { 5055 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5056 getLocationOfByte(startPos), 5057 /*IsStringLocation*/true, 5058 getSpecifierRange(startPos, posLen)); 5059 } 5060 5061 void 5062 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5063 analyze_format_string::PositionContext p) { 5064 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5065 << (unsigned) p, 5066 getLocationOfByte(startPos), /*IsStringLocation*/true, 5067 getSpecifierRange(startPos, posLen)); 5068 } 5069 5070 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5071 unsigned posLen) { 5072 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5073 getLocationOfByte(startPos), 5074 /*IsStringLocation*/true, 5075 getSpecifierRange(startPos, posLen)); 5076 } 5077 5078 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5079 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5080 // The presence of a null character is likely an error. 5081 EmitFormatDiagnostic( 5082 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5083 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5084 getFormatStringRange()); 5085 } 5086 } 5087 5088 // Note that this may return NULL if there was an error parsing or building 5089 // one of the argument expressions. 5090 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5091 return Args[FirstDataArg + i]; 5092 } 5093 5094 void CheckFormatHandler::DoneProcessing() { 5095 // Does the number of data arguments exceed the number of 5096 // format conversions in the format string? 5097 if (!HasVAListArg) { 5098 // Find any arguments that weren't covered. 5099 CoveredArgs.flip(); 5100 signed notCoveredArg = CoveredArgs.find_first(); 5101 if (notCoveredArg >= 0) { 5102 assert((unsigned)notCoveredArg < NumDataArgs); 5103 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 5104 } else { 5105 UncoveredArg.setAllCovered(); 5106 } 5107 } 5108 } 5109 5110 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 5111 const Expr *ArgExpr) { 5112 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 5113 "Invalid state"); 5114 5115 if (!ArgExpr) 5116 return; 5117 5118 SourceLocation Loc = ArgExpr->getLocStart(); 5119 5120 if (S.getSourceManager().isInSystemMacro(Loc)) 5121 return; 5122 5123 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 5124 for (auto E : DiagnosticExprs) 5125 PDiag << E->getSourceRange(); 5126 5127 CheckFormatHandler::EmitFormatDiagnostic( 5128 S, IsFunctionCall, DiagnosticExprs[0], 5129 PDiag, Loc, /*IsStringLocation*/false, 5130 DiagnosticExprs[0]->getSourceRange()); 5131 } 5132 5133 bool 5134 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 5135 SourceLocation Loc, 5136 const char *startSpec, 5137 unsigned specifierLen, 5138 const char *csStart, 5139 unsigned csLen) { 5140 bool keepGoing = true; 5141 if (argIndex < NumDataArgs) { 5142 // Consider the argument coverered, even though the specifier doesn't 5143 // make sense. 5144 CoveredArgs.set(argIndex); 5145 } 5146 else { 5147 // If argIndex exceeds the number of data arguments we 5148 // don't issue a warning because that is just a cascade of warnings (and 5149 // they may have intended '%%' anyway). We don't want to continue processing 5150 // the format string after this point, however, as we will like just get 5151 // gibberish when trying to match arguments. 5152 keepGoing = false; 5153 } 5154 5155 StringRef Specifier(csStart, csLen); 5156 5157 // If the specifier in non-printable, it could be the first byte of a UTF-8 5158 // sequence. In that case, print the UTF-8 code point. If not, print the byte 5159 // hex value. 5160 std::string CodePointStr; 5161 if (!llvm::sys::locale::isPrint(*csStart)) { 5162 llvm::UTF32 CodePoint; 5163 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 5164 const llvm::UTF8 *E = 5165 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 5166 llvm::ConversionResult Result = 5167 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 5168 5169 if (Result != llvm::conversionOK) { 5170 unsigned char FirstChar = *csStart; 5171 CodePoint = (llvm::UTF32)FirstChar; 5172 } 5173 5174 llvm::raw_string_ostream OS(CodePointStr); 5175 if (CodePoint < 256) 5176 OS << "\\x" << llvm::format("%02x", CodePoint); 5177 else if (CodePoint <= 0xFFFF) 5178 OS << "\\u" << llvm::format("%04x", CodePoint); 5179 else 5180 OS << "\\U" << llvm::format("%08x", CodePoint); 5181 OS.flush(); 5182 Specifier = CodePointStr; 5183 } 5184 5185 EmitFormatDiagnostic( 5186 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 5187 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 5188 5189 return keepGoing; 5190 } 5191 5192 void 5193 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 5194 const char *startSpec, 5195 unsigned specifierLen) { 5196 EmitFormatDiagnostic( 5197 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 5198 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 5199 } 5200 5201 bool 5202 CheckFormatHandler::CheckNumArgs( 5203 const analyze_format_string::FormatSpecifier &FS, 5204 const analyze_format_string::ConversionSpecifier &CS, 5205 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 5206 5207 if (argIndex >= NumDataArgs) { 5208 PartialDiagnostic PDiag = FS.usesPositionalArg() 5209 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 5210 << (argIndex+1) << NumDataArgs) 5211 : S.PDiag(diag::warn_printf_insufficient_data_args); 5212 EmitFormatDiagnostic( 5213 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 5214 getSpecifierRange(startSpecifier, specifierLen)); 5215 5216 // Since more arguments than conversion tokens are given, by extension 5217 // all arguments are covered, so mark this as so. 5218 UncoveredArg.setAllCovered(); 5219 return false; 5220 } 5221 return true; 5222 } 5223 5224 template<typename Range> 5225 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 5226 SourceLocation Loc, 5227 bool IsStringLocation, 5228 Range StringRange, 5229 ArrayRef<FixItHint> FixIt) { 5230 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 5231 Loc, IsStringLocation, StringRange, FixIt); 5232 } 5233 5234 /// \brief If the format string is not within the funcion call, emit a note 5235 /// so that the function call and string are in diagnostic messages. 5236 /// 5237 /// \param InFunctionCall if true, the format string is within the function 5238 /// call and only one diagnostic message will be produced. Otherwise, an 5239 /// extra note will be emitted pointing to location of the format string. 5240 /// 5241 /// \param ArgumentExpr the expression that is passed as the format string 5242 /// argument in the function call. Used for getting locations when two 5243 /// diagnostics are emitted. 5244 /// 5245 /// \param PDiag the callee should already have provided any strings for the 5246 /// diagnostic message. This function only adds locations and fixits 5247 /// to diagnostics. 5248 /// 5249 /// \param Loc primary location for diagnostic. If two diagnostics are 5250 /// required, one will be at Loc and a new SourceLocation will be created for 5251 /// the other one. 5252 /// 5253 /// \param IsStringLocation if true, Loc points to the format string should be 5254 /// used for the note. Otherwise, Loc points to the argument list and will 5255 /// be used with PDiag. 5256 /// 5257 /// \param StringRange some or all of the string to highlight. This is 5258 /// templated so it can accept either a CharSourceRange or a SourceRange. 5259 /// 5260 /// \param FixIt optional fix it hint for the format string. 5261 template <typename Range> 5262 void CheckFormatHandler::EmitFormatDiagnostic( 5263 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 5264 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 5265 Range StringRange, ArrayRef<FixItHint> FixIt) { 5266 if (InFunctionCall) { 5267 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 5268 D << StringRange; 5269 D << FixIt; 5270 } else { 5271 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 5272 << ArgumentExpr->getSourceRange(); 5273 5274 const Sema::SemaDiagnosticBuilder &Note = 5275 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 5276 diag::note_format_string_defined); 5277 5278 Note << StringRange; 5279 Note << FixIt; 5280 } 5281 } 5282 5283 //===--- CHECK: Printf format string checking ------------------------------===// 5284 5285 namespace { 5286 class CheckPrintfHandler : public CheckFormatHandler { 5287 public: 5288 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 5289 const Expr *origFormatExpr, 5290 const Sema::FormatStringType type, unsigned firstDataArg, 5291 unsigned numDataArgs, bool isObjC, const char *beg, 5292 bool hasVAListArg, ArrayRef<const Expr *> Args, 5293 unsigned formatIdx, bool inFunctionCall, 5294 Sema::VariadicCallType CallType, 5295 llvm::SmallBitVector &CheckedVarArgs, 5296 UncoveredArgHandler &UncoveredArg) 5297 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 5298 numDataArgs, beg, hasVAListArg, Args, formatIdx, 5299 inFunctionCall, CallType, CheckedVarArgs, 5300 UncoveredArg) {} 5301 5302 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 5303 5304 /// Returns true if '%@' specifiers are allowed in the format string. 5305 bool allowsObjCArg() const { 5306 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 5307 FSType == Sema::FST_OSTrace; 5308 } 5309 5310 bool HandleInvalidPrintfConversionSpecifier( 5311 const analyze_printf::PrintfSpecifier &FS, 5312 const char *startSpecifier, 5313 unsigned specifierLen) override; 5314 5315 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 5316 const char *startSpecifier, 5317 unsigned specifierLen) override; 5318 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5319 const char *StartSpecifier, 5320 unsigned SpecifierLen, 5321 const Expr *E); 5322 5323 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 5324 const char *startSpecifier, unsigned specifierLen); 5325 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 5326 const analyze_printf::OptionalAmount &Amt, 5327 unsigned type, 5328 const char *startSpecifier, unsigned specifierLen); 5329 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5330 const analyze_printf::OptionalFlag &flag, 5331 const char *startSpecifier, unsigned specifierLen); 5332 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 5333 const analyze_printf::OptionalFlag &ignoredFlag, 5334 const analyze_printf::OptionalFlag &flag, 5335 const char *startSpecifier, unsigned specifierLen); 5336 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 5337 const Expr *E); 5338 5339 void HandleEmptyObjCModifierFlag(const char *startFlag, 5340 unsigned flagLen) override; 5341 5342 void HandleInvalidObjCModifierFlag(const char *startFlag, 5343 unsigned flagLen) override; 5344 5345 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 5346 const char *flagsEnd, 5347 const char *conversionPosition) 5348 override; 5349 }; 5350 } // end anonymous namespace 5351 5352 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 5353 const analyze_printf::PrintfSpecifier &FS, 5354 const char *startSpecifier, 5355 unsigned specifierLen) { 5356 const analyze_printf::PrintfConversionSpecifier &CS = 5357 FS.getConversionSpecifier(); 5358 5359 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5360 getLocationOfByte(CS.getStart()), 5361 startSpecifier, specifierLen, 5362 CS.getStart(), CS.getLength()); 5363 } 5364 5365 bool CheckPrintfHandler::HandleAmount( 5366 const analyze_format_string::OptionalAmount &Amt, 5367 unsigned k, const char *startSpecifier, 5368 unsigned specifierLen) { 5369 if (Amt.hasDataArgument()) { 5370 if (!HasVAListArg) { 5371 unsigned argIndex = Amt.getArgIndex(); 5372 if (argIndex >= NumDataArgs) { 5373 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 5374 << k, 5375 getLocationOfByte(Amt.getStart()), 5376 /*IsStringLocation*/true, 5377 getSpecifierRange(startSpecifier, specifierLen)); 5378 // Don't do any more checking. We will just emit 5379 // spurious errors. 5380 return false; 5381 } 5382 5383 // Type check the data argument. It should be an 'int'. 5384 // Although not in conformance with C99, we also allow the argument to be 5385 // an 'unsigned int' as that is a reasonably safe case. GCC also 5386 // doesn't emit a warning for that case. 5387 CoveredArgs.set(argIndex); 5388 const Expr *Arg = getDataArg(argIndex); 5389 if (!Arg) 5390 return false; 5391 5392 QualType T = Arg->getType(); 5393 5394 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 5395 assert(AT.isValid()); 5396 5397 if (!AT.matchesType(S.Context, T)) { 5398 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 5399 << k << AT.getRepresentativeTypeName(S.Context) 5400 << T << Arg->getSourceRange(), 5401 getLocationOfByte(Amt.getStart()), 5402 /*IsStringLocation*/true, 5403 getSpecifierRange(startSpecifier, specifierLen)); 5404 // Don't do any more checking. We will just emit 5405 // spurious errors. 5406 return false; 5407 } 5408 } 5409 } 5410 return true; 5411 } 5412 5413 void CheckPrintfHandler::HandleInvalidAmount( 5414 const analyze_printf::PrintfSpecifier &FS, 5415 const analyze_printf::OptionalAmount &Amt, 5416 unsigned type, 5417 const char *startSpecifier, 5418 unsigned specifierLen) { 5419 const analyze_printf::PrintfConversionSpecifier &CS = 5420 FS.getConversionSpecifier(); 5421 5422 FixItHint fixit = 5423 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 5424 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 5425 Amt.getConstantLength())) 5426 : FixItHint(); 5427 5428 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 5429 << type << CS.toString(), 5430 getLocationOfByte(Amt.getStart()), 5431 /*IsStringLocation*/true, 5432 getSpecifierRange(startSpecifier, specifierLen), 5433 fixit); 5434 } 5435 5436 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5437 const analyze_printf::OptionalFlag &flag, 5438 const char *startSpecifier, 5439 unsigned specifierLen) { 5440 // Warn about pointless flag with a fixit removal. 5441 const analyze_printf::PrintfConversionSpecifier &CS = 5442 FS.getConversionSpecifier(); 5443 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 5444 << flag.toString() << CS.toString(), 5445 getLocationOfByte(flag.getPosition()), 5446 /*IsStringLocation*/true, 5447 getSpecifierRange(startSpecifier, specifierLen), 5448 FixItHint::CreateRemoval( 5449 getSpecifierRange(flag.getPosition(), 1))); 5450 } 5451 5452 void CheckPrintfHandler::HandleIgnoredFlag( 5453 const analyze_printf::PrintfSpecifier &FS, 5454 const analyze_printf::OptionalFlag &ignoredFlag, 5455 const analyze_printf::OptionalFlag &flag, 5456 const char *startSpecifier, 5457 unsigned specifierLen) { 5458 // Warn about ignored flag with a fixit removal. 5459 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 5460 << ignoredFlag.toString() << flag.toString(), 5461 getLocationOfByte(ignoredFlag.getPosition()), 5462 /*IsStringLocation*/true, 5463 getSpecifierRange(startSpecifier, specifierLen), 5464 FixItHint::CreateRemoval( 5465 getSpecifierRange(ignoredFlag.getPosition(), 1))); 5466 } 5467 5468 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5469 // bool IsStringLocation, Range StringRange, 5470 // ArrayRef<FixItHint> Fixit = None); 5471 5472 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 5473 unsigned flagLen) { 5474 // Warn about an empty flag. 5475 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 5476 getLocationOfByte(startFlag), 5477 /*IsStringLocation*/true, 5478 getSpecifierRange(startFlag, flagLen)); 5479 } 5480 5481 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 5482 unsigned flagLen) { 5483 // Warn about an invalid flag. 5484 auto Range = getSpecifierRange(startFlag, flagLen); 5485 StringRef flag(startFlag, flagLen); 5486 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 5487 getLocationOfByte(startFlag), 5488 /*IsStringLocation*/true, 5489 Range, FixItHint::CreateRemoval(Range)); 5490 } 5491 5492 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 5493 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 5494 // Warn about using '[...]' without a '@' conversion. 5495 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 5496 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 5497 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 5498 getLocationOfByte(conversionPosition), 5499 /*IsStringLocation*/true, 5500 Range, FixItHint::CreateRemoval(Range)); 5501 } 5502 5503 // Determines if the specified is a C++ class or struct containing 5504 // a member with the specified name and kind (e.g. a CXXMethodDecl named 5505 // "c_str()"). 5506 template<typename MemberKind> 5507 static llvm::SmallPtrSet<MemberKind*, 1> 5508 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 5509 const RecordType *RT = Ty->getAs<RecordType>(); 5510 llvm::SmallPtrSet<MemberKind*, 1> Results; 5511 5512 if (!RT) 5513 return Results; 5514 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 5515 if (!RD || !RD->getDefinition()) 5516 return Results; 5517 5518 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 5519 Sema::LookupMemberName); 5520 R.suppressDiagnostics(); 5521 5522 // We just need to include all members of the right kind turned up by the 5523 // filter, at this point. 5524 if (S.LookupQualifiedName(R, RT->getDecl())) 5525 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 5526 NamedDecl *decl = (*I)->getUnderlyingDecl(); 5527 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 5528 Results.insert(FK); 5529 } 5530 return Results; 5531 } 5532 5533 /// Check if we could call '.c_str()' on an object. 5534 /// 5535 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 5536 /// allow the call, or if it would be ambiguous). 5537 bool Sema::hasCStrMethod(const Expr *E) { 5538 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5539 MethodSet Results = 5540 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 5541 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5542 MI != ME; ++MI) 5543 if ((*MI)->getMinRequiredArguments() == 0) 5544 return true; 5545 return false; 5546 } 5547 5548 // Check if a (w)string was passed when a (w)char* was needed, and offer a 5549 // better diagnostic if so. AT is assumed to be valid. 5550 // Returns true when a c_str() conversion method is found. 5551 bool CheckPrintfHandler::checkForCStrMembers( 5552 const analyze_printf::ArgType &AT, const Expr *E) { 5553 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5554 5555 MethodSet Results = 5556 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 5557 5558 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5559 MI != ME; ++MI) { 5560 const CXXMethodDecl *Method = *MI; 5561 if (Method->getMinRequiredArguments() == 0 && 5562 AT.matchesType(S.Context, Method->getReturnType())) { 5563 // FIXME: Suggest parens if the expression needs them. 5564 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 5565 S.Diag(E->getLocStart(), diag::note_printf_c_str) 5566 << "c_str()" 5567 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 5568 return true; 5569 } 5570 } 5571 5572 return false; 5573 } 5574 5575 bool 5576 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 5577 &FS, 5578 const char *startSpecifier, 5579 unsigned specifierLen) { 5580 using namespace analyze_format_string; 5581 using namespace analyze_printf; 5582 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 5583 5584 if (FS.consumesDataArgument()) { 5585 if (atFirstArg) { 5586 atFirstArg = false; 5587 usesPositionalArgs = FS.usesPositionalArg(); 5588 } 5589 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5590 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5591 startSpecifier, specifierLen); 5592 return false; 5593 } 5594 } 5595 5596 // First check if the field width, precision, and conversion specifier 5597 // have matching data arguments. 5598 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 5599 startSpecifier, specifierLen)) { 5600 return false; 5601 } 5602 5603 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 5604 startSpecifier, specifierLen)) { 5605 return false; 5606 } 5607 5608 if (!CS.consumesDataArgument()) { 5609 // FIXME: Technically specifying a precision or field width here 5610 // makes no sense. Worth issuing a warning at some point. 5611 return true; 5612 } 5613 5614 // Consume the argument. 5615 unsigned argIndex = FS.getArgIndex(); 5616 if (argIndex < NumDataArgs) { 5617 // The check to see if the argIndex is valid will come later. 5618 // We set the bit here because we may exit early from this 5619 // function if we encounter some other error. 5620 CoveredArgs.set(argIndex); 5621 } 5622 5623 // FreeBSD kernel extensions. 5624 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 5625 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 5626 // We need at least two arguments. 5627 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 5628 return false; 5629 5630 // Claim the second argument. 5631 CoveredArgs.set(argIndex + 1); 5632 5633 // Type check the first argument (int for %b, pointer for %D) 5634 const Expr *Ex = getDataArg(argIndex); 5635 const analyze_printf::ArgType &AT = 5636 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 5637 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 5638 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 5639 EmitFormatDiagnostic( 5640 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5641 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 5642 << false << Ex->getSourceRange(), 5643 Ex->getLocStart(), /*IsStringLocation*/false, 5644 getSpecifierRange(startSpecifier, specifierLen)); 5645 5646 // Type check the second argument (char * for both %b and %D) 5647 Ex = getDataArg(argIndex + 1); 5648 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 5649 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 5650 EmitFormatDiagnostic( 5651 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5652 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 5653 << false << Ex->getSourceRange(), 5654 Ex->getLocStart(), /*IsStringLocation*/false, 5655 getSpecifierRange(startSpecifier, specifierLen)); 5656 5657 return true; 5658 } 5659 5660 // Check for using an Objective-C specific conversion specifier 5661 // in a non-ObjC literal. 5662 if (!allowsObjCArg() && CS.isObjCArg()) { 5663 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5664 specifierLen); 5665 } 5666 5667 // %P can only be used with os_log. 5668 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 5669 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5670 specifierLen); 5671 } 5672 5673 // %n is not allowed with os_log. 5674 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 5675 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 5676 getLocationOfByte(CS.getStart()), 5677 /*IsStringLocation*/ false, 5678 getSpecifierRange(startSpecifier, specifierLen)); 5679 5680 return true; 5681 } 5682 5683 // Only scalars are allowed for os_trace. 5684 if (FSType == Sema::FST_OSTrace && 5685 (CS.getKind() == ConversionSpecifier::PArg || 5686 CS.getKind() == ConversionSpecifier::sArg || 5687 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 5688 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5689 specifierLen); 5690 } 5691 5692 // Check for use of public/private annotation outside of os_log(). 5693 if (FSType != Sema::FST_OSLog) { 5694 if (FS.isPublic().isSet()) { 5695 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 5696 << "public", 5697 getLocationOfByte(FS.isPublic().getPosition()), 5698 /*IsStringLocation*/ false, 5699 getSpecifierRange(startSpecifier, specifierLen)); 5700 } 5701 if (FS.isPrivate().isSet()) { 5702 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 5703 << "private", 5704 getLocationOfByte(FS.isPrivate().getPosition()), 5705 /*IsStringLocation*/ false, 5706 getSpecifierRange(startSpecifier, specifierLen)); 5707 } 5708 } 5709 5710 // Check for invalid use of field width 5711 if (!FS.hasValidFieldWidth()) { 5712 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 5713 startSpecifier, specifierLen); 5714 } 5715 5716 // Check for invalid use of precision 5717 if (!FS.hasValidPrecision()) { 5718 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 5719 startSpecifier, specifierLen); 5720 } 5721 5722 // Precision is mandatory for %P specifier. 5723 if (CS.getKind() == ConversionSpecifier::PArg && 5724 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 5725 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 5726 getLocationOfByte(startSpecifier), 5727 /*IsStringLocation*/ false, 5728 getSpecifierRange(startSpecifier, specifierLen)); 5729 } 5730 5731 // Check each flag does not conflict with any other component. 5732 if (!FS.hasValidThousandsGroupingPrefix()) 5733 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 5734 if (!FS.hasValidLeadingZeros()) 5735 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 5736 if (!FS.hasValidPlusPrefix()) 5737 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 5738 if (!FS.hasValidSpacePrefix()) 5739 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 5740 if (!FS.hasValidAlternativeForm()) 5741 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 5742 if (!FS.hasValidLeftJustified()) 5743 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 5744 5745 // Check that flags are not ignored by another flag 5746 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 5747 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 5748 startSpecifier, specifierLen); 5749 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 5750 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 5751 startSpecifier, specifierLen); 5752 5753 // Check the length modifier is valid with the given conversion specifier. 5754 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 5755 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5756 diag::warn_format_nonsensical_length); 5757 else if (!FS.hasStandardLengthModifier()) 5758 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 5759 else if (!FS.hasStandardLengthConversionCombination()) 5760 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5761 diag::warn_format_non_standard_conversion_spec); 5762 5763 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 5764 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 5765 5766 // The remaining checks depend on the data arguments. 5767 if (HasVAListArg) 5768 return true; 5769 5770 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 5771 return false; 5772 5773 const Expr *Arg = getDataArg(argIndex); 5774 if (!Arg) 5775 return true; 5776 5777 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 5778 } 5779 5780 static bool requiresParensToAddCast(const Expr *E) { 5781 // FIXME: We should have a general way to reason about operator 5782 // precedence and whether parens are actually needed here. 5783 // Take care of a few common cases where they aren't. 5784 const Expr *Inside = E->IgnoreImpCasts(); 5785 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 5786 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 5787 5788 switch (Inside->getStmtClass()) { 5789 case Stmt::ArraySubscriptExprClass: 5790 case Stmt::CallExprClass: 5791 case Stmt::CharacterLiteralClass: 5792 case Stmt::CXXBoolLiteralExprClass: 5793 case Stmt::DeclRefExprClass: 5794 case Stmt::FloatingLiteralClass: 5795 case Stmt::IntegerLiteralClass: 5796 case Stmt::MemberExprClass: 5797 case Stmt::ObjCArrayLiteralClass: 5798 case Stmt::ObjCBoolLiteralExprClass: 5799 case Stmt::ObjCBoxedExprClass: 5800 case Stmt::ObjCDictionaryLiteralClass: 5801 case Stmt::ObjCEncodeExprClass: 5802 case Stmt::ObjCIvarRefExprClass: 5803 case Stmt::ObjCMessageExprClass: 5804 case Stmt::ObjCPropertyRefExprClass: 5805 case Stmt::ObjCStringLiteralClass: 5806 case Stmt::ObjCSubscriptRefExprClass: 5807 case Stmt::ParenExprClass: 5808 case Stmt::StringLiteralClass: 5809 case Stmt::UnaryOperatorClass: 5810 return false; 5811 default: 5812 return true; 5813 } 5814 } 5815 5816 static std::pair<QualType, StringRef> 5817 shouldNotPrintDirectly(const ASTContext &Context, 5818 QualType IntendedTy, 5819 const Expr *E) { 5820 // Use a 'while' to peel off layers of typedefs. 5821 QualType TyTy = IntendedTy; 5822 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 5823 StringRef Name = UserTy->getDecl()->getName(); 5824 QualType CastTy = llvm::StringSwitch<QualType>(Name) 5825 .Case("NSInteger", Context.LongTy) 5826 .Case("NSUInteger", Context.UnsignedLongTy) 5827 .Case("SInt32", Context.IntTy) 5828 .Case("UInt32", Context.UnsignedIntTy) 5829 .Default(QualType()); 5830 5831 if (!CastTy.isNull()) 5832 return std::make_pair(CastTy, Name); 5833 5834 TyTy = UserTy->desugar(); 5835 } 5836 5837 // Strip parens if necessary. 5838 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 5839 return shouldNotPrintDirectly(Context, 5840 PE->getSubExpr()->getType(), 5841 PE->getSubExpr()); 5842 5843 // If this is a conditional expression, then its result type is constructed 5844 // via usual arithmetic conversions and thus there might be no necessary 5845 // typedef sugar there. Recurse to operands to check for NSInteger & 5846 // Co. usage condition. 5847 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 5848 QualType TrueTy, FalseTy; 5849 StringRef TrueName, FalseName; 5850 5851 std::tie(TrueTy, TrueName) = 5852 shouldNotPrintDirectly(Context, 5853 CO->getTrueExpr()->getType(), 5854 CO->getTrueExpr()); 5855 std::tie(FalseTy, FalseName) = 5856 shouldNotPrintDirectly(Context, 5857 CO->getFalseExpr()->getType(), 5858 CO->getFalseExpr()); 5859 5860 if (TrueTy == FalseTy) 5861 return std::make_pair(TrueTy, TrueName); 5862 else if (TrueTy.isNull()) 5863 return std::make_pair(FalseTy, FalseName); 5864 else if (FalseTy.isNull()) 5865 return std::make_pair(TrueTy, TrueName); 5866 } 5867 5868 return std::make_pair(QualType(), StringRef()); 5869 } 5870 5871 bool 5872 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5873 const char *StartSpecifier, 5874 unsigned SpecifierLen, 5875 const Expr *E) { 5876 using namespace analyze_format_string; 5877 using namespace analyze_printf; 5878 // Now type check the data expression that matches the 5879 // format specifier. 5880 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 5881 if (!AT.isValid()) 5882 return true; 5883 5884 QualType ExprTy = E->getType(); 5885 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 5886 ExprTy = TET->getUnderlyingExpr()->getType(); 5887 } 5888 5889 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 5890 5891 if (match == analyze_printf::ArgType::Match) { 5892 return true; 5893 } 5894 5895 // Look through argument promotions for our error message's reported type. 5896 // This includes the integral and floating promotions, but excludes array 5897 // and function pointer decay; seeing that an argument intended to be a 5898 // string has type 'char [6]' is probably more confusing than 'char *'. 5899 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5900 if (ICE->getCastKind() == CK_IntegralCast || 5901 ICE->getCastKind() == CK_FloatingCast) { 5902 E = ICE->getSubExpr(); 5903 ExprTy = E->getType(); 5904 5905 // Check if we didn't match because of an implicit cast from a 'char' 5906 // or 'short' to an 'int'. This is done because printf is a varargs 5907 // function. 5908 if (ICE->getType() == S.Context.IntTy || 5909 ICE->getType() == S.Context.UnsignedIntTy) { 5910 // All further checking is done on the subexpression. 5911 if (AT.matchesType(S.Context, ExprTy)) 5912 return true; 5913 } 5914 } 5915 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 5916 // Special case for 'a', which has type 'int' in C. 5917 // Note, however, that we do /not/ want to treat multibyte constants like 5918 // 'MooV' as characters! This form is deprecated but still exists. 5919 if (ExprTy == S.Context.IntTy) 5920 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 5921 ExprTy = S.Context.CharTy; 5922 } 5923 5924 // Look through enums to their underlying type. 5925 bool IsEnum = false; 5926 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 5927 ExprTy = EnumTy->getDecl()->getIntegerType(); 5928 IsEnum = true; 5929 } 5930 5931 // %C in an Objective-C context prints a unichar, not a wchar_t. 5932 // If the argument is an integer of some kind, believe the %C and suggest 5933 // a cast instead of changing the conversion specifier. 5934 QualType IntendedTy = ExprTy; 5935 if (isObjCContext() && 5936 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 5937 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 5938 !ExprTy->isCharType()) { 5939 // 'unichar' is defined as a typedef of unsigned short, but we should 5940 // prefer using the typedef if it is visible. 5941 IntendedTy = S.Context.UnsignedShortTy; 5942 5943 // While we are here, check if the value is an IntegerLiteral that happens 5944 // to be within the valid range. 5945 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 5946 const llvm::APInt &V = IL->getValue(); 5947 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 5948 return true; 5949 } 5950 5951 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 5952 Sema::LookupOrdinaryName); 5953 if (S.LookupName(Result, S.getCurScope())) { 5954 NamedDecl *ND = Result.getFoundDecl(); 5955 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 5956 if (TD->getUnderlyingType() == IntendedTy) 5957 IntendedTy = S.Context.getTypedefType(TD); 5958 } 5959 } 5960 } 5961 5962 // Special-case some of Darwin's platform-independence types by suggesting 5963 // casts to primitive types that are known to be large enough. 5964 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 5965 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 5966 QualType CastTy; 5967 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 5968 if (!CastTy.isNull()) { 5969 IntendedTy = CastTy; 5970 ShouldNotPrintDirectly = true; 5971 } 5972 } 5973 5974 // We may be able to offer a FixItHint if it is a supported type. 5975 PrintfSpecifier fixedFS = FS; 5976 bool success = 5977 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 5978 5979 if (success) { 5980 // Get the fix string from the fixed format specifier 5981 SmallString<16> buf; 5982 llvm::raw_svector_ostream os(buf); 5983 fixedFS.toString(os); 5984 5985 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 5986 5987 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 5988 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 5989 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 5990 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 5991 } 5992 // In this case, the specifier is wrong and should be changed to match 5993 // the argument. 5994 EmitFormatDiagnostic(S.PDiag(diag) 5995 << AT.getRepresentativeTypeName(S.Context) 5996 << IntendedTy << IsEnum << E->getSourceRange(), 5997 E->getLocStart(), 5998 /*IsStringLocation*/ false, SpecRange, 5999 FixItHint::CreateReplacement(SpecRange, os.str())); 6000 } else { 6001 // The canonical type for formatting this value is different from the 6002 // actual type of the expression. (This occurs, for example, with Darwin's 6003 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 6004 // should be printed as 'long' for 64-bit compatibility.) 6005 // Rather than emitting a normal format/argument mismatch, we want to 6006 // add a cast to the recommended type (and correct the format string 6007 // if necessary). 6008 SmallString<16> CastBuf; 6009 llvm::raw_svector_ostream CastFix(CastBuf); 6010 CastFix << "("; 6011 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 6012 CastFix << ")"; 6013 6014 SmallVector<FixItHint,4> Hints; 6015 if (!AT.matchesType(S.Context, IntendedTy)) 6016 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 6017 6018 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 6019 // If there's already a cast present, just replace it. 6020 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 6021 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 6022 6023 } else if (!requiresParensToAddCast(E)) { 6024 // If the expression has high enough precedence, 6025 // just write the C-style cast. 6026 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6027 CastFix.str())); 6028 } else { 6029 // Otherwise, add parens around the expression as well as the cast. 6030 CastFix << "("; 6031 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6032 CastFix.str())); 6033 6034 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6035 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6036 } 6037 6038 if (ShouldNotPrintDirectly) { 6039 // The expression has a type that should not be printed directly. 6040 // We extract the name from the typedef because we don't want to show 6041 // the underlying type in the diagnostic. 6042 StringRef Name; 6043 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6044 Name = TypedefTy->getDecl()->getName(); 6045 else 6046 Name = CastTyName; 6047 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6048 << Name << IntendedTy << IsEnum 6049 << E->getSourceRange(), 6050 E->getLocStart(), /*IsStringLocation=*/false, 6051 SpecRange, Hints); 6052 } else { 6053 // In this case, the expression could be printed using a different 6054 // specifier, but we've decided that the specifier is probably correct 6055 // and we should cast instead. Just use the normal warning message. 6056 EmitFormatDiagnostic( 6057 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6058 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6059 << E->getSourceRange(), 6060 E->getLocStart(), /*IsStringLocation*/false, 6061 SpecRange, Hints); 6062 } 6063 } 6064 } else { 6065 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6066 SpecifierLen); 6067 // Since the warning for passing non-POD types to variadic functions 6068 // was deferred until now, we emit a warning for non-POD 6069 // arguments here. 6070 switch (S.isValidVarArgType(ExprTy)) { 6071 case Sema::VAK_Valid: 6072 case Sema::VAK_ValidInCXX11: { 6073 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6074 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6075 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6076 } 6077 6078 EmitFormatDiagnostic( 6079 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6080 << IsEnum << CSR << E->getSourceRange(), 6081 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6082 break; 6083 } 6084 case Sema::VAK_Undefined: 6085 case Sema::VAK_MSVCUndefined: 6086 EmitFormatDiagnostic( 6087 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6088 << S.getLangOpts().CPlusPlus11 6089 << ExprTy 6090 << CallType 6091 << AT.getRepresentativeTypeName(S.Context) 6092 << CSR 6093 << E->getSourceRange(), 6094 E->getLocStart(), /*IsStringLocation*/false, CSR); 6095 checkForCStrMembers(AT, E); 6096 break; 6097 6098 case Sema::VAK_Invalid: 6099 if (ExprTy->isObjCObjectType()) 6100 EmitFormatDiagnostic( 6101 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 6102 << S.getLangOpts().CPlusPlus11 6103 << ExprTy 6104 << CallType 6105 << AT.getRepresentativeTypeName(S.Context) 6106 << CSR 6107 << E->getSourceRange(), 6108 E->getLocStart(), /*IsStringLocation*/false, CSR); 6109 else 6110 // FIXME: If this is an initializer list, suggest removing the braces 6111 // or inserting a cast to the target type. 6112 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 6113 << isa<InitListExpr>(E) << ExprTy << CallType 6114 << AT.getRepresentativeTypeName(S.Context) 6115 << E->getSourceRange(); 6116 break; 6117 } 6118 6119 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 6120 "format string specifier index out of range"); 6121 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 6122 } 6123 6124 return true; 6125 } 6126 6127 //===--- CHECK: Scanf format string checking ------------------------------===// 6128 6129 namespace { 6130 class CheckScanfHandler : public CheckFormatHandler { 6131 public: 6132 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 6133 const Expr *origFormatExpr, Sema::FormatStringType type, 6134 unsigned firstDataArg, unsigned numDataArgs, 6135 const char *beg, bool hasVAListArg, 6136 ArrayRef<const Expr *> Args, unsigned formatIdx, 6137 bool inFunctionCall, Sema::VariadicCallType CallType, 6138 llvm::SmallBitVector &CheckedVarArgs, 6139 UncoveredArgHandler &UncoveredArg) 6140 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6141 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6142 inFunctionCall, CallType, CheckedVarArgs, 6143 UncoveredArg) {} 6144 6145 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 6146 const char *startSpecifier, 6147 unsigned specifierLen) override; 6148 6149 bool HandleInvalidScanfConversionSpecifier( 6150 const analyze_scanf::ScanfSpecifier &FS, 6151 const char *startSpecifier, 6152 unsigned specifierLen) override; 6153 6154 void HandleIncompleteScanList(const char *start, const char *end) override; 6155 }; 6156 } // end anonymous namespace 6157 6158 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 6159 const char *end) { 6160 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 6161 getLocationOfByte(end), /*IsStringLocation*/true, 6162 getSpecifierRange(start, end - start)); 6163 } 6164 6165 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 6166 const analyze_scanf::ScanfSpecifier &FS, 6167 const char *startSpecifier, 6168 unsigned specifierLen) { 6169 6170 const analyze_scanf::ScanfConversionSpecifier &CS = 6171 FS.getConversionSpecifier(); 6172 6173 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6174 getLocationOfByte(CS.getStart()), 6175 startSpecifier, specifierLen, 6176 CS.getStart(), CS.getLength()); 6177 } 6178 6179 bool CheckScanfHandler::HandleScanfSpecifier( 6180 const analyze_scanf::ScanfSpecifier &FS, 6181 const char *startSpecifier, 6182 unsigned specifierLen) { 6183 using namespace analyze_scanf; 6184 using namespace analyze_format_string; 6185 6186 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 6187 6188 // Handle case where '%' and '*' don't consume an argument. These shouldn't 6189 // be used to decide if we are using positional arguments consistently. 6190 if (FS.consumesDataArgument()) { 6191 if (atFirstArg) { 6192 atFirstArg = false; 6193 usesPositionalArgs = FS.usesPositionalArg(); 6194 } 6195 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6196 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6197 startSpecifier, specifierLen); 6198 return false; 6199 } 6200 } 6201 6202 // Check if the field with is non-zero. 6203 const OptionalAmount &Amt = FS.getFieldWidth(); 6204 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 6205 if (Amt.getConstantAmount() == 0) { 6206 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 6207 Amt.getConstantLength()); 6208 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 6209 getLocationOfByte(Amt.getStart()), 6210 /*IsStringLocation*/true, R, 6211 FixItHint::CreateRemoval(R)); 6212 } 6213 } 6214 6215 if (!FS.consumesDataArgument()) { 6216 // FIXME: Technically specifying a precision or field width here 6217 // makes no sense. Worth issuing a warning at some point. 6218 return true; 6219 } 6220 6221 // Consume the argument. 6222 unsigned argIndex = FS.getArgIndex(); 6223 if (argIndex < NumDataArgs) { 6224 // The check to see if the argIndex is valid will come later. 6225 // We set the bit here because we may exit early from this 6226 // function if we encounter some other error. 6227 CoveredArgs.set(argIndex); 6228 } 6229 6230 // Check the length modifier is valid with the given conversion specifier. 6231 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6232 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6233 diag::warn_format_nonsensical_length); 6234 else if (!FS.hasStandardLengthModifier()) 6235 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6236 else if (!FS.hasStandardLengthConversionCombination()) 6237 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6238 diag::warn_format_non_standard_conversion_spec); 6239 6240 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6241 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6242 6243 // The remaining checks depend on the data arguments. 6244 if (HasVAListArg) 6245 return true; 6246 6247 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6248 return false; 6249 6250 // Check that the argument type matches the format specifier. 6251 const Expr *Ex = getDataArg(argIndex); 6252 if (!Ex) 6253 return true; 6254 6255 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 6256 6257 if (!AT.isValid()) { 6258 return true; 6259 } 6260 6261 analyze_format_string::ArgType::MatchKind match = 6262 AT.matchesType(S.Context, Ex->getType()); 6263 if (match == analyze_format_string::ArgType::Match) { 6264 return true; 6265 } 6266 6267 ScanfSpecifier fixedFS = FS; 6268 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 6269 S.getLangOpts(), S.Context); 6270 6271 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6272 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6273 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6274 } 6275 6276 if (success) { 6277 // Get the fix string from the fixed format specifier. 6278 SmallString<128> buf; 6279 llvm::raw_svector_ostream os(buf); 6280 fixedFS.toString(os); 6281 6282 EmitFormatDiagnostic( 6283 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 6284 << Ex->getType() << false << Ex->getSourceRange(), 6285 Ex->getLocStart(), 6286 /*IsStringLocation*/ false, 6287 getSpecifierRange(startSpecifier, specifierLen), 6288 FixItHint::CreateReplacement( 6289 getSpecifierRange(startSpecifier, specifierLen), os.str())); 6290 } else { 6291 EmitFormatDiagnostic(S.PDiag(diag) 6292 << AT.getRepresentativeTypeName(S.Context) 6293 << Ex->getType() << false << Ex->getSourceRange(), 6294 Ex->getLocStart(), 6295 /*IsStringLocation*/ false, 6296 getSpecifierRange(startSpecifier, specifierLen)); 6297 } 6298 6299 return true; 6300 } 6301 6302 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6303 const Expr *OrigFormatExpr, 6304 ArrayRef<const Expr *> Args, 6305 bool HasVAListArg, unsigned format_idx, 6306 unsigned firstDataArg, 6307 Sema::FormatStringType Type, 6308 bool inFunctionCall, 6309 Sema::VariadicCallType CallType, 6310 llvm::SmallBitVector &CheckedVarArgs, 6311 UncoveredArgHandler &UncoveredArg) { 6312 // CHECK: is the format string a wide literal? 6313 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 6314 CheckFormatHandler::EmitFormatDiagnostic( 6315 S, inFunctionCall, Args[format_idx], 6316 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 6317 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6318 return; 6319 } 6320 6321 // Str - The format string. NOTE: this is NOT null-terminated! 6322 StringRef StrRef = FExpr->getString(); 6323 const char *Str = StrRef.data(); 6324 // Account for cases where the string literal is truncated in a declaration. 6325 const ConstantArrayType *T = 6326 S.Context.getAsConstantArrayType(FExpr->getType()); 6327 assert(T && "String literal not of constant array type!"); 6328 size_t TypeSize = T->getSize().getZExtValue(); 6329 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6330 const unsigned numDataArgs = Args.size() - firstDataArg; 6331 6332 // Emit a warning if the string literal is truncated and does not contain an 6333 // embedded null character. 6334 if (TypeSize <= StrRef.size() && 6335 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 6336 CheckFormatHandler::EmitFormatDiagnostic( 6337 S, inFunctionCall, Args[format_idx], 6338 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 6339 FExpr->getLocStart(), 6340 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 6341 return; 6342 } 6343 6344 // CHECK: empty format string? 6345 if (StrLen == 0 && numDataArgs > 0) { 6346 CheckFormatHandler::EmitFormatDiagnostic( 6347 S, inFunctionCall, Args[format_idx], 6348 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 6349 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6350 return; 6351 } 6352 6353 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 6354 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 6355 Type == Sema::FST_OSTrace) { 6356 CheckPrintfHandler H( 6357 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 6358 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 6359 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 6360 CheckedVarArgs, UncoveredArg); 6361 6362 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 6363 S.getLangOpts(), 6364 S.Context.getTargetInfo(), 6365 Type == Sema::FST_FreeBSDKPrintf)) 6366 H.DoneProcessing(); 6367 } else if (Type == Sema::FST_Scanf) { 6368 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 6369 numDataArgs, Str, HasVAListArg, Args, format_idx, 6370 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 6371 6372 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 6373 S.getLangOpts(), 6374 S.Context.getTargetInfo())) 6375 H.DoneProcessing(); 6376 } // TODO: handle other formats 6377 } 6378 6379 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 6380 // Str - The format string. NOTE: this is NOT null-terminated! 6381 StringRef StrRef = FExpr->getString(); 6382 const char *Str = StrRef.data(); 6383 // Account for cases where the string literal is truncated in a declaration. 6384 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 6385 assert(T && "String literal not of constant array type!"); 6386 size_t TypeSize = T->getSize().getZExtValue(); 6387 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6388 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 6389 getLangOpts(), 6390 Context.getTargetInfo()); 6391 } 6392 6393 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 6394 6395 // Returns the related absolute value function that is larger, of 0 if one 6396 // does not exist. 6397 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 6398 switch (AbsFunction) { 6399 default: 6400 return 0; 6401 6402 case Builtin::BI__builtin_abs: 6403 return Builtin::BI__builtin_labs; 6404 case Builtin::BI__builtin_labs: 6405 return Builtin::BI__builtin_llabs; 6406 case Builtin::BI__builtin_llabs: 6407 return 0; 6408 6409 case Builtin::BI__builtin_fabsf: 6410 return Builtin::BI__builtin_fabs; 6411 case Builtin::BI__builtin_fabs: 6412 return Builtin::BI__builtin_fabsl; 6413 case Builtin::BI__builtin_fabsl: 6414 return 0; 6415 6416 case Builtin::BI__builtin_cabsf: 6417 return Builtin::BI__builtin_cabs; 6418 case Builtin::BI__builtin_cabs: 6419 return Builtin::BI__builtin_cabsl; 6420 case Builtin::BI__builtin_cabsl: 6421 return 0; 6422 6423 case Builtin::BIabs: 6424 return Builtin::BIlabs; 6425 case Builtin::BIlabs: 6426 return Builtin::BIllabs; 6427 case Builtin::BIllabs: 6428 return 0; 6429 6430 case Builtin::BIfabsf: 6431 return Builtin::BIfabs; 6432 case Builtin::BIfabs: 6433 return Builtin::BIfabsl; 6434 case Builtin::BIfabsl: 6435 return 0; 6436 6437 case Builtin::BIcabsf: 6438 return Builtin::BIcabs; 6439 case Builtin::BIcabs: 6440 return Builtin::BIcabsl; 6441 case Builtin::BIcabsl: 6442 return 0; 6443 } 6444 } 6445 6446 // Returns the argument type of the absolute value function. 6447 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 6448 unsigned AbsType) { 6449 if (AbsType == 0) 6450 return QualType(); 6451 6452 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 6453 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 6454 if (Error != ASTContext::GE_None) 6455 return QualType(); 6456 6457 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 6458 if (!FT) 6459 return QualType(); 6460 6461 if (FT->getNumParams() != 1) 6462 return QualType(); 6463 6464 return FT->getParamType(0); 6465 } 6466 6467 // Returns the best absolute value function, or zero, based on type and 6468 // current absolute value function. 6469 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 6470 unsigned AbsFunctionKind) { 6471 unsigned BestKind = 0; 6472 uint64_t ArgSize = Context.getTypeSize(ArgType); 6473 for (unsigned Kind = AbsFunctionKind; Kind != 0; 6474 Kind = getLargerAbsoluteValueFunction(Kind)) { 6475 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 6476 if (Context.getTypeSize(ParamType) >= ArgSize) { 6477 if (BestKind == 0) 6478 BestKind = Kind; 6479 else if (Context.hasSameType(ParamType, ArgType)) { 6480 BestKind = Kind; 6481 break; 6482 } 6483 } 6484 } 6485 return BestKind; 6486 } 6487 6488 enum AbsoluteValueKind { 6489 AVK_Integer, 6490 AVK_Floating, 6491 AVK_Complex 6492 }; 6493 6494 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 6495 if (T->isIntegralOrEnumerationType()) 6496 return AVK_Integer; 6497 if (T->isRealFloatingType()) 6498 return AVK_Floating; 6499 if (T->isAnyComplexType()) 6500 return AVK_Complex; 6501 6502 llvm_unreachable("Type not integer, floating, or complex"); 6503 } 6504 6505 // Changes the absolute value function to a different type. Preserves whether 6506 // the function is a builtin. 6507 static unsigned changeAbsFunction(unsigned AbsKind, 6508 AbsoluteValueKind ValueKind) { 6509 switch (ValueKind) { 6510 case AVK_Integer: 6511 switch (AbsKind) { 6512 default: 6513 return 0; 6514 case Builtin::BI__builtin_fabsf: 6515 case Builtin::BI__builtin_fabs: 6516 case Builtin::BI__builtin_fabsl: 6517 case Builtin::BI__builtin_cabsf: 6518 case Builtin::BI__builtin_cabs: 6519 case Builtin::BI__builtin_cabsl: 6520 return Builtin::BI__builtin_abs; 6521 case Builtin::BIfabsf: 6522 case Builtin::BIfabs: 6523 case Builtin::BIfabsl: 6524 case Builtin::BIcabsf: 6525 case Builtin::BIcabs: 6526 case Builtin::BIcabsl: 6527 return Builtin::BIabs; 6528 } 6529 case AVK_Floating: 6530 switch (AbsKind) { 6531 default: 6532 return 0; 6533 case Builtin::BI__builtin_abs: 6534 case Builtin::BI__builtin_labs: 6535 case Builtin::BI__builtin_llabs: 6536 case Builtin::BI__builtin_cabsf: 6537 case Builtin::BI__builtin_cabs: 6538 case Builtin::BI__builtin_cabsl: 6539 return Builtin::BI__builtin_fabsf; 6540 case Builtin::BIabs: 6541 case Builtin::BIlabs: 6542 case Builtin::BIllabs: 6543 case Builtin::BIcabsf: 6544 case Builtin::BIcabs: 6545 case Builtin::BIcabsl: 6546 return Builtin::BIfabsf; 6547 } 6548 case AVK_Complex: 6549 switch (AbsKind) { 6550 default: 6551 return 0; 6552 case Builtin::BI__builtin_abs: 6553 case Builtin::BI__builtin_labs: 6554 case Builtin::BI__builtin_llabs: 6555 case Builtin::BI__builtin_fabsf: 6556 case Builtin::BI__builtin_fabs: 6557 case Builtin::BI__builtin_fabsl: 6558 return Builtin::BI__builtin_cabsf; 6559 case Builtin::BIabs: 6560 case Builtin::BIlabs: 6561 case Builtin::BIllabs: 6562 case Builtin::BIfabsf: 6563 case Builtin::BIfabs: 6564 case Builtin::BIfabsl: 6565 return Builtin::BIcabsf; 6566 } 6567 } 6568 llvm_unreachable("Unable to convert function"); 6569 } 6570 6571 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 6572 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 6573 if (!FnInfo) 6574 return 0; 6575 6576 switch (FDecl->getBuiltinID()) { 6577 default: 6578 return 0; 6579 case Builtin::BI__builtin_abs: 6580 case Builtin::BI__builtin_fabs: 6581 case Builtin::BI__builtin_fabsf: 6582 case Builtin::BI__builtin_fabsl: 6583 case Builtin::BI__builtin_labs: 6584 case Builtin::BI__builtin_llabs: 6585 case Builtin::BI__builtin_cabs: 6586 case Builtin::BI__builtin_cabsf: 6587 case Builtin::BI__builtin_cabsl: 6588 case Builtin::BIabs: 6589 case Builtin::BIlabs: 6590 case Builtin::BIllabs: 6591 case Builtin::BIfabs: 6592 case Builtin::BIfabsf: 6593 case Builtin::BIfabsl: 6594 case Builtin::BIcabs: 6595 case Builtin::BIcabsf: 6596 case Builtin::BIcabsl: 6597 return FDecl->getBuiltinID(); 6598 } 6599 llvm_unreachable("Unknown Builtin type"); 6600 } 6601 6602 // If the replacement is valid, emit a note with replacement function. 6603 // Additionally, suggest including the proper header if not already included. 6604 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 6605 unsigned AbsKind, QualType ArgType) { 6606 bool EmitHeaderHint = true; 6607 const char *HeaderName = nullptr; 6608 const char *FunctionName = nullptr; 6609 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 6610 FunctionName = "std::abs"; 6611 if (ArgType->isIntegralOrEnumerationType()) { 6612 HeaderName = "cstdlib"; 6613 } else if (ArgType->isRealFloatingType()) { 6614 HeaderName = "cmath"; 6615 } else { 6616 llvm_unreachable("Invalid Type"); 6617 } 6618 6619 // Lookup all std::abs 6620 if (NamespaceDecl *Std = S.getStdNamespace()) { 6621 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 6622 R.suppressDiagnostics(); 6623 S.LookupQualifiedName(R, Std); 6624 6625 for (const auto *I : R) { 6626 const FunctionDecl *FDecl = nullptr; 6627 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 6628 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 6629 } else { 6630 FDecl = dyn_cast<FunctionDecl>(I); 6631 } 6632 if (!FDecl) 6633 continue; 6634 6635 // Found std::abs(), check that they are the right ones. 6636 if (FDecl->getNumParams() != 1) 6637 continue; 6638 6639 // Check that the parameter type can handle the argument. 6640 QualType ParamType = FDecl->getParamDecl(0)->getType(); 6641 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 6642 S.Context.getTypeSize(ArgType) <= 6643 S.Context.getTypeSize(ParamType)) { 6644 // Found a function, don't need the header hint. 6645 EmitHeaderHint = false; 6646 break; 6647 } 6648 } 6649 } 6650 } else { 6651 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 6652 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 6653 6654 if (HeaderName) { 6655 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 6656 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 6657 R.suppressDiagnostics(); 6658 S.LookupName(R, S.getCurScope()); 6659 6660 if (R.isSingleResult()) { 6661 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 6662 if (FD && FD->getBuiltinID() == AbsKind) { 6663 EmitHeaderHint = false; 6664 } else { 6665 return; 6666 } 6667 } else if (!R.empty()) { 6668 return; 6669 } 6670 } 6671 } 6672 6673 S.Diag(Loc, diag::note_replace_abs_function) 6674 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 6675 6676 if (!HeaderName) 6677 return; 6678 6679 if (!EmitHeaderHint) 6680 return; 6681 6682 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 6683 << FunctionName; 6684 } 6685 6686 template <std::size_t StrLen> 6687 static bool IsStdFunction(const FunctionDecl *FDecl, 6688 const char (&Str)[StrLen]) { 6689 if (!FDecl) 6690 return false; 6691 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 6692 return false; 6693 if (!FDecl->isInStdNamespace()) 6694 return false; 6695 6696 return true; 6697 } 6698 6699 // Warn when using the wrong abs() function. 6700 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 6701 const FunctionDecl *FDecl) { 6702 if (Call->getNumArgs() != 1) 6703 return; 6704 6705 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 6706 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 6707 if (AbsKind == 0 && !IsStdAbs) 6708 return; 6709 6710 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 6711 QualType ParamType = Call->getArg(0)->getType(); 6712 6713 // Unsigned types cannot be negative. Suggest removing the absolute value 6714 // function call. 6715 if (ArgType->isUnsignedIntegerType()) { 6716 const char *FunctionName = 6717 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 6718 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 6719 Diag(Call->getExprLoc(), diag::note_remove_abs) 6720 << FunctionName 6721 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 6722 return; 6723 } 6724 6725 // Taking the absolute value of a pointer is very suspicious, they probably 6726 // wanted to index into an array, dereference a pointer, call a function, etc. 6727 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 6728 unsigned DiagType = 0; 6729 if (ArgType->isFunctionType()) 6730 DiagType = 1; 6731 else if (ArgType->isArrayType()) 6732 DiagType = 2; 6733 6734 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 6735 return; 6736 } 6737 6738 // std::abs has overloads which prevent most of the absolute value problems 6739 // from occurring. 6740 if (IsStdAbs) 6741 return; 6742 6743 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 6744 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 6745 6746 // The argument and parameter are the same kind. Check if they are the right 6747 // size. 6748 if (ArgValueKind == ParamValueKind) { 6749 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 6750 return; 6751 6752 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 6753 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 6754 << FDecl << ArgType << ParamType; 6755 6756 if (NewAbsKind == 0) 6757 return; 6758 6759 emitReplacement(*this, Call->getExprLoc(), 6760 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6761 return; 6762 } 6763 6764 // ArgValueKind != ParamValueKind 6765 // The wrong type of absolute value function was used. Attempt to find the 6766 // proper one. 6767 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 6768 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 6769 if (NewAbsKind == 0) 6770 return; 6771 6772 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 6773 << FDecl << ParamValueKind << ArgValueKind; 6774 6775 emitReplacement(*this, Call->getExprLoc(), 6776 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6777 } 6778 6779 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 6780 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 6781 const FunctionDecl *FDecl) { 6782 if (!Call || !FDecl) return; 6783 6784 // Ignore template specializations and macros. 6785 if (!ActiveTemplateInstantiations.empty()) return; 6786 if (Call->getExprLoc().isMacroID()) return; 6787 6788 // Only care about the one template argument, two function parameter std::max 6789 if (Call->getNumArgs() != 2) return; 6790 if (!IsStdFunction(FDecl, "max")) return; 6791 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 6792 if (!ArgList) return; 6793 if (ArgList->size() != 1) return; 6794 6795 // Check that template type argument is unsigned integer. 6796 const auto& TA = ArgList->get(0); 6797 if (TA.getKind() != TemplateArgument::Type) return; 6798 QualType ArgType = TA.getAsType(); 6799 if (!ArgType->isUnsignedIntegerType()) return; 6800 6801 // See if either argument is a literal zero. 6802 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 6803 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 6804 if (!MTE) return false; 6805 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 6806 if (!Num) return false; 6807 if (Num->getValue() != 0) return false; 6808 return true; 6809 }; 6810 6811 const Expr *FirstArg = Call->getArg(0); 6812 const Expr *SecondArg = Call->getArg(1); 6813 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 6814 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 6815 6816 // Only warn when exactly one argument is zero. 6817 if (IsFirstArgZero == IsSecondArgZero) return; 6818 6819 SourceRange FirstRange = FirstArg->getSourceRange(); 6820 SourceRange SecondRange = SecondArg->getSourceRange(); 6821 6822 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 6823 6824 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 6825 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 6826 6827 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 6828 SourceRange RemovalRange; 6829 if (IsFirstArgZero) { 6830 RemovalRange = SourceRange(FirstRange.getBegin(), 6831 SecondRange.getBegin().getLocWithOffset(-1)); 6832 } else { 6833 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 6834 SecondRange.getEnd()); 6835 } 6836 6837 Diag(Call->getExprLoc(), diag::note_remove_max_call) 6838 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 6839 << FixItHint::CreateRemoval(RemovalRange); 6840 } 6841 6842 //===--- CHECK: Standard memory functions ---------------------------------===// 6843 6844 /// \brief Takes the expression passed to the size_t parameter of functions 6845 /// such as memcmp, strncat, etc and warns if it's a comparison. 6846 /// 6847 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 6848 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 6849 IdentifierInfo *FnName, 6850 SourceLocation FnLoc, 6851 SourceLocation RParenLoc) { 6852 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 6853 if (!Size) 6854 return false; 6855 6856 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 6857 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 6858 return false; 6859 6860 SourceRange SizeRange = Size->getSourceRange(); 6861 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 6862 << SizeRange << FnName; 6863 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 6864 << FnName << FixItHint::CreateInsertion( 6865 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 6866 << FixItHint::CreateRemoval(RParenLoc); 6867 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 6868 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 6869 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 6870 ")"); 6871 6872 return true; 6873 } 6874 6875 /// \brief Determine whether the given type is or contains a dynamic class type 6876 /// (e.g., whether it has a vtable). 6877 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 6878 bool &IsContained) { 6879 // Look through array types while ignoring qualifiers. 6880 const Type *Ty = T->getBaseElementTypeUnsafe(); 6881 IsContained = false; 6882 6883 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 6884 RD = RD ? RD->getDefinition() : nullptr; 6885 if (!RD || RD->isInvalidDecl()) 6886 return nullptr; 6887 6888 if (RD->isDynamicClass()) 6889 return RD; 6890 6891 // Check all the fields. If any bases were dynamic, the class is dynamic. 6892 // It's impossible for a class to transitively contain itself by value, so 6893 // infinite recursion is impossible. 6894 for (auto *FD : RD->fields()) { 6895 bool SubContained; 6896 if (const CXXRecordDecl *ContainedRD = 6897 getContainedDynamicClass(FD->getType(), SubContained)) { 6898 IsContained = true; 6899 return ContainedRD; 6900 } 6901 } 6902 6903 return nullptr; 6904 } 6905 6906 /// \brief If E is a sizeof expression, returns its argument expression, 6907 /// otherwise returns NULL. 6908 static const Expr *getSizeOfExprArg(const Expr *E) { 6909 if (const UnaryExprOrTypeTraitExpr *SizeOf = 6910 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 6911 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 6912 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 6913 6914 return nullptr; 6915 } 6916 6917 /// \brief If E is a sizeof expression, returns its argument type. 6918 static QualType getSizeOfArgType(const Expr *E) { 6919 if (const UnaryExprOrTypeTraitExpr *SizeOf = 6920 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 6921 if (SizeOf->getKind() == clang::UETT_SizeOf) 6922 return SizeOf->getTypeOfArgument(); 6923 6924 return QualType(); 6925 } 6926 6927 /// \brief Check for dangerous or invalid arguments to memset(). 6928 /// 6929 /// This issues warnings on known problematic, dangerous or unspecified 6930 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 6931 /// function calls. 6932 /// 6933 /// \param Call The call expression to diagnose. 6934 void Sema::CheckMemaccessArguments(const CallExpr *Call, 6935 unsigned BId, 6936 IdentifierInfo *FnName) { 6937 assert(BId != 0); 6938 6939 // It is possible to have a non-standard definition of memset. Validate 6940 // we have enough arguments, and if not, abort further checking. 6941 unsigned ExpectedNumArgs = 6942 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 6943 if (Call->getNumArgs() < ExpectedNumArgs) 6944 return; 6945 6946 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 6947 BId == Builtin::BIstrndup ? 1 : 2); 6948 unsigned LenArg = 6949 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 6950 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 6951 6952 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 6953 Call->getLocStart(), Call->getRParenLoc())) 6954 return; 6955 6956 // We have special checking when the length is a sizeof expression. 6957 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 6958 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 6959 llvm::FoldingSetNodeID SizeOfArgID; 6960 6961 // Although widely used, 'bzero' is not a standard function. Be more strict 6962 // with the argument types before allowing diagnostics and only allow the 6963 // form bzero(ptr, sizeof(...)). 6964 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 6965 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 6966 return; 6967 6968 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 6969 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 6970 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 6971 6972 QualType DestTy = Dest->getType(); 6973 QualType PointeeTy; 6974 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 6975 PointeeTy = DestPtrTy->getPointeeType(); 6976 6977 // Never warn about void type pointers. This can be used to suppress 6978 // false positives. 6979 if (PointeeTy->isVoidType()) 6980 continue; 6981 6982 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 6983 // actually comparing the expressions for equality. Because computing the 6984 // expression IDs can be expensive, we only do this if the diagnostic is 6985 // enabled. 6986 if (SizeOfArg && 6987 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 6988 SizeOfArg->getExprLoc())) { 6989 // We only compute IDs for expressions if the warning is enabled, and 6990 // cache the sizeof arg's ID. 6991 if (SizeOfArgID == llvm::FoldingSetNodeID()) 6992 SizeOfArg->Profile(SizeOfArgID, Context, true); 6993 llvm::FoldingSetNodeID DestID; 6994 Dest->Profile(DestID, Context, true); 6995 if (DestID == SizeOfArgID) { 6996 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 6997 // over sizeof(src) as well. 6998 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 6999 StringRef ReadableName = FnName->getName(); 7000 7001 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 7002 if (UnaryOp->getOpcode() == UO_AddrOf) 7003 ActionIdx = 1; // If its an address-of operator, just remove it. 7004 if (!PointeeTy->isIncompleteType() && 7005 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 7006 ActionIdx = 2; // If the pointee's size is sizeof(char), 7007 // suggest an explicit length. 7008 7009 // If the function is defined as a builtin macro, do not show macro 7010 // expansion. 7011 SourceLocation SL = SizeOfArg->getExprLoc(); 7012 SourceRange DSR = Dest->getSourceRange(); 7013 SourceRange SSR = SizeOfArg->getSourceRange(); 7014 SourceManager &SM = getSourceManager(); 7015 7016 if (SM.isMacroArgExpansion(SL)) { 7017 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 7018 SL = SM.getSpellingLoc(SL); 7019 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 7020 SM.getSpellingLoc(DSR.getEnd())); 7021 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 7022 SM.getSpellingLoc(SSR.getEnd())); 7023 } 7024 7025 DiagRuntimeBehavior(SL, SizeOfArg, 7026 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 7027 << ReadableName 7028 << PointeeTy 7029 << DestTy 7030 << DSR 7031 << SSR); 7032 DiagRuntimeBehavior(SL, SizeOfArg, 7033 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 7034 << ActionIdx 7035 << SSR); 7036 7037 break; 7038 } 7039 } 7040 7041 // Also check for cases where the sizeof argument is the exact same 7042 // type as the memory argument, and where it points to a user-defined 7043 // record type. 7044 if (SizeOfArgTy != QualType()) { 7045 if (PointeeTy->isRecordType() && 7046 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 7047 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 7048 PDiag(diag::warn_sizeof_pointer_type_memaccess) 7049 << FnName << SizeOfArgTy << ArgIdx 7050 << PointeeTy << Dest->getSourceRange() 7051 << LenExpr->getSourceRange()); 7052 break; 7053 } 7054 } 7055 } else if (DestTy->isArrayType()) { 7056 PointeeTy = DestTy; 7057 } 7058 7059 if (PointeeTy == QualType()) 7060 continue; 7061 7062 // Always complain about dynamic classes. 7063 bool IsContained; 7064 if (const CXXRecordDecl *ContainedRD = 7065 getContainedDynamicClass(PointeeTy, IsContained)) { 7066 7067 unsigned OperationType = 0; 7068 // "overwritten" if we're warning about the destination for any call 7069 // but memcmp; otherwise a verb appropriate to the call. 7070 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 7071 if (BId == Builtin::BImemcpy) 7072 OperationType = 1; 7073 else if(BId == Builtin::BImemmove) 7074 OperationType = 2; 7075 else if (BId == Builtin::BImemcmp) 7076 OperationType = 3; 7077 } 7078 7079 DiagRuntimeBehavior( 7080 Dest->getExprLoc(), Dest, 7081 PDiag(diag::warn_dyn_class_memaccess) 7082 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 7083 << FnName << IsContained << ContainedRD << OperationType 7084 << Call->getCallee()->getSourceRange()); 7085 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 7086 BId != Builtin::BImemset) 7087 DiagRuntimeBehavior( 7088 Dest->getExprLoc(), Dest, 7089 PDiag(diag::warn_arc_object_memaccess) 7090 << ArgIdx << FnName << PointeeTy 7091 << Call->getCallee()->getSourceRange()); 7092 else 7093 continue; 7094 7095 DiagRuntimeBehavior( 7096 Dest->getExprLoc(), Dest, 7097 PDiag(diag::note_bad_memaccess_silence) 7098 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 7099 break; 7100 } 7101 } 7102 7103 // A little helper routine: ignore addition and subtraction of integer literals. 7104 // This intentionally does not ignore all integer constant expressions because 7105 // we don't want to remove sizeof(). 7106 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 7107 Ex = Ex->IgnoreParenCasts(); 7108 7109 for (;;) { 7110 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 7111 if (!BO || !BO->isAdditiveOp()) 7112 break; 7113 7114 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 7115 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 7116 7117 if (isa<IntegerLiteral>(RHS)) 7118 Ex = LHS; 7119 else if (isa<IntegerLiteral>(LHS)) 7120 Ex = RHS; 7121 else 7122 break; 7123 } 7124 7125 return Ex; 7126 } 7127 7128 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 7129 ASTContext &Context) { 7130 // Only handle constant-sized or VLAs, but not flexible members. 7131 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 7132 // Only issue the FIXIT for arrays of size > 1. 7133 if (CAT->getSize().getSExtValue() <= 1) 7134 return false; 7135 } else if (!Ty->isVariableArrayType()) { 7136 return false; 7137 } 7138 return true; 7139 } 7140 7141 // Warn if the user has made the 'size' argument to strlcpy or strlcat 7142 // be the size of the source, instead of the destination. 7143 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 7144 IdentifierInfo *FnName) { 7145 7146 // Don't crash if the user has the wrong number of arguments 7147 unsigned NumArgs = Call->getNumArgs(); 7148 if ((NumArgs != 3) && (NumArgs != 4)) 7149 return; 7150 7151 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 7152 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 7153 const Expr *CompareWithSrc = nullptr; 7154 7155 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 7156 Call->getLocStart(), Call->getRParenLoc())) 7157 return; 7158 7159 // Look for 'strlcpy(dst, x, sizeof(x))' 7160 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 7161 CompareWithSrc = Ex; 7162 else { 7163 // Look for 'strlcpy(dst, x, strlen(x))' 7164 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 7165 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 7166 SizeCall->getNumArgs() == 1) 7167 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 7168 } 7169 } 7170 7171 if (!CompareWithSrc) 7172 return; 7173 7174 // Determine if the argument to sizeof/strlen is equal to the source 7175 // argument. In principle there's all kinds of things you could do 7176 // here, for instance creating an == expression and evaluating it with 7177 // EvaluateAsBooleanCondition, but this uses a more direct technique: 7178 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 7179 if (!SrcArgDRE) 7180 return; 7181 7182 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 7183 if (!CompareWithSrcDRE || 7184 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 7185 return; 7186 7187 const Expr *OriginalSizeArg = Call->getArg(2); 7188 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 7189 << OriginalSizeArg->getSourceRange() << FnName; 7190 7191 // Output a FIXIT hint if the destination is an array (rather than a 7192 // pointer to an array). This could be enhanced to handle some 7193 // pointers if we know the actual size, like if DstArg is 'array+2' 7194 // we could say 'sizeof(array)-2'. 7195 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 7196 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 7197 return; 7198 7199 SmallString<128> sizeString; 7200 llvm::raw_svector_ostream OS(sizeString); 7201 OS << "sizeof("; 7202 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7203 OS << ")"; 7204 7205 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 7206 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 7207 OS.str()); 7208 } 7209 7210 /// Check if two expressions refer to the same declaration. 7211 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 7212 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 7213 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 7214 return D1->getDecl() == D2->getDecl(); 7215 return false; 7216 } 7217 7218 static const Expr *getStrlenExprArg(const Expr *E) { 7219 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7220 const FunctionDecl *FD = CE->getDirectCallee(); 7221 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 7222 return nullptr; 7223 return CE->getArg(0)->IgnoreParenCasts(); 7224 } 7225 return nullptr; 7226 } 7227 7228 // Warn on anti-patterns as the 'size' argument to strncat. 7229 // The correct size argument should look like following: 7230 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 7231 void Sema::CheckStrncatArguments(const CallExpr *CE, 7232 IdentifierInfo *FnName) { 7233 // Don't crash if the user has the wrong number of arguments. 7234 if (CE->getNumArgs() < 3) 7235 return; 7236 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 7237 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 7238 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 7239 7240 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 7241 CE->getRParenLoc())) 7242 return; 7243 7244 // Identify common expressions, which are wrongly used as the size argument 7245 // to strncat and may lead to buffer overflows. 7246 unsigned PatternType = 0; 7247 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 7248 // - sizeof(dst) 7249 if (referToTheSameDecl(SizeOfArg, DstArg)) 7250 PatternType = 1; 7251 // - sizeof(src) 7252 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 7253 PatternType = 2; 7254 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 7255 if (BE->getOpcode() == BO_Sub) { 7256 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 7257 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 7258 // - sizeof(dst) - strlen(dst) 7259 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 7260 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 7261 PatternType = 1; 7262 // - sizeof(src) - (anything) 7263 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 7264 PatternType = 2; 7265 } 7266 } 7267 7268 if (PatternType == 0) 7269 return; 7270 7271 // Generate the diagnostic. 7272 SourceLocation SL = LenArg->getLocStart(); 7273 SourceRange SR = LenArg->getSourceRange(); 7274 SourceManager &SM = getSourceManager(); 7275 7276 // If the function is defined as a builtin macro, do not show macro expansion. 7277 if (SM.isMacroArgExpansion(SL)) { 7278 SL = SM.getSpellingLoc(SL); 7279 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 7280 SM.getSpellingLoc(SR.getEnd())); 7281 } 7282 7283 // Check if the destination is an array (rather than a pointer to an array). 7284 QualType DstTy = DstArg->getType(); 7285 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 7286 Context); 7287 if (!isKnownSizeArray) { 7288 if (PatternType == 1) 7289 Diag(SL, diag::warn_strncat_wrong_size) << SR; 7290 else 7291 Diag(SL, diag::warn_strncat_src_size) << SR; 7292 return; 7293 } 7294 7295 if (PatternType == 1) 7296 Diag(SL, diag::warn_strncat_large_size) << SR; 7297 else 7298 Diag(SL, diag::warn_strncat_src_size) << SR; 7299 7300 SmallString<128> sizeString; 7301 llvm::raw_svector_ostream OS(sizeString); 7302 OS << "sizeof("; 7303 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7304 OS << ") - "; 7305 OS << "strlen("; 7306 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7307 OS << ") - 1"; 7308 7309 Diag(SL, diag::note_strncat_wrong_size) 7310 << FixItHint::CreateReplacement(SR, OS.str()); 7311 } 7312 7313 //===--- CHECK: Return Address of Stack Variable --------------------------===// 7314 7315 static const Expr *EvalVal(const Expr *E, 7316 SmallVectorImpl<const DeclRefExpr *> &refVars, 7317 const Decl *ParentDecl); 7318 static const Expr *EvalAddr(const Expr *E, 7319 SmallVectorImpl<const DeclRefExpr *> &refVars, 7320 const Decl *ParentDecl); 7321 7322 /// CheckReturnStackAddr - Check if a return statement returns the address 7323 /// of a stack variable. 7324 static void 7325 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 7326 SourceLocation ReturnLoc) { 7327 7328 const Expr *stackE = nullptr; 7329 SmallVector<const DeclRefExpr *, 8> refVars; 7330 7331 // Perform checking for returned stack addresses, local blocks, 7332 // label addresses or references to temporaries. 7333 if (lhsType->isPointerType() || 7334 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 7335 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 7336 } else if (lhsType->isReferenceType()) { 7337 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 7338 } 7339 7340 if (!stackE) 7341 return; // Nothing suspicious was found. 7342 7343 // Parameters are initalized in the calling scope, so taking the address 7344 // of a parameter reference doesn't need a warning. 7345 for (auto *DRE : refVars) 7346 if (isa<ParmVarDecl>(DRE->getDecl())) 7347 return; 7348 7349 SourceLocation diagLoc; 7350 SourceRange diagRange; 7351 if (refVars.empty()) { 7352 diagLoc = stackE->getLocStart(); 7353 diagRange = stackE->getSourceRange(); 7354 } else { 7355 // We followed through a reference variable. 'stackE' contains the 7356 // problematic expression but we will warn at the return statement pointing 7357 // at the reference variable. We will later display the "trail" of 7358 // reference variables using notes. 7359 diagLoc = refVars[0]->getLocStart(); 7360 diagRange = refVars[0]->getSourceRange(); 7361 } 7362 7363 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 7364 // address of local var 7365 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 7366 << DR->getDecl()->getDeclName() << diagRange; 7367 } else if (isa<BlockExpr>(stackE)) { // local block. 7368 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 7369 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 7370 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 7371 } else { // local temporary. 7372 // If there is an LValue->RValue conversion, then the value of the 7373 // reference type is used, not the reference. 7374 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 7375 if (ICE->getCastKind() == CK_LValueToRValue) { 7376 return; 7377 } 7378 } 7379 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 7380 << lhsType->isReferenceType() << diagRange; 7381 } 7382 7383 // Display the "trail" of reference variables that we followed until we 7384 // found the problematic expression using notes. 7385 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 7386 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 7387 // If this var binds to another reference var, show the range of the next 7388 // var, otherwise the var binds to the problematic expression, in which case 7389 // show the range of the expression. 7390 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 7391 : stackE->getSourceRange(); 7392 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 7393 << VD->getDeclName() << range; 7394 } 7395 } 7396 7397 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 7398 /// check if the expression in a return statement evaluates to an address 7399 /// to a location on the stack, a local block, an address of a label, or a 7400 /// reference to local temporary. The recursion is used to traverse the 7401 /// AST of the return expression, with recursion backtracking when we 7402 /// encounter a subexpression that (1) clearly does not lead to one of the 7403 /// above problematic expressions (2) is something we cannot determine leads to 7404 /// a problematic expression based on such local checking. 7405 /// 7406 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 7407 /// the expression that they point to. Such variables are added to the 7408 /// 'refVars' vector so that we know what the reference variable "trail" was. 7409 /// 7410 /// EvalAddr processes expressions that are pointers that are used as 7411 /// references (and not L-values). EvalVal handles all other values. 7412 /// At the base case of the recursion is a check for the above problematic 7413 /// expressions. 7414 /// 7415 /// This implementation handles: 7416 /// 7417 /// * pointer-to-pointer casts 7418 /// * implicit conversions from array references to pointers 7419 /// * taking the address of fields 7420 /// * arbitrary interplay between "&" and "*" operators 7421 /// * pointer arithmetic from an address of a stack variable 7422 /// * taking the address of an array element where the array is on the stack 7423 static const Expr *EvalAddr(const Expr *E, 7424 SmallVectorImpl<const DeclRefExpr *> &refVars, 7425 const Decl *ParentDecl) { 7426 if (E->isTypeDependent()) 7427 return nullptr; 7428 7429 // We should only be called for evaluating pointer expressions. 7430 assert((E->getType()->isAnyPointerType() || 7431 E->getType()->isBlockPointerType() || 7432 E->getType()->isObjCQualifiedIdType()) && 7433 "EvalAddr only works on pointers"); 7434 7435 E = E->IgnoreParens(); 7436 7437 // Our "symbolic interpreter" is just a dispatch off the currently 7438 // viewed AST node. We then recursively traverse the AST by calling 7439 // EvalAddr and EvalVal appropriately. 7440 switch (E->getStmtClass()) { 7441 case Stmt::DeclRefExprClass: { 7442 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7443 7444 // If we leave the immediate function, the lifetime isn't about to end. 7445 if (DR->refersToEnclosingVariableOrCapture()) 7446 return nullptr; 7447 7448 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 7449 // If this is a reference variable, follow through to the expression that 7450 // it points to. 7451 if (V->hasLocalStorage() && 7452 V->getType()->isReferenceType() && V->hasInit()) { 7453 // Add the reference variable to the "trail". 7454 refVars.push_back(DR); 7455 return EvalAddr(V->getInit(), refVars, ParentDecl); 7456 } 7457 7458 return nullptr; 7459 } 7460 7461 case Stmt::UnaryOperatorClass: { 7462 // The only unary operator that make sense to handle here 7463 // is AddrOf. All others don't make sense as pointers. 7464 const UnaryOperator *U = cast<UnaryOperator>(E); 7465 7466 if (U->getOpcode() == UO_AddrOf) 7467 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 7468 return nullptr; 7469 } 7470 7471 case Stmt::BinaryOperatorClass: { 7472 // Handle pointer arithmetic. All other binary operators are not valid 7473 // in this context. 7474 const BinaryOperator *B = cast<BinaryOperator>(E); 7475 BinaryOperatorKind op = B->getOpcode(); 7476 7477 if (op != BO_Add && op != BO_Sub) 7478 return nullptr; 7479 7480 const Expr *Base = B->getLHS(); 7481 7482 // Determine which argument is the real pointer base. It could be 7483 // the RHS argument instead of the LHS. 7484 if (!Base->getType()->isPointerType()) 7485 Base = B->getRHS(); 7486 7487 assert(Base->getType()->isPointerType()); 7488 return EvalAddr(Base, refVars, ParentDecl); 7489 } 7490 7491 // For conditional operators we need to see if either the LHS or RHS are 7492 // valid DeclRefExpr*s. If one of them is valid, we return it. 7493 case Stmt::ConditionalOperatorClass: { 7494 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7495 7496 // Handle the GNU extension for missing LHS. 7497 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 7498 if (const Expr *LHSExpr = C->getLHS()) { 7499 // In C++, we can have a throw-expression, which has 'void' type. 7500 if (!LHSExpr->getType()->isVoidType()) 7501 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 7502 return LHS; 7503 } 7504 7505 // In C++, we can have a throw-expression, which has 'void' type. 7506 if (C->getRHS()->getType()->isVoidType()) 7507 return nullptr; 7508 7509 return EvalAddr(C->getRHS(), refVars, ParentDecl); 7510 } 7511 7512 case Stmt::BlockExprClass: 7513 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 7514 return E; // local block. 7515 return nullptr; 7516 7517 case Stmt::AddrLabelExprClass: 7518 return E; // address of label. 7519 7520 case Stmt::ExprWithCleanupsClass: 7521 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7522 ParentDecl); 7523 7524 // For casts, we need to handle conversions from arrays to 7525 // pointer values, and pointer-to-pointer conversions. 7526 case Stmt::ImplicitCastExprClass: 7527 case Stmt::CStyleCastExprClass: 7528 case Stmt::CXXFunctionalCastExprClass: 7529 case Stmt::ObjCBridgedCastExprClass: 7530 case Stmt::CXXStaticCastExprClass: 7531 case Stmt::CXXDynamicCastExprClass: 7532 case Stmt::CXXConstCastExprClass: 7533 case Stmt::CXXReinterpretCastExprClass: { 7534 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 7535 switch (cast<CastExpr>(E)->getCastKind()) { 7536 case CK_LValueToRValue: 7537 case CK_NoOp: 7538 case CK_BaseToDerived: 7539 case CK_DerivedToBase: 7540 case CK_UncheckedDerivedToBase: 7541 case CK_Dynamic: 7542 case CK_CPointerToObjCPointerCast: 7543 case CK_BlockPointerToObjCPointerCast: 7544 case CK_AnyPointerToBlockPointerCast: 7545 return EvalAddr(SubExpr, refVars, ParentDecl); 7546 7547 case CK_ArrayToPointerDecay: 7548 return EvalVal(SubExpr, refVars, ParentDecl); 7549 7550 case CK_BitCast: 7551 if (SubExpr->getType()->isAnyPointerType() || 7552 SubExpr->getType()->isBlockPointerType() || 7553 SubExpr->getType()->isObjCQualifiedIdType()) 7554 return EvalAddr(SubExpr, refVars, ParentDecl); 7555 else 7556 return nullptr; 7557 7558 default: 7559 return nullptr; 7560 } 7561 } 7562 7563 case Stmt::MaterializeTemporaryExprClass: 7564 if (const Expr *Result = 7565 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7566 refVars, ParentDecl)) 7567 return Result; 7568 return E; 7569 7570 // Everything else: we simply don't reason about them. 7571 default: 7572 return nullptr; 7573 } 7574 } 7575 7576 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 7577 /// See the comments for EvalAddr for more details. 7578 static const Expr *EvalVal(const Expr *E, 7579 SmallVectorImpl<const DeclRefExpr *> &refVars, 7580 const Decl *ParentDecl) { 7581 do { 7582 // We should only be called for evaluating non-pointer expressions, or 7583 // expressions with a pointer type that are not used as references but 7584 // instead 7585 // are l-values (e.g., DeclRefExpr with a pointer type). 7586 7587 // Our "symbolic interpreter" is just a dispatch off the currently 7588 // viewed AST node. We then recursively traverse the AST by calling 7589 // EvalAddr and EvalVal appropriately. 7590 7591 E = E->IgnoreParens(); 7592 switch (E->getStmtClass()) { 7593 case Stmt::ImplicitCastExprClass: { 7594 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 7595 if (IE->getValueKind() == VK_LValue) { 7596 E = IE->getSubExpr(); 7597 continue; 7598 } 7599 return nullptr; 7600 } 7601 7602 case Stmt::ExprWithCleanupsClass: 7603 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7604 ParentDecl); 7605 7606 case Stmt::DeclRefExprClass: { 7607 // When we hit a DeclRefExpr we are looking at code that refers to a 7608 // variable's name. If it's not a reference variable we check if it has 7609 // local storage within the function, and if so, return the expression. 7610 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7611 7612 // If we leave the immediate function, the lifetime isn't about to end. 7613 if (DR->refersToEnclosingVariableOrCapture()) 7614 return nullptr; 7615 7616 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 7617 // Check if it refers to itself, e.g. "int& i = i;". 7618 if (V == ParentDecl) 7619 return DR; 7620 7621 if (V->hasLocalStorage()) { 7622 if (!V->getType()->isReferenceType()) 7623 return DR; 7624 7625 // Reference variable, follow through to the expression that 7626 // it points to. 7627 if (V->hasInit()) { 7628 // Add the reference variable to the "trail". 7629 refVars.push_back(DR); 7630 return EvalVal(V->getInit(), refVars, V); 7631 } 7632 } 7633 } 7634 7635 return nullptr; 7636 } 7637 7638 case Stmt::UnaryOperatorClass: { 7639 // The only unary operator that make sense to handle here 7640 // is Deref. All others don't resolve to a "name." This includes 7641 // handling all sorts of rvalues passed to a unary operator. 7642 const UnaryOperator *U = cast<UnaryOperator>(E); 7643 7644 if (U->getOpcode() == UO_Deref) 7645 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 7646 7647 return nullptr; 7648 } 7649 7650 case Stmt::ArraySubscriptExprClass: { 7651 // Array subscripts are potential references to data on the stack. We 7652 // retrieve the DeclRefExpr* for the array variable if it indeed 7653 // has local storage. 7654 const auto *ASE = cast<ArraySubscriptExpr>(E); 7655 if (ASE->isTypeDependent()) 7656 return nullptr; 7657 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 7658 } 7659 7660 case Stmt::OMPArraySectionExprClass: { 7661 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 7662 ParentDecl); 7663 } 7664 7665 case Stmt::ConditionalOperatorClass: { 7666 // For conditional operators we need to see if either the LHS or RHS are 7667 // non-NULL Expr's. If one is non-NULL, we return it. 7668 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7669 7670 // Handle the GNU extension for missing LHS. 7671 if (const Expr *LHSExpr = C->getLHS()) { 7672 // In C++, we can have a throw-expression, which has 'void' type. 7673 if (!LHSExpr->getType()->isVoidType()) 7674 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 7675 return LHS; 7676 } 7677 7678 // In C++, we can have a throw-expression, which has 'void' type. 7679 if (C->getRHS()->getType()->isVoidType()) 7680 return nullptr; 7681 7682 return EvalVal(C->getRHS(), refVars, ParentDecl); 7683 } 7684 7685 // Accesses to members are potential references to data on the stack. 7686 case Stmt::MemberExprClass: { 7687 const MemberExpr *M = cast<MemberExpr>(E); 7688 7689 // Check for indirect access. We only want direct field accesses. 7690 if (M->isArrow()) 7691 return nullptr; 7692 7693 // Check whether the member type is itself a reference, in which case 7694 // we're not going to refer to the member, but to what the member refers 7695 // to. 7696 if (M->getMemberDecl()->getType()->isReferenceType()) 7697 return nullptr; 7698 7699 return EvalVal(M->getBase(), refVars, ParentDecl); 7700 } 7701 7702 case Stmt::MaterializeTemporaryExprClass: 7703 if (const Expr *Result = 7704 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7705 refVars, ParentDecl)) 7706 return Result; 7707 return E; 7708 7709 default: 7710 // Check that we don't return or take the address of a reference to a 7711 // temporary. This is only useful in C++. 7712 if (!E->isTypeDependent() && E->isRValue()) 7713 return E; 7714 7715 // Everything else: we simply don't reason about them. 7716 return nullptr; 7717 } 7718 } while (true); 7719 } 7720 7721 void 7722 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 7723 SourceLocation ReturnLoc, 7724 bool isObjCMethod, 7725 const AttrVec *Attrs, 7726 const FunctionDecl *FD) { 7727 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 7728 7729 // Check if the return value is null but should not be. 7730 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 7731 (!isObjCMethod && isNonNullType(Context, lhsType))) && 7732 CheckNonNullExpr(*this, RetValExp)) 7733 Diag(ReturnLoc, diag::warn_null_ret) 7734 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 7735 7736 // C++11 [basic.stc.dynamic.allocation]p4: 7737 // If an allocation function declared with a non-throwing 7738 // exception-specification fails to allocate storage, it shall return 7739 // a null pointer. Any other allocation function that fails to allocate 7740 // storage shall indicate failure only by throwing an exception [...] 7741 if (FD) { 7742 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 7743 if (Op == OO_New || Op == OO_Array_New) { 7744 const FunctionProtoType *Proto 7745 = FD->getType()->castAs<FunctionProtoType>(); 7746 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 7747 CheckNonNullExpr(*this, RetValExp)) 7748 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 7749 << FD << getLangOpts().CPlusPlus11; 7750 } 7751 } 7752 } 7753 7754 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 7755 7756 /// Check for comparisons of floating point operands using != and ==. 7757 /// Issue a warning if these are no self-comparisons, as they are not likely 7758 /// to do what the programmer intended. 7759 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 7760 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 7761 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 7762 7763 // Special case: check for x == x (which is OK). 7764 // Do not emit warnings for such cases. 7765 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 7766 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 7767 if (DRL->getDecl() == DRR->getDecl()) 7768 return; 7769 7770 // Special case: check for comparisons against literals that can be exactly 7771 // represented by APFloat. In such cases, do not emit a warning. This 7772 // is a heuristic: often comparison against such literals are used to 7773 // detect if a value in a variable has not changed. This clearly can 7774 // lead to false negatives. 7775 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 7776 if (FLL->isExact()) 7777 return; 7778 } else 7779 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 7780 if (FLR->isExact()) 7781 return; 7782 7783 // Check for comparisons with builtin types. 7784 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 7785 if (CL->getBuiltinCallee()) 7786 return; 7787 7788 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 7789 if (CR->getBuiltinCallee()) 7790 return; 7791 7792 // Emit the diagnostic. 7793 Diag(Loc, diag::warn_floatingpoint_eq) 7794 << LHS->getSourceRange() << RHS->getSourceRange(); 7795 } 7796 7797 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 7798 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 7799 7800 namespace { 7801 7802 /// Structure recording the 'active' range of an integer-valued 7803 /// expression. 7804 struct IntRange { 7805 /// The number of bits active in the int. 7806 unsigned Width; 7807 7808 /// True if the int is known not to have negative values. 7809 bool NonNegative; 7810 7811 IntRange(unsigned Width, bool NonNegative) 7812 : Width(Width), NonNegative(NonNegative) 7813 {} 7814 7815 /// Returns the range of the bool type. 7816 static IntRange forBoolType() { 7817 return IntRange(1, true); 7818 } 7819 7820 /// Returns the range of an opaque value of the given integral type. 7821 static IntRange forValueOfType(ASTContext &C, QualType T) { 7822 return forValueOfCanonicalType(C, 7823 T->getCanonicalTypeInternal().getTypePtr()); 7824 } 7825 7826 /// Returns the range of an opaque value of a canonical integral type. 7827 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 7828 assert(T->isCanonicalUnqualified()); 7829 7830 if (const VectorType *VT = dyn_cast<VectorType>(T)) 7831 T = VT->getElementType().getTypePtr(); 7832 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 7833 T = CT->getElementType().getTypePtr(); 7834 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 7835 T = AT->getValueType().getTypePtr(); 7836 7837 // For enum types, use the known bit width of the enumerators. 7838 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 7839 EnumDecl *Enum = ET->getDecl(); 7840 if (!Enum->isCompleteDefinition()) 7841 return IntRange(C.getIntWidth(QualType(T, 0)), false); 7842 7843 unsigned NumPositive = Enum->getNumPositiveBits(); 7844 unsigned NumNegative = Enum->getNumNegativeBits(); 7845 7846 if (NumNegative == 0) 7847 return IntRange(NumPositive, true/*NonNegative*/); 7848 else 7849 return IntRange(std::max(NumPositive + 1, NumNegative), 7850 false/*NonNegative*/); 7851 } 7852 7853 const BuiltinType *BT = cast<BuiltinType>(T); 7854 assert(BT->isInteger()); 7855 7856 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 7857 } 7858 7859 /// Returns the "target" range of a canonical integral type, i.e. 7860 /// the range of values expressible in the type. 7861 /// 7862 /// This matches forValueOfCanonicalType except that enums have the 7863 /// full range of their type, not the range of their enumerators. 7864 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 7865 assert(T->isCanonicalUnqualified()); 7866 7867 if (const VectorType *VT = dyn_cast<VectorType>(T)) 7868 T = VT->getElementType().getTypePtr(); 7869 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 7870 T = CT->getElementType().getTypePtr(); 7871 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 7872 T = AT->getValueType().getTypePtr(); 7873 if (const EnumType *ET = dyn_cast<EnumType>(T)) 7874 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 7875 7876 const BuiltinType *BT = cast<BuiltinType>(T); 7877 assert(BT->isInteger()); 7878 7879 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 7880 } 7881 7882 /// Returns the supremum of two ranges: i.e. their conservative merge. 7883 static IntRange join(IntRange L, IntRange R) { 7884 return IntRange(std::max(L.Width, R.Width), 7885 L.NonNegative && R.NonNegative); 7886 } 7887 7888 /// Returns the infinum of two ranges: i.e. their aggressive merge. 7889 static IntRange meet(IntRange L, IntRange R) { 7890 return IntRange(std::min(L.Width, R.Width), 7891 L.NonNegative || R.NonNegative); 7892 } 7893 }; 7894 7895 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 7896 if (value.isSigned() && value.isNegative()) 7897 return IntRange(value.getMinSignedBits(), false); 7898 7899 if (value.getBitWidth() > MaxWidth) 7900 value = value.trunc(MaxWidth); 7901 7902 // isNonNegative() just checks the sign bit without considering 7903 // signedness. 7904 return IntRange(value.getActiveBits(), true); 7905 } 7906 7907 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 7908 unsigned MaxWidth) { 7909 if (result.isInt()) 7910 return GetValueRange(C, result.getInt(), MaxWidth); 7911 7912 if (result.isVector()) { 7913 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 7914 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 7915 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 7916 R = IntRange::join(R, El); 7917 } 7918 return R; 7919 } 7920 7921 if (result.isComplexInt()) { 7922 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 7923 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 7924 return IntRange::join(R, I); 7925 } 7926 7927 // This can happen with lossless casts to intptr_t of "based" lvalues. 7928 // Assume it might use arbitrary bits. 7929 // FIXME: The only reason we need to pass the type in here is to get 7930 // the sign right on this one case. It would be nice if APValue 7931 // preserved this. 7932 assert(result.isLValue() || result.isAddrLabelDiff()); 7933 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 7934 } 7935 7936 QualType GetExprType(const Expr *E) { 7937 QualType Ty = E->getType(); 7938 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 7939 Ty = AtomicRHS->getValueType(); 7940 return Ty; 7941 } 7942 7943 /// Pseudo-evaluate the given integer expression, estimating the 7944 /// range of values it might take. 7945 /// 7946 /// \param MaxWidth - the width to which the value will be truncated 7947 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 7948 E = E->IgnoreParens(); 7949 7950 // Try a full evaluation first. 7951 Expr::EvalResult result; 7952 if (E->EvaluateAsRValue(result, C)) 7953 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 7954 7955 // I think we only want to look through implicit casts here; if the 7956 // user has an explicit widening cast, we should treat the value as 7957 // being of the new, wider type. 7958 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 7959 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 7960 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 7961 7962 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 7963 7964 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 7965 CE->getCastKind() == CK_BooleanToSignedIntegral; 7966 7967 // Assume that non-integer casts can span the full range of the type. 7968 if (!isIntegerCast) 7969 return OutputTypeRange; 7970 7971 IntRange SubRange 7972 = GetExprRange(C, CE->getSubExpr(), 7973 std::min(MaxWidth, OutputTypeRange.Width)); 7974 7975 // Bail out if the subexpr's range is as wide as the cast type. 7976 if (SubRange.Width >= OutputTypeRange.Width) 7977 return OutputTypeRange; 7978 7979 // Otherwise, we take the smaller width, and we're non-negative if 7980 // either the output type or the subexpr is. 7981 return IntRange(SubRange.Width, 7982 SubRange.NonNegative || OutputTypeRange.NonNegative); 7983 } 7984 7985 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 7986 // If we can fold the condition, just take that operand. 7987 bool CondResult; 7988 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 7989 return GetExprRange(C, CondResult ? CO->getTrueExpr() 7990 : CO->getFalseExpr(), 7991 MaxWidth); 7992 7993 // Otherwise, conservatively merge. 7994 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 7995 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 7996 return IntRange::join(L, R); 7997 } 7998 7999 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 8000 switch (BO->getOpcode()) { 8001 8002 // Boolean-valued operations are single-bit and positive. 8003 case BO_LAnd: 8004 case BO_LOr: 8005 case BO_LT: 8006 case BO_GT: 8007 case BO_LE: 8008 case BO_GE: 8009 case BO_EQ: 8010 case BO_NE: 8011 return IntRange::forBoolType(); 8012 8013 // The type of the assignments is the type of the LHS, so the RHS 8014 // is not necessarily the same type. 8015 case BO_MulAssign: 8016 case BO_DivAssign: 8017 case BO_RemAssign: 8018 case BO_AddAssign: 8019 case BO_SubAssign: 8020 case BO_XorAssign: 8021 case BO_OrAssign: 8022 // TODO: bitfields? 8023 return IntRange::forValueOfType(C, GetExprType(E)); 8024 8025 // Simple assignments just pass through the RHS, which will have 8026 // been coerced to the LHS type. 8027 case BO_Assign: 8028 // TODO: bitfields? 8029 return GetExprRange(C, BO->getRHS(), MaxWidth); 8030 8031 // Operations with opaque sources are black-listed. 8032 case BO_PtrMemD: 8033 case BO_PtrMemI: 8034 return IntRange::forValueOfType(C, GetExprType(E)); 8035 8036 // Bitwise-and uses the *infinum* of the two source ranges. 8037 case BO_And: 8038 case BO_AndAssign: 8039 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 8040 GetExprRange(C, BO->getRHS(), MaxWidth)); 8041 8042 // Left shift gets black-listed based on a judgement call. 8043 case BO_Shl: 8044 // ...except that we want to treat '1 << (blah)' as logically 8045 // positive. It's an important idiom. 8046 if (IntegerLiteral *I 8047 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 8048 if (I->getValue() == 1) { 8049 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 8050 return IntRange(R.Width, /*NonNegative*/ true); 8051 } 8052 } 8053 // fallthrough 8054 8055 case BO_ShlAssign: 8056 return IntRange::forValueOfType(C, GetExprType(E)); 8057 8058 // Right shift by a constant can narrow its left argument. 8059 case BO_Shr: 8060 case BO_ShrAssign: { 8061 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8062 8063 // If the shift amount is a positive constant, drop the width by 8064 // that much. 8065 llvm::APSInt shift; 8066 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 8067 shift.isNonNegative()) { 8068 unsigned zext = shift.getZExtValue(); 8069 if (zext >= L.Width) 8070 L.Width = (L.NonNegative ? 0 : 1); 8071 else 8072 L.Width -= zext; 8073 } 8074 8075 return L; 8076 } 8077 8078 // Comma acts as its right operand. 8079 case BO_Comma: 8080 return GetExprRange(C, BO->getRHS(), MaxWidth); 8081 8082 // Black-list pointer subtractions. 8083 case BO_Sub: 8084 if (BO->getLHS()->getType()->isPointerType()) 8085 return IntRange::forValueOfType(C, GetExprType(E)); 8086 break; 8087 8088 // The width of a division result is mostly determined by the size 8089 // of the LHS. 8090 case BO_Div: { 8091 // Don't 'pre-truncate' the operands. 8092 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8093 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8094 8095 // If the divisor is constant, use that. 8096 llvm::APSInt divisor; 8097 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 8098 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 8099 if (log2 >= L.Width) 8100 L.Width = (L.NonNegative ? 0 : 1); 8101 else 8102 L.Width = std::min(L.Width - log2, MaxWidth); 8103 return L; 8104 } 8105 8106 // Otherwise, just use the LHS's width. 8107 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8108 return IntRange(L.Width, L.NonNegative && R.NonNegative); 8109 } 8110 8111 // The result of a remainder can't be larger than the result of 8112 // either side. 8113 case BO_Rem: { 8114 // Don't 'pre-truncate' the operands. 8115 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8116 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8117 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8118 8119 IntRange meet = IntRange::meet(L, R); 8120 meet.Width = std::min(meet.Width, MaxWidth); 8121 return meet; 8122 } 8123 8124 // The default behavior is okay for these. 8125 case BO_Mul: 8126 case BO_Add: 8127 case BO_Xor: 8128 case BO_Or: 8129 break; 8130 } 8131 8132 // The default case is to treat the operation as if it were closed 8133 // on the narrowest type that encompasses both operands. 8134 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8135 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 8136 return IntRange::join(L, R); 8137 } 8138 8139 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 8140 switch (UO->getOpcode()) { 8141 // Boolean-valued operations are white-listed. 8142 case UO_LNot: 8143 return IntRange::forBoolType(); 8144 8145 // Operations with opaque sources are black-listed. 8146 case UO_Deref: 8147 case UO_AddrOf: // should be impossible 8148 return IntRange::forValueOfType(C, GetExprType(E)); 8149 8150 default: 8151 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 8152 } 8153 } 8154 8155 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 8156 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 8157 8158 if (const auto *BitField = E->getSourceBitField()) 8159 return IntRange(BitField->getBitWidthValue(C), 8160 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 8161 8162 return IntRange::forValueOfType(C, GetExprType(E)); 8163 } 8164 8165 IntRange GetExprRange(ASTContext &C, const Expr *E) { 8166 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 8167 } 8168 8169 /// Checks whether the given value, which currently has the given 8170 /// source semantics, has the same value when coerced through the 8171 /// target semantics. 8172 bool IsSameFloatAfterCast(const llvm::APFloat &value, 8173 const llvm::fltSemantics &Src, 8174 const llvm::fltSemantics &Tgt) { 8175 llvm::APFloat truncated = value; 8176 8177 bool ignored; 8178 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 8179 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 8180 8181 return truncated.bitwiseIsEqual(value); 8182 } 8183 8184 /// Checks whether the given value, which currently has the given 8185 /// source semantics, has the same value when coerced through the 8186 /// target semantics. 8187 /// 8188 /// The value might be a vector of floats (or a complex number). 8189 bool IsSameFloatAfterCast(const APValue &value, 8190 const llvm::fltSemantics &Src, 8191 const llvm::fltSemantics &Tgt) { 8192 if (value.isFloat()) 8193 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 8194 8195 if (value.isVector()) { 8196 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 8197 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 8198 return false; 8199 return true; 8200 } 8201 8202 assert(value.isComplexFloat()); 8203 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 8204 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 8205 } 8206 8207 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 8208 8209 bool IsZero(Sema &S, Expr *E) { 8210 // Suppress cases where we are comparing against an enum constant. 8211 if (const DeclRefExpr *DR = 8212 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 8213 if (isa<EnumConstantDecl>(DR->getDecl())) 8214 return false; 8215 8216 // Suppress cases where the '0' value is expanded from a macro. 8217 if (E->getLocStart().isMacroID()) 8218 return false; 8219 8220 llvm::APSInt Value; 8221 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 8222 } 8223 8224 bool HasEnumType(Expr *E) { 8225 // Strip off implicit integral promotions. 8226 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8227 if (ICE->getCastKind() != CK_IntegralCast && 8228 ICE->getCastKind() != CK_NoOp) 8229 break; 8230 E = ICE->getSubExpr(); 8231 } 8232 8233 return E->getType()->isEnumeralType(); 8234 } 8235 8236 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 8237 // Disable warning in template instantiations. 8238 if (!S.ActiveTemplateInstantiations.empty()) 8239 return; 8240 8241 BinaryOperatorKind op = E->getOpcode(); 8242 if (E->isValueDependent()) 8243 return; 8244 8245 if (op == BO_LT && IsZero(S, E->getRHS())) { 8246 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8247 << "< 0" << "false" << HasEnumType(E->getLHS()) 8248 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8249 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 8250 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8251 << ">= 0" << "true" << HasEnumType(E->getLHS()) 8252 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8253 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 8254 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8255 << "0 >" << "false" << HasEnumType(E->getRHS()) 8256 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8257 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 8258 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8259 << "0 <=" << "true" << HasEnumType(E->getRHS()) 8260 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8261 } 8262 } 8263 8264 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant, 8265 Expr *Other, const llvm::APSInt &Value, 8266 bool RhsConstant) { 8267 // Disable warning in template instantiations. 8268 if (!S.ActiveTemplateInstantiations.empty()) 8269 return; 8270 8271 // TODO: Investigate using GetExprRange() to get tighter bounds 8272 // on the bit ranges. 8273 QualType OtherT = Other->getType(); 8274 if (const auto *AT = OtherT->getAs<AtomicType>()) 8275 OtherT = AT->getValueType(); 8276 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 8277 unsigned OtherWidth = OtherRange.Width; 8278 8279 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 8280 8281 // 0 values are handled later by CheckTrivialUnsignedComparison(). 8282 if ((Value == 0) && (!OtherIsBooleanType)) 8283 return; 8284 8285 BinaryOperatorKind op = E->getOpcode(); 8286 bool IsTrue = true; 8287 8288 // Used for diagnostic printout. 8289 enum { 8290 LiteralConstant = 0, 8291 CXXBoolLiteralTrue, 8292 CXXBoolLiteralFalse 8293 } LiteralOrBoolConstant = LiteralConstant; 8294 8295 if (!OtherIsBooleanType) { 8296 QualType ConstantT = Constant->getType(); 8297 QualType CommonT = E->getLHS()->getType(); 8298 8299 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 8300 return; 8301 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 8302 "comparison with non-integer type"); 8303 8304 bool ConstantSigned = ConstantT->isSignedIntegerType(); 8305 bool CommonSigned = CommonT->isSignedIntegerType(); 8306 8307 bool EqualityOnly = false; 8308 8309 if (CommonSigned) { 8310 // The common type is signed, therefore no signed to unsigned conversion. 8311 if (!OtherRange.NonNegative) { 8312 // Check that the constant is representable in type OtherT. 8313 if (ConstantSigned) { 8314 if (OtherWidth >= Value.getMinSignedBits()) 8315 return; 8316 } else { // !ConstantSigned 8317 if (OtherWidth >= Value.getActiveBits() + 1) 8318 return; 8319 } 8320 } else { // !OtherSigned 8321 // Check that the constant is representable in type OtherT. 8322 // Negative values are out of range. 8323 if (ConstantSigned) { 8324 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 8325 return; 8326 } else { // !ConstantSigned 8327 if (OtherWidth >= Value.getActiveBits()) 8328 return; 8329 } 8330 } 8331 } else { // !CommonSigned 8332 if (OtherRange.NonNegative) { 8333 if (OtherWidth >= Value.getActiveBits()) 8334 return; 8335 } else { // OtherSigned 8336 assert(!ConstantSigned && 8337 "Two signed types converted to unsigned types."); 8338 // Check to see if the constant is representable in OtherT. 8339 if (OtherWidth > Value.getActiveBits()) 8340 return; 8341 // Check to see if the constant is equivalent to a negative value 8342 // cast to CommonT. 8343 if (S.Context.getIntWidth(ConstantT) == 8344 S.Context.getIntWidth(CommonT) && 8345 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 8346 return; 8347 // The constant value rests between values that OtherT can represent 8348 // after conversion. Relational comparison still works, but equality 8349 // comparisons will be tautological. 8350 EqualityOnly = true; 8351 } 8352 } 8353 8354 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 8355 8356 if (op == BO_EQ || op == BO_NE) { 8357 IsTrue = op == BO_NE; 8358 } else if (EqualityOnly) { 8359 return; 8360 } else if (RhsConstant) { 8361 if (op == BO_GT || op == BO_GE) 8362 IsTrue = !PositiveConstant; 8363 else // op == BO_LT || op == BO_LE 8364 IsTrue = PositiveConstant; 8365 } else { 8366 if (op == BO_LT || op == BO_LE) 8367 IsTrue = !PositiveConstant; 8368 else // op == BO_GT || op == BO_GE 8369 IsTrue = PositiveConstant; 8370 } 8371 } else { 8372 // Other isKnownToHaveBooleanValue 8373 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 8374 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 8375 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 8376 8377 static const struct LinkedConditions { 8378 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 8379 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 8380 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 8381 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 8382 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 8383 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 8384 8385 } TruthTable = { 8386 // Constant on LHS. | Constant on RHS. | 8387 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 8388 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 8389 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 8390 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 8391 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 8392 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 8393 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 8394 }; 8395 8396 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 8397 8398 enum ConstantValue ConstVal = Zero; 8399 if (Value.isUnsigned() || Value.isNonNegative()) { 8400 if (Value == 0) { 8401 LiteralOrBoolConstant = 8402 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 8403 ConstVal = Zero; 8404 } else if (Value == 1) { 8405 LiteralOrBoolConstant = 8406 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 8407 ConstVal = One; 8408 } else { 8409 LiteralOrBoolConstant = LiteralConstant; 8410 ConstVal = GT_One; 8411 } 8412 } else { 8413 ConstVal = LT_Zero; 8414 } 8415 8416 CompareBoolWithConstantResult CmpRes; 8417 8418 switch (op) { 8419 case BO_LT: 8420 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 8421 break; 8422 case BO_GT: 8423 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 8424 break; 8425 case BO_LE: 8426 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 8427 break; 8428 case BO_GE: 8429 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 8430 break; 8431 case BO_EQ: 8432 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 8433 break; 8434 case BO_NE: 8435 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 8436 break; 8437 default: 8438 CmpRes = Unkwn; 8439 break; 8440 } 8441 8442 if (CmpRes == AFals) { 8443 IsTrue = false; 8444 } else if (CmpRes == ATrue) { 8445 IsTrue = true; 8446 } else { 8447 return; 8448 } 8449 } 8450 8451 // If this is a comparison to an enum constant, include that 8452 // constant in the diagnostic. 8453 const EnumConstantDecl *ED = nullptr; 8454 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 8455 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 8456 8457 SmallString<64> PrettySourceValue; 8458 llvm::raw_svector_ostream OS(PrettySourceValue); 8459 if (ED) 8460 OS << '\'' << *ED << "' (" << Value << ")"; 8461 else 8462 OS << Value; 8463 8464 S.DiagRuntimeBehavior( 8465 E->getOperatorLoc(), E, 8466 S.PDiag(diag::warn_out_of_range_compare) 8467 << OS.str() << LiteralOrBoolConstant 8468 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 8469 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 8470 } 8471 8472 /// Analyze the operands of the given comparison. Implements the 8473 /// fallback case from AnalyzeComparison. 8474 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 8475 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8476 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8477 } 8478 8479 /// \brief Implements -Wsign-compare. 8480 /// 8481 /// \param E the binary operator to check for warnings 8482 void AnalyzeComparison(Sema &S, BinaryOperator *E) { 8483 // The type the comparison is being performed in. 8484 QualType T = E->getLHS()->getType(); 8485 8486 // Only analyze comparison operators where both sides have been converted to 8487 // the same type. 8488 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 8489 return AnalyzeImpConvsInComparison(S, E); 8490 8491 // Don't analyze value-dependent comparisons directly. 8492 if (E->isValueDependent()) 8493 return AnalyzeImpConvsInComparison(S, E); 8494 8495 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 8496 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 8497 8498 bool IsComparisonConstant = false; 8499 8500 // Check whether an integer constant comparison results in a value 8501 // of 'true' or 'false'. 8502 if (T->isIntegralType(S.Context)) { 8503 llvm::APSInt RHSValue; 8504 bool IsRHSIntegralLiteral = 8505 RHS->isIntegerConstantExpr(RHSValue, S.Context); 8506 llvm::APSInt LHSValue; 8507 bool IsLHSIntegralLiteral = 8508 LHS->isIntegerConstantExpr(LHSValue, S.Context); 8509 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 8510 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 8511 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 8512 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 8513 else 8514 IsComparisonConstant = 8515 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 8516 } else if (!T->hasUnsignedIntegerRepresentation()) 8517 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 8518 8519 // We don't do anything special if this isn't an unsigned integral 8520 // comparison: we're only interested in integral comparisons, and 8521 // signed comparisons only happen in cases we don't care to warn about. 8522 // 8523 // We also don't care about value-dependent expressions or expressions 8524 // whose result is a constant. 8525 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 8526 return AnalyzeImpConvsInComparison(S, E); 8527 8528 // Check to see if one of the (unmodified) operands is of different 8529 // signedness. 8530 Expr *signedOperand, *unsignedOperand; 8531 if (LHS->getType()->hasSignedIntegerRepresentation()) { 8532 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 8533 "unsigned comparison between two signed integer expressions?"); 8534 signedOperand = LHS; 8535 unsignedOperand = RHS; 8536 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 8537 signedOperand = RHS; 8538 unsignedOperand = LHS; 8539 } else { 8540 CheckTrivialUnsignedComparison(S, E); 8541 return AnalyzeImpConvsInComparison(S, E); 8542 } 8543 8544 // Otherwise, calculate the effective range of the signed operand. 8545 IntRange signedRange = GetExprRange(S.Context, signedOperand); 8546 8547 // Go ahead and analyze implicit conversions in the operands. Note 8548 // that we skip the implicit conversions on both sides. 8549 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 8550 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 8551 8552 // If the signed range is non-negative, -Wsign-compare won't fire, 8553 // but we should still check for comparisons which are always true 8554 // or false. 8555 if (signedRange.NonNegative) 8556 return CheckTrivialUnsignedComparison(S, E); 8557 8558 // For (in)equality comparisons, if the unsigned operand is a 8559 // constant which cannot collide with a overflowed signed operand, 8560 // then reinterpreting the signed operand as unsigned will not 8561 // change the result of the comparison. 8562 if (E->isEqualityOp()) { 8563 unsigned comparisonWidth = S.Context.getIntWidth(T); 8564 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 8565 8566 // We should never be unable to prove that the unsigned operand is 8567 // non-negative. 8568 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 8569 8570 if (unsignedRange.Width < comparisonWidth) 8571 return; 8572 } 8573 8574 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 8575 S.PDiag(diag::warn_mixed_sign_comparison) 8576 << LHS->getType() << RHS->getType() 8577 << LHS->getSourceRange() << RHS->getSourceRange()); 8578 } 8579 8580 /// Analyzes an attempt to assign the given value to a bitfield. 8581 /// 8582 /// Returns true if there was something fishy about the attempt. 8583 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 8584 SourceLocation InitLoc) { 8585 assert(Bitfield->isBitField()); 8586 if (Bitfield->isInvalidDecl()) 8587 return false; 8588 8589 // White-list bool bitfields. 8590 QualType BitfieldType = Bitfield->getType(); 8591 if (BitfieldType->isBooleanType()) 8592 return false; 8593 8594 if (BitfieldType->isEnumeralType()) { 8595 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 8596 // If the underlying enum type was not explicitly specified as an unsigned 8597 // type and the enum contain only positive values, MSVC++ will cause an 8598 // inconsistency by storing this as a signed type. 8599 if (S.getLangOpts().CPlusPlus11 && 8600 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 8601 BitfieldEnumDecl->getNumPositiveBits() > 0 && 8602 BitfieldEnumDecl->getNumNegativeBits() == 0) { 8603 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 8604 << BitfieldEnumDecl->getNameAsString(); 8605 } 8606 } 8607 8608 if (Bitfield->getType()->isBooleanType()) 8609 return false; 8610 8611 // Ignore value- or type-dependent expressions. 8612 if (Bitfield->getBitWidth()->isValueDependent() || 8613 Bitfield->getBitWidth()->isTypeDependent() || 8614 Init->isValueDependent() || 8615 Init->isTypeDependent()) 8616 return false; 8617 8618 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 8619 8620 llvm::APSInt Value; 8621 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 8622 return false; 8623 8624 unsigned OriginalWidth = Value.getBitWidth(); 8625 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 8626 8627 if (!Value.isSigned() || Value.isNegative()) 8628 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 8629 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 8630 OriginalWidth = Value.getMinSignedBits(); 8631 8632 if (OriginalWidth <= FieldWidth) 8633 return false; 8634 8635 // Compute the value which the bitfield will contain. 8636 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 8637 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 8638 8639 // Check whether the stored value is equal to the original value. 8640 TruncatedValue = TruncatedValue.extend(OriginalWidth); 8641 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 8642 return false; 8643 8644 // Special-case bitfields of width 1: booleans are naturally 0/1, and 8645 // therefore don't strictly fit into a signed bitfield of width 1. 8646 if (FieldWidth == 1 && Value == 1) 8647 return false; 8648 8649 std::string PrettyValue = Value.toString(10); 8650 std::string PrettyTrunc = TruncatedValue.toString(10); 8651 8652 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 8653 << PrettyValue << PrettyTrunc << OriginalInit->getType() 8654 << Init->getSourceRange(); 8655 8656 return true; 8657 } 8658 8659 /// Analyze the given simple or compound assignment for warning-worthy 8660 /// operations. 8661 void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 8662 // Just recurse on the LHS. 8663 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8664 8665 // We want to recurse on the RHS as normal unless we're assigning to 8666 // a bitfield. 8667 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 8668 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 8669 E->getOperatorLoc())) { 8670 // Recurse, ignoring any implicit conversions on the RHS. 8671 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 8672 E->getOperatorLoc()); 8673 } 8674 } 8675 8676 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8677 } 8678 8679 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 8680 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 8681 SourceLocation CContext, unsigned diag, 8682 bool pruneControlFlow = false) { 8683 if (pruneControlFlow) { 8684 S.DiagRuntimeBehavior(E->getExprLoc(), E, 8685 S.PDiag(diag) 8686 << SourceType << T << E->getSourceRange() 8687 << SourceRange(CContext)); 8688 return; 8689 } 8690 S.Diag(E->getExprLoc(), diag) 8691 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 8692 } 8693 8694 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 8695 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 8696 unsigned diag, bool pruneControlFlow = false) { 8697 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 8698 } 8699 8700 8701 /// Diagnose an implicit cast from a floating point value to an integer value. 8702 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 8703 8704 SourceLocation CContext) { 8705 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 8706 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty(); 8707 8708 Expr *InnerE = E->IgnoreParenImpCasts(); 8709 // We also want to warn on, e.g., "int i = -1.234" 8710 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 8711 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 8712 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 8713 8714 const bool IsLiteral = 8715 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 8716 8717 llvm::APFloat Value(0.0); 8718 bool IsConstant = 8719 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 8720 if (!IsConstant) { 8721 return DiagnoseImpCast(S, E, T, CContext, 8722 diag::warn_impcast_float_integer, PruneWarnings); 8723 } 8724 8725 bool isExact = false; 8726 8727 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 8728 T->hasUnsignedIntegerRepresentation()); 8729 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 8730 &isExact) == llvm::APFloat::opOK && 8731 isExact) { 8732 if (IsLiteral) return; 8733 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 8734 PruneWarnings); 8735 } 8736 8737 unsigned DiagID = 0; 8738 if (IsLiteral) { 8739 // Warn on floating point literal to integer. 8740 DiagID = diag::warn_impcast_literal_float_to_integer; 8741 } else if (IntegerValue == 0) { 8742 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 8743 return DiagnoseImpCast(S, E, T, CContext, 8744 diag::warn_impcast_float_integer, PruneWarnings); 8745 } 8746 // Warn on non-zero to zero conversion. 8747 DiagID = diag::warn_impcast_float_to_integer_zero; 8748 } else { 8749 if (IntegerValue.isUnsigned()) { 8750 if (!IntegerValue.isMaxValue()) { 8751 return DiagnoseImpCast(S, E, T, CContext, 8752 diag::warn_impcast_float_integer, PruneWarnings); 8753 } 8754 } else { // IntegerValue.isSigned() 8755 if (!IntegerValue.isMaxSignedValue() && 8756 !IntegerValue.isMinSignedValue()) { 8757 return DiagnoseImpCast(S, E, T, CContext, 8758 diag::warn_impcast_float_integer, PruneWarnings); 8759 } 8760 } 8761 // Warn on evaluatable floating point expression to integer conversion. 8762 DiagID = diag::warn_impcast_float_to_integer; 8763 } 8764 8765 // FIXME: Force the precision of the source value down so we don't print 8766 // digits which are usually useless (we don't really care here if we 8767 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 8768 // would automatically print the shortest representation, but it's a bit 8769 // tricky to implement. 8770 SmallString<16> PrettySourceValue; 8771 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 8772 precision = (precision * 59 + 195) / 196; 8773 Value.toString(PrettySourceValue, precision); 8774 8775 SmallString<16> PrettyTargetValue; 8776 if (IsBool) 8777 PrettyTargetValue = Value.isZero() ? "false" : "true"; 8778 else 8779 IntegerValue.toString(PrettyTargetValue); 8780 8781 if (PruneWarnings) { 8782 S.DiagRuntimeBehavior(E->getExprLoc(), E, 8783 S.PDiag(DiagID) 8784 << E->getType() << T.getUnqualifiedType() 8785 << PrettySourceValue << PrettyTargetValue 8786 << E->getSourceRange() << SourceRange(CContext)); 8787 } else { 8788 S.Diag(E->getExprLoc(), DiagID) 8789 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 8790 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 8791 } 8792 } 8793 8794 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 8795 if (!Range.Width) return "0"; 8796 8797 llvm::APSInt ValueInRange = Value; 8798 ValueInRange.setIsSigned(!Range.NonNegative); 8799 ValueInRange = ValueInRange.trunc(Range.Width); 8800 return ValueInRange.toString(10); 8801 } 8802 8803 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 8804 if (!isa<ImplicitCastExpr>(Ex)) 8805 return false; 8806 8807 Expr *InnerE = Ex->IgnoreParenImpCasts(); 8808 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 8809 const Type *Source = 8810 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 8811 if (Target->isDependentType()) 8812 return false; 8813 8814 const BuiltinType *FloatCandidateBT = 8815 dyn_cast<BuiltinType>(ToBool ? Source : Target); 8816 const Type *BoolCandidateType = ToBool ? Target : Source; 8817 8818 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 8819 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 8820 } 8821 8822 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 8823 SourceLocation CC) { 8824 unsigned NumArgs = TheCall->getNumArgs(); 8825 for (unsigned i = 0; i < NumArgs; ++i) { 8826 Expr *CurrA = TheCall->getArg(i); 8827 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 8828 continue; 8829 8830 bool IsSwapped = ((i > 0) && 8831 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 8832 IsSwapped |= ((i < (NumArgs - 1)) && 8833 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 8834 if (IsSwapped) { 8835 // Warn on this floating-point to bool conversion. 8836 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 8837 CurrA->getType(), CC, 8838 diag::warn_impcast_floating_point_to_bool); 8839 } 8840 } 8841 } 8842 8843 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) { 8844 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 8845 E->getExprLoc())) 8846 return; 8847 8848 // Don't warn on functions which have return type nullptr_t. 8849 if (isa<CallExpr>(E)) 8850 return; 8851 8852 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 8853 const Expr::NullPointerConstantKind NullKind = 8854 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 8855 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 8856 return; 8857 8858 // Return if target type is a safe conversion. 8859 if (T->isAnyPointerType() || T->isBlockPointerType() || 8860 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 8861 return; 8862 8863 SourceLocation Loc = E->getSourceRange().getBegin(); 8864 8865 // Venture through the macro stacks to get to the source of macro arguments. 8866 // The new location is a better location than the complete location that was 8867 // passed in. 8868 while (S.SourceMgr.isMacroArgExpansion(Loc)) 8869 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); 8870 8871 while (S.SourceMgr.isMacroArgExpansion(CC)) 8872 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); 8873 8874 // __null is usually wrapped in a macro. Go up a macro if that is the case. 8875 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 8876 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 8877 Loc, S.SourceMgr, S.getLangOpts()); 8878 if (MacroName == "NULL") 8879 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 8880 } 8881 8882 // Only warn if the null and context location are in the same macro expansion. 8883 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 8884 return; 8885 8886 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 8887 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) 8888 << FixItHint::CreateReplacement(Loc, 8889 S.getFixItZeroLiteralForType(T, Loc)); 8890 } 8891 8892 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 8893 ObjCArrayLiteral *ArrayLiteral); 8894 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 8895 ObjCDictionaryLiteral *DictionaryLiteral); 8896 8897 /// Check a single element within a collection literal against the 8898 /// target element type. 8899 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, 8900 Expr *Element, unsigned ElementKind) { 8901 // Skip a bitcast to 'id' or qualified 'id'. 8902 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 8903 if (ICE->getCastKind() == CK_BitCast && 8904 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 8905 Element = ICE->getSubExpr(); 8906 } 8907 8908 QualType ElementType = Element->getType(); 8909 ExprResult ElementResult(Element); 8910 if (ElementType->getAs<ObjCObjectPointerType>() && 8911 S.CheckSingleAssignmentConstraints(TargetElementType, 8912 ElementResult, 8913 false, false) 8914 != Sema::Compatible) { 8915 S.Diag(Element->getLocStart(), 8916 diag::warn_objc_collection_literal_element) 8917 << ElementType << ElementKind << TargetElementType 8918 << Element->getSourceRange(); 8919 } 8920 8921 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 8922 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 8923 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 8924 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 8925 } 8926 8927 /// Check an Objective-C array literal being converted to the given 8928 /// target type. 8929 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 8930 ObjCArrayLiteral *ArrayLiteral) { 8931 if (!S.NSArrayDecl) 8932 return; 8933 8934 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 8935 if (!TargetObjCPtr) 8936 return; 8937 8938 if (TargetObjCPtr->isUnspecialized() || 8939 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 8940 != S.NSArrayDecl->getCanonicalDecl()) 8941 return; 8942 8943 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 8944 if (TypeArgs.size() != 1) 8945 return; 8946 8947 QualType TargetElementType = TypeArgs[0]; 8948 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 8949 checkObjCCollectionLiteralElement(S, TargetElementType, 8950 ArrayLiteral->getElement(I), 8951 0); 8952 } 8953 } 8954 8955 /// Check an Objective-C dictionary literal being converted to the given 8956 /// target type. 8957 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 8958 ObjCDictionaryLiteral *DictionaryLiteral) { 8959 if (!S.NSDictionaryDecl) 8960 return; 8961 8962 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 8963 if (!TargetObjCPtr) 8964 return; 8965 8966 if (TargetObjCPtr->isUnspecialized() || 8967 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 8968 != S.NSDictionaryDecl->getCanonicalDecl()) 8969 return; 8970 8971 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 8972 if (TypeArgs.size() != 2) 8973 return; 8974 8975 QualType TargetKeyType = TypeArgs[0]; 8976 QualType TargetObjectType = TypeArgs[1]; 8977 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 8978 auto Element = DictionaryLiteral->getKeyValueElement(I); 8979 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 8980 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 8981 } 8982 } 8983 8984 // Helper function to filter out cases for constant width constant conversion. 8985 // Don't warn on char array initialization or for non-decimal values. 8986 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 8987 SourceLocation CC) { 8988 // If initializing from a constant, and the constant starts with '0', 8989 // then it is a binary, octal, or hexadecimal. Allow these constants 8990 // to fill all the bits, even if there is a sign change. 8991 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 8992 const char FirstLiteralCharacter = 8993 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 8994 if (FirstLiteralCharacter == '0') 8995 return false; 8996 } 8997 8998 // If the CC location points to a '{', and the type is char, then assume 8999 // assume it is an array initialization. 9000 if (CC.isValid() && T->isCharType()) { 9001 const char FirstContextCharacter = 9002 S.getSourceManager().getCharacterData(CC)[0]; 9003 if (FirstContextCharacter == '{') 9004 return false; 9005 } 9006 9007 return true; 9008 } 9009 9010 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 9011 SourceLocation CC, bool *ICContext = nullptr) { 9012 if (E->isTypeDependent() || E->isValueDependent()) return; 9013 9014 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 9015 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 9016 if (Source == Target) return; 9017 if (Target->isDependentType()) return; 9018 9019 // If the conversion context location is invalid don't complain. We also 9020 // don't want to emit a warning if the issue occurs from the expansion of 9021 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 9022 // delay this check as long as possible. Once we detect we are in that 9023 // scenario, we just return. 9024 if (CC.isInvalid()) 9025 return; 9026 9027 // Diagnose implicit casts to bool. 9028 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 9029 if (isa<StringLiteral>(E)) 9030 // Warn on string literal to bool. Checks for string literals in logical 9031 // and expressions, for instance, assert(0 && "error here"), are 9032 // prevented by a check in AnalyzeImplicitConversions(). 9033 return DiagnoseImpCast(S, E, T, CC, 9034 diag::warn_impcast_string_literal_to_bool); 9035 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 9036 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 9037 // This covers the literal expressions that evaluate to Objective-C 9038 // objects. 9039 return DiagnoseImpCast(S, E, T, CC, 9040 diag::warn_impcast_objective_c_literal_to_bool); 9041 } 9042 if (Source->isPointerType() || Source->canDecayToPointerType()) { 9043 // Warn on pointer to bool conversion that is always true. 9044 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 9045 SourceRange(CC)); 9046 } 9047 } 9048 9049 // Check implicit casts from Objective-C collection literals to specialized 9050 // collection types, e.g., NSArray<NSString *> *. 9051 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 9052 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 9053 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 9054 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 9055 9056 // Strip vector types. 9057 if (isa<VectorType>(Source)) { 9058 if (!isa<VectorType>(Target)) { 9059 if (S.SourceMgr.isInSystemMacro(CC)) 9060 return; 9061 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 9062 } 9063 9064 // If the vector cast is cast between two vectors of the same size, it is 9065 // a bitcast, not a conversion. 9066 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 9067 return; 9068 9069 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 9070 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 9071 } 9072 if (auto VecTy = dyn_cast<VectorType>(Target)) 9073 Target = VecTy->getElementType().getTypePtr(); 9074 9075 // Strip complex types. 9076 if (isa<ComplexType>(Source)) { 9077 if (!isa<ComplexType>(Target)) { 9078 if (S.SourceMgr.isInSystemMacro(CC)) 9079 return; 9080 9081 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 9082 } 9083 9084 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 9085 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 9086 } 9087 9088 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 9089 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 9090 9091 // If the source is floating point... 9092 if (SourceBT && SourceBT->isFloatingPoint()) { 9093 // ...and the target is floating point... 9094 if (TargetBT && TargetBT->isFloatingPoint()) { 9095 // ...then warn if we're dropping FP rank. 9096 9097 // Builtin FP kinds are ordered by increasing FP rank. 9098 if (SourceBT->getKind() > TargetBT->getKind()) { 9099 // Don't warn about float constants that are precisely 9100 // representable in the target type. 9101 Expr::EvalResult result; 9102 if (E->EvaluateAsRValue(result, S.Context)) { 9103 // Value might be a float, a float vector, or a float complex. 9104 if (IsSameFloatAfterCast(result.Val, 9105 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 9106 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 9107 return; 9108 } 9109 9110 if (S.SourceMgr.isInSystemMacro(CC)) 9111 return; 9112 9113 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 9114 } 9115 // ... or possibly if we're increasing rank, too 9116 else if (TargetBT->getKind() > SourceBT->getKind()) { 9117 if (S.SourceMgr.isInSystemMacro(CC)) 9118 return; 9119 9120 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 9121 } 9122 return; 9123 } 9124 9125 // If the target is integral, always warn. 9126 if (TargetBT && TargetBT->isInteger()) { 9127 if (S.SourceMgr.isInSystemMacro(CC)) 9128 return; 9129 9130 DiagnoseFloatingImpCast(S, E, T, CC); 9131 } 9132 9133 // Detect the case where a call result is converted from floating-point to 9134 // to bool, and the final argument to the call is converted from bool, to 9135 // discover this typo: 9136 // 9137 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 9138 // 9139 // FIXME: This is an incredibly special case; is there some more general 9140 // way to detect this class of misplaced-parentheses bug? 9141 if (Target->isBooleanType() && isa<CallExpr>(E)) { 9142 // Check last argument of function call to see if it is an 9143 // implicit cast from a type matching the type the result 9144 // is being cast to. 9145 CallExpr *CEx = cast<CallExpr>(E); 9146 if (unsigned NumArgs = CEx->getNumArgs()) { 9147 Expr *LastA = CEx->getArg(NumArgs - 1); 9148 Expr *InnerE = LastA->IgnoreParenImpCasts(); 9149 if (isa<ImplicitCastExpr>(LastA) && 9150 InnerE->getType()->isBooleanType()) { 9151 // Warn on this floating-point to bool conversion 9152 DiagnoseImpCast(S, E, T, CC, 9153 diag::warn_impcast_floating_point_to_bool); 9154 } 9155 } 9156 } 9157 return; 9158 } 9159 9160 DiagnoseNullConversion(S, E, T, CC); 9161 9162 S.DiscardMisalignedMemberAddress(Target, E); 9163 9164 if (!Source->isIntegerType() || !Target->isIntegerType()) 9165 return; 9166 9167 // TODO: remove this early return once the false positives for constant->bool 9168 // in templates, macros, etc, are reduced or removed. 9169 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 9170 return; 9171 9172 IntRange SourceRange = GetExprRange(S.Context, E); 9173 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 9174 9175 if (SourceRange.Width > TargetRange.Width) { 9176 // If the source is a constant, use a default-on diagnostic. 9177 // TODO: this should happen for bitfield stores, too. 9178 llvm::APSInt Value(32); 9179 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 9180 if (S.SourceMgr.isInSystemMacro(CC)) 9181 return; 9182 9183 std::string PrettySourceValue = Value.toString(10); 9184 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9185 9186 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9187 S.PDiag(diag::warn_impcast_integer_precision_constant) 9188 << PrettySourceValue << PrettyTargetValue 9189 << E->getType() << T << E->getSourceRange() 9190 << clang::SourceRange(CC)); 9191 return; 9192 } 9193 9194 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 9195 if (S.SourceMgr.isInSystemMacro(CC)) 9196 return; 9197 9198 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 9199 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 9200 /* pruneControlFlow */ true); 9201 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 9202 } 9203 9204 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 9205 SourceRange.NonNegative && Source->isSignedIntegerType()) { 9206 // Warn when doing a signed to signed conversion, warn if the positive 9207 // source value is exactly the width of the target type, which will 9208 // cause a negative value to be stored. 9209 9210 llvm::APSInt Value; 9211 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 9212 !S.SourceMgr.isInSystemMacro(CC)) { 9213 if (isSameWidthConstantConversion(S, E, T, CC)) { 9214 std::string PrettySourceValue = Value.toString(10); 9215 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9216 9217 S.DiagRuntimeBehavior( 9218 E->getExprLoc(), E, 9219 S.PDiag(diag::warn_impcast_integer_precision_constant) 9220 << PrettySourceValue << PrettyTargetValue << E->getType() << T 9221 << E->getSourceRange() << clang::SourceRange(CC)); 9222 return; 9223 } 9224 } 9225 9226 // Fall through for non-constants to give a sign conversion warning. 9227 } 9228 9229 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 9230 (!TargetRange.NonNegative && SourceRange.NonNegative && 9231 SourceRange.Width == TargetRange.Width)) { 9232 if (S.SourceMgr.isInSystemMacro(CC)) 9233 return; 9234 9235 unsigned DiagID = diag::warn_impcast_integer_sign; 9236 9237 // Traditionally, gcc has warned about this under -Wsign-compare. 9238 // We also want to warn about it in -Wconversion. 9239 // So if -Wconversion is off, use a completely identical diagnostic 9240 // in the sign-compare group. 9241 // The conditional-checking code will 9242 if (ICContext) { 9243 DiagID = diag::warn_impcast_integer_sign_conditional; 9244 *ICContext = true; 9245 } 9246 9247 return DiagnoseImpCast(S, E, T, CC, DiagID); 9248 } 9249 9250 // Diagnose conversions between different enumeration types. 9251 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 9252 // type, to give us better diagnostics. 9253 QualType SourceType = E->getType(); 9254 if (!S.getLangOpts().CPlusPlus) { 9255 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9256 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 9257 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 9258 SourceType = S.Context.getTypeDeclType(Enum); 9259 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 9260 } 9261 } 9262 9263 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 9264 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 9265 if (SourceEnum->getDecl()->hasNameForLinkage() && 9266 TargetEnum->getDecl()->hasNameForLinkage() && 9267 SourceEnum != TargetEnum) { 9268 if (S.SourceMgr.isInSystemMacro(CC)) 9269 return; 9270 9271 return DiagnoseImpCast(S, E, SourceType, T, CC, 9272 diag::warn_impcast_different_enum_types); 9273 } 9274 } 9275 9276 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9277 SourceLocation CC, QualType T); 9278 9279 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 9280 SourceLocation CC, bool &ICContext) { 9281 E = E->IgnoreParenImpCasts(); 9282 9283 if (isa<ConditionalOperator>(E)) 9284 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 9285 9286 AnalyzeImplicitConversions(S, E, CC); 9287 if (E->getType() != T) 9288 return CheckImplicitConversion(S, E, T, CC, &ICContext); 9289 } 9290 9291 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9292 SourceLocation CC, QualType T) { 9293 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 9294 9295 bool Suspicious = false; 9296 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 9297 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 9298 9299 // If -Wconversion would have warned about either of the candidates 9300 // for a signedness conversion to the context type... 9301 if (!Suspicious) return; 9302 9303 // ...but it's currently ignored... 9304 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 9305 return; 9306 9307 // ...then check whether it would have warned about either of the 9308 // candidates for a signedness conversion to the condition type. 9309 if (E->getType() == T) return; 9310 9311 Suspicious = false; 9312 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 9313 E->getType(), CC, &Suspicious); 9314 if (!Suspicious) 9315 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 9316 E->getType(), CC, &Suspicious); 9317 } 9318 9319 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9320 /// Input argument E is a logical expression. 9321 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 9322 if (S.getLangOpts().Bool) 9323 return; 9324 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 9325 } 9326 9327 /// AnalyzeImplicitConversions - Find and report any interesting 9328 /// implicit conversions in the given expression. There are a couple 9329 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 9330 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 9331 QualType T = OrigE->getType(); 9332 Expr *E = OrigE->IgnoreParenImpCasts(); 9333 9334 if (E->isTypeDependent() || E->isValueDependent()) 9335 return; 9336 9337 // For conditional operators, we analyze the arguments as if they 9338 // were being fed directly into the output. 9339 if (isa<ConditionalOperator>(E)) { 9340 ConditionalOperator *CO = cast<ConditionalOperator>(E); 9341 CheckConditionalOperator(S, CO, CC, T); 9342 return; 9343 } 9344 9345 // Check implicit argument conversions for function calls. 9346 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 9347 CheckImplicitArgumentConversions(S, Call, CC); 9348 9349 // Go ahead and check any implicit conversions we might have skipped. 9350 // The non-canonical typecheck is just an optimization; 9351 // CheckImplicitConversion will filter out dead implicit conversions. 9352 if (E->getType() != T) 9353 CheckImplicitConversion(S, E, T, CC); 9354 9355 // Now continue drilling into this expression. 9356 9357 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 9358 // The bound subexpressions in a PseudoObjectExpr are not reachable 9359 // as transitive children. 9360 // FIXME: Use a more uniform representation for this. 9361 for (auto *SE : POE->semantics()) 9362 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 9363 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 9364 } 9365 9366 // Skip past explicit casts. 9367 if (isa<ExplicitCastExpr>(E)) { 9368 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 9369 return AnalyzeImplicitConversions(S, E, CC); 9370 } 9371 9372 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9373 // Do a somewhat different check with comparison operators. 9374 if (BO->isComparisonOp()) 9375 return AnalyzeComparison(S, BO); 9376 9377 // And with simple assignments. 9378 if (BO->getOpcode() == BO_Assign) 9379 return AnalyzeAssignment(S, BO); 9380 } 9381 9382 // These break the otherwise-useful invariant below. Fortunately, 9383 // we don't really need to recurse into them, because any internal 9384 // expressions should have been analyzed already when they were 9385 // built into statements. 9386 if (isa<StmtExpr>(E)) return; 9387 9388 // Don't descend into unevaluated contexts. 9389 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 9390 9391 // Now just recurse over the expression's children. 9392 CC = E->getExprLoc(); 9393 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 9394 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 9395 for (Stmt *SubStmt : E->children()) { 9396 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 9397 if (!ChildExpr) 9398 continue; 9399 9400 if (IsLogicalAndOperator && 9401 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 9402 // Ignore checking string literals that are in logical and operators. 9403 // This is a common pattern for asserts. 9404 continue; 9405 AnalyzeImplicitConversions(S, ChildExpr, CC); 9406 } 9407 9408 if (BO && BO->isLogicalOp()) { 9409 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 9410 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9411 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9412 9413 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 9414 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9415 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9416 } 9417 9418 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 9419 if (U->getOpcode() == UO_LNot) 9420 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 9421 } 9422 9423 } // end anonymous namespace 9424 9425 /// Diagnose integer type and any valid implicit convertion to it. 9426 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 9427 // Taking into account implicit conversions, 9428 // allow any integer. 9429 if (!E->getType()->isIntegerType()) { 9430 S.Diag(E->getLocStart(), 9431 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 9432 return true; 9433 } 9434 // Potentially emit standard warnings for implicit conversions if enabled 9435 // using -Wconversion. 9436 CheckImplicitConversion(S, E, IntT, E->getLocStart()); 9437 return false; 9438 } 9439 9440 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 9441 // Returns true when emitting a warning about taking the address of a reference. 9442 static bool CheckForReference(Sema &SemaRef, const Expr *E, 9443 const PartialDiagnostic &PD) { 9444 E = E->IgnoreParenImpCasts(); 9445 9446 const FunctionDecl *FD = nullptr; 9447 9448 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9449 if (!DRE->getDecl()->getType()->isReferenceType()) 9450 return false; 9451 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9452 if (!M->getMemberDecl()->getType()->isReferenceType()) 9453 return false; 9454 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 9455 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 9456 return false; 9457 FD = Call->getDirectCallee(); 9458 } else { 9459 return false; 9460 } 9461 9462 SemaRef.Diag(E->getExprLoc(), PD); 9463 9464 // If possible, point to location of function. 9465 if (FD) { 9466 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 9467 } 9468 9469 return true; 9470 } 9471 9472 // Returns true if the SourceLocation is expanded from any macro body. 9473 // Returns false if the SourceLocation is invalid, is from not in a macro 9474 // expansion, or is from expanded from a top-level macro argument. 9475 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 9476 if (Loc.isInvalid()) 9477 return false; 9478 9479 while (Loc.isMacroID()) { 9480 if (SM.isMacroBodyExpansion(Loc)) 9481 return true; 9482 Loc = SM.getImmediateMacroCallerLoc(Loc); 9483 } 9484 9485 return false; 9486 } 9487 9488 /// \brief Diagnose pointers that are always non-null. 9489 /// \param E the expression containing the pointer 9490 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 9491 /// compared to a null pointer 9492 /// \param IsEqual True when the comparison is equal to a null pointer 9493 /// \param Range Extra SourceRange to highlight in the diagnostic 9494 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 9495 Expr::NullPointerConstantKind NullKind, 9496 bool IsEqual, SourceRange Range) { 9497 if (!E) 9498 return; 9499 9500 // Don't warn inside macros. 9501 if (E->getExprLoc().isMacroID()) { 9502 const SourceManager &SM = getSourceManager(); 9503 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 9504 IsInAnyMacroBody(SM, Range.getBegin())) 9505 return; 9506 } 9507 E = E->IgnoreImpCasts(); 9508 9509 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 9510 9511 if (isa<CXXThisExpr>(E)) { 9512 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 9513 : diag::warn_this_bool_conversion; 9514 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 9515 return; 9516 } 9517 9518 bool IsAddressOf = false; 9519 9520 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9521 if (UO->getOpcode() != UO_AddrOf) 9522 return; 9523 IsAddressOf = true; 9524 E = UO->getSubExpr(); 9525 } 9526 9527 if (IsAddressOf) { 9528 unsigned DiagID = IsCompare 9529 ? diag::warn_address_of_reference_null_compare 9530 : diag::warn_address_of_reference_bool_conversion; 9531 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 9532 << IsEqual; 9533 if (CheckForReference(*this, E, PD)) { 9534 return; 9535 } 9536 } 9537 9538 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 9539 bool IsParam = isa<NonNullAttr>(NonnullAttr); 9540 std::string Str; 9541 llvm::raw_string_ostream S(Str); 9542 E->printPretty(S, nullptr, getPrintingPolicy()); 9543 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 9544 : diag::warn_cast_nonnull_to_bool; 9545 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 9546 << E->getSourceRange() << Range << IsEqual; 9547 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 9548 }; 9549 9550 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 9551 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 9552 if (auto *Callee = Call->getDirectCallee()) { 9553 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 9554 ComplainAboutNonnullParamOrCall(A); 9555 return; 9556 } 9557 } 9558 } 9559 9560 // Expect to find a single Decl. Skip anything more complicated. 9561 ValueDecl *D = nullptr; 9562 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 9563 D = R->getDecl(); 9564 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9565 D = M->getMemberDecl(); 9566 } 9567 9568 // Weak Decls can be null. 9569 if (!D || D->isWeak()) 9570 return; 9571 9572 // Check for parameter decl with nonnull attribute 9573 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 9574 if (getCurFunction() && 9575 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 9576 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 9577 ComplainAboutNonnullParamOrCall(A); 9578 return; 9579 } 9580 9581 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 9582 auto ParamIter = llvm::find(FD->parameters(), PV); 9583 assert(ParamIter != FD->param_end()); 9584 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 9585 9586 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 9587 if (!NonNull->args_size()) { 9588 ComplainAboutNonnullParamOrCall(NonNull); 9589 return; 9590 } 9591 9592 for (unsigned ArgNo : NonNull->args()) { 9593 if (ArgNo == ParamNo) { 9594 ComplainAboutNonnullParamOrCall(NonNull); 9595 return; 9596 } 9597 } 9598 } 9599 } 9600 } 9601 } 9602 9603 QualType T = D->getType(); 9604 const bool IsArray = T->isArrayType(); 9605 const bool IsFunction = T->isFunctionType(); 9606 9607 // Address of function is used to silence the function warning. 9608 if (IsAddressOf && IsFunction) { 9609 return; 9610 } 9611 9612 // Found nothing. 9613 if (!IsAddressOf && !IsFunction && !IsArray) 9614 return; 9615 9616 // Pretty print the expression for the diagnostic. 9617 std::string Str; 9618 llvm::raw_string_ostream S(Str); 9619 E->printPretty(S, nullptr, getPrintingPolicy()); 9620 9621 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 9622 : diag::warn_impcast_pointer_to_bool; 9623 enum { 9624 AddressOf, 9625 FunctionPointer, 9626 ArrayPointer 9627 } DiagType; 9628 if (IsAddressOf) 9629 DiagType = AddressOf; 9630 else if (IsFunction) 9631 DiagType = FunctionPointer; 9632 else if (IsArray) 9633 DiagType = ArrayPointer; 9634 else 9635 llvm_unreachable("Could not determine diagnostic."); 9636 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 9637 << Range << IsEqual; 9638 9639 if (!IsFunction) 9640 return; 9641 9642 // Suggest '&' to silence the function warning. 9643 Diag(E->getExprLoc(), diag::note_function_warning_silence) 9644 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 9645 9646 // Check to see if '()' fixit should be emitted. 9647 QualType ReturnType; 9648 UnresolvedSet<4> NonTemplateOverloads; 9649 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 9650 if (ReturnType.isNull()) 9651 return; 9652 9653 if (IsCompare) { 9654 // There are two cases here. If there is null constant, the only suggest 9655 // for a pointer return type. If the null is 0, then suggest if the return 9656 // type is a pointer or an integer type. 9657 if (!ReturnType->isPointerType()) { 9658 if (NullKind == Expr::NPCK_ZeroExpression || 9659 NullKind == Expr::NPCK_ZeroLiteral) { 9660 if (!ReturnType->isIntegerType()) 9661 return; 9662 } else { 9663 return; 9664 } 9665 } 9666 } else { // !IsCompare 9667 // For function to bool, only suggest if the function pointer has bool 9668 // return type. 9669 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 9670 return; 9671 } 9672 Diag(E->getExprLoc(), diag::note_function_to_function_call) 9673 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 9674 } 9675 9676 /// Diagnoses "dangerous" implicit conversions within the given 9677 /// expression (which is a full expression). Implements -Wconversion 9678 /// and -Wsign-compare. 9679 /// 9680 /// \param CC the "context" location of the implicit conversion, i.e. 9681 /// the most location of the syntactic entity requiring the implicit 9682 /// conversion 9683 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 9684 // Don't diagnose in unevaluated contexts. 9685 if (isUnevaluatedContext()) 9686 return; 9687 9688 // Don't diagnose for value- or type-dependent expressions. 9689 if (E->isTypeDependent() || E->isValueDependent()) 9690 return; 9691 9692 // Check for array bounds violations in cases where the check isn't triggered 9693 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 9694 // ArraySubscriptExpr is on the RHS of a variable initialization. 9695 CheckArrayAccess(E); 9696 9697 // This is not the right CC for (e.g.) a variable initialization. 9698 AnalyzeImplicitConversions(*this, E, CC); 9699 } 9700 9701 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9702 /// Input argument E is a logical expression. 9703 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 9704 ::CheckBoolLikeConversion(*this, E, CC); 9705 } 9706 9707 /// Diagnose when expression is an integer constant expression and its evaluation 9708 /// results in integer overflow 9709 void Sema::CheckForIntOverflow (Expr *E) { 9710 // Use a work list to deal with nested struct initializers. 9711 SmallVector<Expr *, 2> Exprs(1, E); 9712 9713 do { 9714 Expr *E = Exprs.pop_back_val(); 9715 9716 if (isa<BinaryOperator>(E->IgnoreParenCasts())) { 9717 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 9718 continue; 9719 } 9720 9721 if (auto InitList = dyn_cast<InitListExpr>(E)) 9722 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 9723 } while (!Exprs.empty()); 9724 } 9725 9726 namespace { 9727 /// \brief Visitor for expressions which looks for unsequenced operations on the 9728 /// same object. 9729 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 9730 typedef EvaluatedExprVisitor<SequenceChecker> Base; 9731 9732 /// \brief A tree of sequenced regions within an expression. Two regions are 9733 /// unsequenced if one is an ancestor or a descendent of the other. When we 9734 /// finish processing an expression with sequencing, such as a comma 9735 /// expression, we fold its tree nodes into its parent, since they are 9736 /// unsequenced with respect to nodes we will visit later. 9737 class SequenceTree { 9738 struct Value { 9739 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 9740 unsigned Parent : 31; 9741 unsigned Merged : 1; 9742 }; 9743 SmallVector<Value, 8> Values; 9744 9745 public: 9746 /// \brief A region within an expression which may be sequenced with respect 9747 /// to some other region. 9748 class Seq { 9749 explicit Seq(unsigned N) : Index(N) {} 9750 unsigned Index; 9751 friend class SequenceTree; 9752 public: 9753 Seq() : Index(0) {} 9754 }; 9755 9756 SequenceTree() { Values.push_back(Value(0)); } 9757 Seq root() const { return Seq(0); } 9758 9759 /// \brief Create a new sequence of operations, which is an unsequenced 9760 /// subset of \p Parent. This sequence of operations is sequenced with 9761 /// respect to other children of \p Parent. 9762 Seq allocate(Seq Parent) { 9763 Values.push_back(Value(Parent.Index)); 9764 return Seq(Values.size() - 1); 9765 } 9766 9767 /// \brief Merge a sequence of operations into its parent. 9768 void merge(Seq S) { 9769 Values[S.Index].Merged = true; 9770 } 9771 9772 /// \brief Determine whether two operations are unsequenced. This operation 9773 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 9774 /// should have been merged into its parent as appropriate. 9775 bool isUnsequenced(Seq Cur, Seq Old) { 9776 unsigned C = representative(Cur.Index); 9777 unsigned Target = representative(Old.Index); 9778 while (C >= Target) { 9779 if (C == Target) 9780 return true; 9781 C = Values[C].Parent; 9782 } 9783 return false; 9784 } 9785 9786 private: 9787 /// \brief Pick a representative for a sequence. 9788 unsigned representative(unsigned K) { 9789 if (Values[K].Merged) 9790 // Perform path compression as we go. 9791 return Values[K].Parent = representative(Values[K].Parent); 9792 return K; 9793 } 9794 }; 9795 9796 /// An object for which we can track unsequenced uses. 9797 typedef NamedDecl *Object; 9798 9799 /// Different flavors of object usage which we track. We only track the 9800 /// least-sequenced usage of each kind. 9801 enum UsageKind { 9802 /// A read of an object. Multiple unsequenced reads are OK. 9803 UK_Use, 9804 /// A modification of an object which is sequenced before the value 9805 /// computation of the expression, such as ++n in C++. 9806 UK_ModAsValue, 9807 /// A modification of an object which is not sequenced before the value 9808 /// computation of the expression, such as n++. 9809 UK_ModAsSideEffect, 9810 9811 UK_Count = UK_ModAsSideEffect + 1 9812 }; 9813 9814 struct Usage { 9815 Usage() : Use(nullptr), Seq() {} 9816 Expr *Use; 9817 SequenceTree::Seq Seq; 9818 }; 9819 9820 struct UsageInfo { 9821 UsageInfo() : Diagnosed(false) {} 9822 Usage Uses[UK_Count]; 9823 /// Have we issued a diagnostic for this variable already? 9824 bool Diagnosed; 9825 }; 9826 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 9827 9828 Sema &SemaRef; 9829 /// Sequenced regions within the expression. 9830 SequenceTree Tree; 9831 /// Declaration modifications and references which we have seen. 9832 UsageInfoMap UsageMap; 9833 /// The region we are currently within. 9834 SequenceTree::Seq Region; 9835 /// Filled in with declarations which were modified as a side-effect 9836 /// (that is, post-increment operations). 9837 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 9838 /// Expressions to check later. We defer checking these to reduce 9839 /// stack usage. 9840 SmallVectorImpl<Expr *> &WorkList; 9841 9842 /// RAII object wrapping the visitation of a sequenced subexpression of an 9843 /// expression. At the end of this process, the side-effects of the evaluation 9844 /// become sequenced with respect to the value computation of the result, so 9845 /// we downgrade any UK_ModAsSideEffect within the evaluation to 9846 /// UK_ModAsValue. 9847 struct SequencedSubexpression { 9848 SequencedSubexpression(SequenceChecker &Self) 9849 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 9850 Self.ModAsSideEffect = &ModAsSideEffect; 9851 } 9852 ~SequencedSubexpression() { 9853 for (auto &M : llvm::reverse(ModAsSideEffect)) { 9854 UsageInfo &U = Self.UsageMap[M.first]; 9855 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 9856 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 9857 SideEffectUsage = M.second; 9858 } 9859 Self.ModAsSideEffect = OldModAsSideEffect; 9860 } 9861 9862 SequenceChecker &Self; 9863 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 9864 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 9865 }; 9866 9867 /// RAII object wrapping the visitation of a subexpression which we might 9868 /// choose to evaluate as a constant. If any subexpression is evaluated and 9869 /// found to be non-constant, this allows us to suppress the evaluation of 9870 /// the outer expression. 9871 class EvaluationTracker { 9872 public: 9873 EvaluationTracker(SequenceChecker &Self) 9874 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 9875 Self.EvalTracker = this; 9876 } 9877 ~EvaluationTracker() { 9878 Self.EvalTracker = Prev; 9879 if (Prev) 9880 Prev->EvalOK &= EvalOK; 9881 } 9882 9883 bool evaluate(const Expr *E, bool &Result) { 9884 if (!EvalOK || E->isValueDependent()) 9885 return false; 9886 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 9887 return EvalOK; 9888 } 9889 9890 private: 9891 SequenceChecker &Self; 9892 EvaluationTracker *Prev; 9893 bool EvalOK; 9894 } *EvalTracker; 9895 9896 /// \brief Find the object which is produced by the specified expression, 9897 /// if any. 9898 Object getObject(Expr *E, bool Mod) const { 9899 E = E->IgnoreParenCasts(); 9900 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9901 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 9902 return getObject(UO->getSubExpr(), Mod); 9903 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9904 if (BO->getOpcode() == BO_Comma) 9905 return getObject(BO->getRHS(), Mod); 9906 if (Mod && BO->isAssignmentOp()) 9907 return getObject(BO->getLHS(), Mod); 9908 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9909 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 9910 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 9911 return ME->getMemberDecl(); 9912 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9913 // FIXME: If this is a reference, map through to its value. 9914 return DRE->getDecl(); 9915 return nullptr; 9916 } 9917 9918 /// \brief Note that an object was modified or used by an expression. 9919 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 9920 Usage &U = UI.Uses[UK]; 9921 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 9922 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 9923 ModAsSideEffect->push_back(std::make_pair(O, U)); 9924 U.Use = Ref; 9925 U.Seq = Region; 9926 } 9927 } 9928 /// \brief Check whether a modification or use conflicts with a prior usage. 9929 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 9930 bool IsModMod) { 9931 if (UI.Diagnosed) 9932 return; 9933 9934 const Usage &U = UI.Uses[OtherKind]; 9935 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 9936 return; 9937 9938 Expr *Mod = U.Use; 9939 Expr *ModOrUse = Ref; 9940 if (OtherKind == UK_Use) 9941 std::swap(Mod, ModOrUse); 9942 9943 SemaRef.Diag(Mod->getExprLoc(), 9944 IsModMod ? diag::warn_unsequenced_mod_mod 9945 : diag::warn_unsequenced_mod_use) 9946 << O << SourceRange(ModOrUse->getExprLoc()); 9947 UI.Diagnosed = true; 9948 } 9949 9950 void notePreUse(Object O, Expr *Use) { 9951 UsageInfo &U = UsageMap[O]; 9952 // Uses conflict with other modifications. 9953 checkUsage(O, U, Use, UK_ModAsValue, false); 9954 } 9955 void notePostUse(Object O, Expr *Use) { 9956 UsageInfo &U = UsageMap[O]; 9957 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 9958 addUsage(U, O, Use, UK_Use); 9959 } 9960 9961 void notePreMod(Object O, Expr *Mod) { 9962 UsageInfo &U = UsageMap[O]; 9963 // Modifications conflict with other modifications and with uses. 9964 checkUsage(O, U, Mod, UK_ModAsValue, true); 9965 checkUsage(O, U, Mod, UK_Use, false); 9966 } 9967 void notePostMod(Object O, Expr *Use, UsageKind UK) { 9968 UsageInfo &U = UsageMap[O]; 9969 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 9970 addUsage(U, O, Use, UK); 9971 } 9972 9973 public: 9974 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 9975 : Base(S.Context), SemaRef(S), Region(Tree.root()), 9976 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 9977 Visit(E); 9978 } 9979 9980 void VisitStmt(Stmt *S) { 9981 // Skip all statements which aren't expressions for now. 9982 } 9983 9984 void VisitExpr(Expr *E) { 9985 // By default, just recurse to evaluated subexpressions. 9986 Base::VisitStmt(E); 9987 } 9988 9989 void VisitCastExpr(CastExpr *E) { 9990 Object O = Object(); 9991 if (E->getCastKind() == CK_LValueToRValue) 9992 O = getObject(E->getSubExpr(), false); 9993 9994 if (O) 9995 notePreUse(O, E); 9996 VisitExpr(E); 9997 if (O) 9998 notePostUse(O, E); 9999 } 10000 10001 void VisitBinComma(BinaryOperator *BO) { 10002 // C++11 [expr.comma]p1: 10003 // Every value computation and side effect associated with the left 10004 // expression is sequenced before every value computation and side 10005 // effect associated with the right expression. 10006 SequenceTree::Seq LHS = Tree.allocate(Region); 10007 SequenceTree::Seq RHS = Tree.allocate(Region); 10008 SequenceTree::Seq OldRegion = Region; 10009 10010 { 10011 SequencedSubexpression SeqLHS(*this); 10012 Region = LHS; 10013 Visit(BO->getLHS()); 10014 } 10015 10016 Region = RHS; 10017 Visit(BO->getRHS()); 10018 10019 Region = OldRegion; 10020 10021 // Forget that LHS and RHS are sequenced. They are both unsequenced 10022 // with respect to other stuff. 10023 Tree.merge(LHS); 10024 Tree.merge(RHS); 10025 } 10026 10027 void VisitBinAssign(BinaryOperator *BO) { 10028 // The modification is sequenced after the value computation of the LHS 10029 // and RHS, so check it before inspecting the operands and update the 10030 // map afterwards. 10031 Object O = getObject(BO->getLHS(), true); 10032 if (!O) 10033 return VisitExpr(BO); 10034 10035 notePreMod(O, BO); 10036 10037 // C++11 [expr.ass]p7: 10038 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 10039 // only once. 10040 // 10041 // Therefore, for a compound assignment operator, O is considered used 10042 // everywhere except within the evaluation of E1 itself. 10043 if (isa<CompoundAssignOperator>(BO)) 10044 notePreUse(O, BO); 10045 10046 Visit(BO->getLHS()); 10047 10048 if (isa<CompoundAssignOperator>(BO)) 10049 notePostUse(O, BO); 10050 10051 Visit(BO->getRHS()); 10052 10053 // C++11 [expr.ass]p1: 10054 // the assignment is sequenced [...] before the value computation of the 10055 // assignment expression. 10056 // C11 6.5.16/3 has no such rule. 10057 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10058 : UK_ModAsSideEffect); 10059 } 10060 10061 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 10062 VisitBinAssign(CAO); 10063 } 10064 10065 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10066 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10067 void VisitUnaryPreIncDec(UnaryOperator *UO) { 10068 Object O = getObject(UO->getSubExpr(), true); 10069 if (!O) 10070 return VisitExpr(UO); 10071 10072 notePreMod(O, UO); 10073 Visit(UO->getSubExpr()); 10074 // C++11 [expr.pre.incr]p1: 10075 // the expression ++x is equivalent to x+=1 10076 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10077 : UK_ModAsSideEffect); 10078 } 10079 10080 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10081 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10082 void VisitUnaryPostIncDec(UnaryOperator *UO) { 10083 Object O = getObject(UO->getSubExpr(), true); 10084 if (!O) 10085 return VisitExpr(UO); 10086 10087 notePreMod(O, UO); 10088 Visit(UO->getSubExpr()); 10089 notePostMod(O, UO, UK_ModAsSideEffect); 10090 } 10091 10092 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 10093 void VisitBinLOr(BinaryOperator *BO) { 10094 // The side-effects of the LHS of an '&&' are sequenced before the 10095 // value computation of the RHS, and hence before the value computation 10096 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 10097 // as if they were unconditionally sequenced. 10098 EvaluationTracker Eval(*this); 10099 { 10100 SequencedSubexpression Sequenced(*this); 10101 Visit(BO->getLHS()); 10102 } 10103 10104 bool Result; 10105 if (Eval.evaluate(BO->getLHS(), Result)) { 10106 if (!Result) 10107 Visit(BO->getRHS()); 10108 } else { 10109 // Check for unsequenced operations in the RHS, treating it as an 10110 // entirely separate evaluation. 10111 // 10112 // FIXME: If there are operations in the RHS which are unsequenced 10113 // with respect to operations outside the RHS, and those operations 10114 // are unconditionally evaluated, diagnose them. 10115 WorkList.push_back(BO->getRHS()); 10116 } 10117 } 10118 void VisitBinLAnd(BinaryOperator *BO) { 10119 EvaluationTracker Eval(*this); 10120 { 10121 SequencedSubexpression Sequenced(*this); 10122 Visit(BO->getLHS()); 10123 } 10124 10125 bool Result; 10126 if (Eval.evaluate(BO->getLHS(), Result)) { 10127 if (Result) 10128 Visit(BO->getRHS()); 10129 } else { 10130 WorkList.push_back(BO->getRHS()); 10131 } 10132 } 10133 10134 // Only visit the condition, unless we can be sure which subexpression will 10135 // be chosen. 10136 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 10137 EvaluationTracker Eval(*this); 10138 { 10139 SequencedSubexpression Sequenced(*this); 10140 Visit(CO->getCond()); 10141 } 10142 10143 bool Result; 10144 if (Eval.evaluate(CO->getCond(), Result)) 10145 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 10146 else { 10147 WorkList.push_back(CO->getTrueExpr()); 10148 WorkList.push_back(CO->getFalseExpr()); 10149 } 10150 } 10151 10152 void VisitCallExpr(CallExpr *CE) { 10153 // C++11 [intro.execution]p15: 10154 // When calling a function [...], every value computation and side effect 10155 // associated with any argument expression, or with the postfix expression 10156 // designating the called function, is sequenced before execution of every 10157 // expression or statement in the body of the function [and thus before 10158 // the value computation of its result]. 10159 SequencedSubexpression Sequenced(*this); 10160 Base::VisitCallExpr(CE); 10161 10162 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 10163 } 10164 10165 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 10166 // This is a call, so all subexpressions are sequenced before the result. 10167 SequencedSubexpression Sequenced(*this); 10168 10169 if (!CCE->isListInitialization()) 10170 return VisitExpr(CCE); 10171 10172 // In C++11, list initializations are sequenced. 10173 SmallVector<SequenceTree::Seq, 32> Elts; 10174 SequenceTree::Seq Parent = Region; 10175 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 10176 E = CCE->arg_end(); 10177 I != E; ++I) { 10178 Region = Tree.allocate(Parent); 10179 Elts.push_back(Region); 10180 Visit(*I); 10181 } 10182 10183 // Forget that the initializers are sequenced. 10184 Region = Parent; 10185 for (unsigned I = 0; I < Elts.size(); ++I) 10186 Tree.merge(Elts[I]); 10187 } 10188 10189 void VisitInitListExpr(InitListExpr *ILE) { 10190 if (!SemaRef.getLangOpts().CPlusPlus11) 10191 return VisitExpr(ILE); 10192 10193 // In C++11, list initializations are sequenced. 10194 SmallVector<SequenceTree::Seq, 32> Elts; 10195 SequenceTree::Seq Parent = Region; 10196 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 10197 Expr *E = ILE->getInit(I); 10198 if (!E) continue; 10199 Region = Tree.allocate(Parent); 10200 Elts.push_back(Region); 10201 Visit(E); 10202 } 10203 10204 // Forget that the initializers are sequenced. 10205 Region = Parent; 10206 for (unsigned I = 0; I < Elts.size(); ++I) 10207 Tree.merge(Elts[I]); 10208 } 10209 }; 10210 } // end anonymous namespace 10211 10212 void Sema::CheckUnsequencedOperations(Expr *E) { 10213 SmallVector<Expr *, 8> WorkList; 10214 WorkList.push_back(E); 10215 while (!WorkList.empty()) { 10216 Expr *Item = WorkList.pop_back_val(); 10217 SequenceChecker(*this, Item, WorkList); 10218 } 10219 } 10220 10221 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 10222 bool IsConstexpr) { 10223 CheckImplicitConversions(E, CheckLoc); 10224 if (!E->isInstantiationDependent()) 10225 CheckUnsequencedOperations(E); 10226 if (!IsConstexpr && !E->isValueDependent()) 10227 CheckForIntOverflow(E); 10228 DiagnoseMisalignedMembers(); 10229 } 10230 10231 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 10232 FieldDecl *BitField, 10233 Expr *Init) { 10234 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 10235 } 10236 10237 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 10238 SourceLocation Loc) { 10239 if (!PType->isVariablyModifiedType()) 10240 return; 10241 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 10242 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 10243 return; 10244 } 10245 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 10246 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 10247 return; 10248 } 10249 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 10250 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 10251 return; 10252 } 10253 10254 const ArrayType *AT = S.Context.getAsArrayType(PType); 10255 if (!AT) 10256 return; 10257 10258 if (AT->getSizeModifier() != ArrayType::Star) { 10259 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 10260 return; 10261 } 10262 10263 S.Diag(Loc, diag::err_array_star_in_function_definition); 10264 } 10265 10266 /// CheckParmsForFunctionDef - Check that the parameters of the given 10267 /// function are appropriate for the definition of a function. This 10268 /// takes care of any checks that cannot be performed on the 10269 /// declaration itself, e.g., that the types of each of the function 10270 /// parameters are complete. 10271 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 10272 bool CheckParameterNames) { 10273 bool HasInvalidParm = false; 10274 for (ParmVarDecl *Param : Parameters) { 10275 // C99 6.7.5.3p4: the parameters in a parameter type list in a 10276 // function declarator that is part of a function definition of 10277 // that function shall not have incomplete type. 10278 // 10279 // This is also C++ [dcl.fct]p6. 10280 if (!Param->isInvalidDecl() && 10281 RequireCompleteType(Param->getLocation(), Param->getType(), 10282 diag::err_typecheck_decl_incomplete_type)) { 10283 Param->setInvalidDecl(); 10284 HasInvalidParm = true; 10285 } 10286 10287 // C99 6.9.1p5: If the declarator includes a parameter type list, the 10288 // declaration of each parameter shall include an identifier. 10289 if (CheckParameterNames && 10290 Param->getIdentifier() == nullptr && 10291 !Param->isImplicit() && 10292 !getLangOpts().CPlusPlus) 10293 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10294 10295 // C99 6.7.5.3p12: 10296 // If the function declarator is not part of a definition of that 10297 // function, parameters may have incomplete type and may use the [*] 10298 // notation in their sequences of declarator specifiers to specify 10299 // variable length array types. 10300 QualType PType = Param->getOriginalType(); 10301 // FIXME: This diagnostic should point the '[*]' if source-location 10302 // information is added for it. 10303 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 10304 10305 // MSVC destroys objects passed by value in the callee. Therefore a 10306 // function definition which takes such a parameter must be able to call the 10307 // object's destructor. However, we don't perform any direct access check 10308 // on the dtor. 10309 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 10310 .getCXXABI() 10311 .areArgsDestroyedLeftToRightInCallee()) { 10312 if (!Param->isInvalidDecl()) { 10313 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 10314 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 10315 if (!ClassDecl->isInvalidDecl() && 10316 !ClassDecl->hasIrrelevantDestructor() && 10317 !ClassDecl->isDependentContext()) { 10318 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10319 MarkFunctionReferenced(Param->getLocation(), Destructor); 10320 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 10321 } 10322 } 10323 } 10324 } 10325 10326 // Parameters with the pass_object_size attribute only need to be marked 10327 // constant at function definitions. Because we lack information about 10328 // whether we're on a declaration or definition when we're instantiating the 10329 // attribute, we need to check for constness here. 10330 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 10331 if (!Param->getType().isConstQualified()) 10332 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 10333 << Attr->getSpelling() << 1; 10334 } 10335 10336 return HasInvalidParm; 10337 } 10338 10339 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 10340 /// or MemberExpr. 10341 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 10342 ASTContext &Context) { 10343 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 10344 return Context.getDeclAlign(DRE->getDecl()); 10345 10346 if (const auto *ME = dyn_cast<MemberExpr>(E)) 10347 return Context.getDeclAlign(ME->getMemberDecl()); 10348 10349 return TypeAlign; 10350 } 10351 10352 /// CheckCastAlign - Implements -Wcast-align, which warns when a 10353 /// pointer cast increases the alignment requirements. 10354 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 10355 // This is actually a lot of work to potentially be doing on every 10356 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 10357 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 10358 return; 10359 10360 // Ignore dependent types. 10361 if (T->isDependentType() || Op->getType()->isDependentType()) 10362 return; 10363 10364 // Require that the destination be a pointer type. 10365 const PointerType *DestPtr = T->getAs<PointerType>(); 10366 if (!DestPtr) return; 10367 10368 // If the destination has alignment 1, we're done. 10369 QualType DestPointee = DestPtr->getPointeeType(); 10370 if (DestPointee->isIncompleteType()) return; 10371 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 10372 if (DestAlign.isOne()) return; 10373 10374 // Require that the source be a pointer type. 10375 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 10376 if (!SrcPtr) return; 10377 QualType SrcPointee = SrcPtr->getPointeeType(); 10378 10379 // Whitelist casts from cv void*. We already implicitly 10380 // whitelisted casts to cv void*, since they have alignment 1. 10381 // Also whitelist casts involving incomplete types, which implicitly 10382 // includes 'void'. 10383 if (SrcPointee->isIncompleteType()) return; 10384 10385 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 10386 10387 if (auto *CE = dyn_cast<CastExpr>(Op)) { 10388 if (CE->getCastKind() == CK_ArrayToPointerDecay) 10389 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 10390 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 10391 if (UO->getOpcode() == UO_AddrOf) 10392 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 10393 } 10394 10395 if (SrcAlign >= DestAlign) return; 10396 10397 Diag(TRange.getBegin(), diag::warn_cast_align) 10398 << Op->getType() << T 10399 << static_cast<unsigned>(SrcAlign.getQuantity()) 10400 << static_cast<unsigned>(DestAlign.getQuantity()) 10401 << TRange << Op->getSourceRange(); 10402 } 10403 10404 /// \brief Check whether this array fits the idiom of a size-one tail padded 10405 /// array member of a struct. 10406 /// 10407 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 10408 /// commonly used to emulate flexible arrays in C89 code. 10409 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 10410 const NamedDecl *ND) { 10411 if (Size != 1 || !ND) return false; 10412 10413 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 10414 if (!FD) return false; 10415 10416 // Don't consider sizes resulting from macro expansions or template argument 10417 // substitution to form C89 tail-padded arrays. 10418 10419 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 10420 while (TInfo) { 10421 TypeLoc TL = TInfo->getTypeLoc(); 10422 // Look through typedefs. 10423 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 10424 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 10425 TInfo = TDL->getTypeSourceInfo(); 10426 continue; 10427 } 10428 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 10429 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 10430 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 10431 return false; 10432 } 10433 break; 10434 } 10435 10436 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 10437 if (!RD) return false; 10438 if (RD->isUnion()) return false; 10439 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10440 if (!CRD->isStandardLayout()) return false; 10441 } 10442 10443 // See if this is the last field decl in the record. 10444 const Decl *D = FD; 10445 while ((D = D->getNextDeclInContext())) 10446 if (isa<FieldDecl>(D)) 10447 return false; 10448 return true; 10449 } 10450 10451 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 10452 const ArraySubscriptExpr *ASE, 10453 bool AllowOnePastEnd, bool IndexNegated) { 10454 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 10455 if (IndexExpr->isValueDependent()) 10456 return; 10457 10458 const Type *EffectiveType = 10459 BaseExpr->getType()->getPointeeOrArrayElementType(); 10460 BaseExpr = BaseExpr->IgnoreParenCasts(); 10461 const ConstantArrayType *ArrayTy = 10462 Context.getAsConstantArrayType(BaseExpr->getType()); 10463 if (!ArrayTy) 10464 return; 10465 10466 llvm::APSInt index; 10467 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 10468 return; 10469 if (IndexNegated) 10470 index = -index; 10471 10472 const NamedDecl *ND = nullptr; 10473 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10474 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10475 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10476 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10477 10478 if (index.isUnsigned() || !index.isNegative()) { 10479 llvm::APInt size = ArrayTy->getSize(); 10480 if (!size.isStrictlyPositive()) 10481 return; 10482 10483 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 10484 if (BaseType != EffectiveType) { 10485 // Make sure we're comparing apples to apples when comparing index to size 10486 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 10487 uint64_t array_typesize = Context.getTypeSize(BaseType); 10488 // Handle ptrarith_typesize being zero, such as when casting to void* 10489 if (!ptrarith_typesize) ptrarith_typesize = 1; 10490 if (ptrarith_typesize != array_typesize) { 10491 // There's a cast to a different size type involved 10492 uint64_t ratio = array_typesize / ptrarith_typesize; 10493 // TODO: Be smarter about handling cases where array_typesize is not a 10494 // multiple of ptrarith_typesize 10495 if (ptrarith_typesize * ratio == array_typesize) 10496 size *= llvm::APInt(size.getBitWidth(), ratio); 10497 } 10498 } 10499 10500 if (size.getBitWidth() > index.getBitWidth()) 10501 index = index.zext(size.getBitWidth()); 10502 else if (size.getBitWidth() < index.getBitWidth()) 10503 size = size.zext(index.getBitWidth()); 10504 10505 // For array subscripting the index must be less than size, but for pointer 10506 // arithmetic also allow the index (offset) to be equal to size since 10507 // computing the next address after the end of the array is legal and 10508 // commonly done e.g. in C++ iterators and range-based for loops. 10509 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 10510 return; 10511 10512 // Also don't warn for arrays of size 1 which are members of some 10513 // structure. These are often used to approximate flexible arrays in C89 10514 // code. 10515 if (IsTailPaddedMemberArray(*this, size, ND)) 10516 return; 10517 10518 // Suppress the warning if the subscript expression (as identified by the 10519 // ']' location) and the index expression are both from macro expansions 10520 // within a system header. 10521 if (ASE) { 10522 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 10523 ASE->getRBracketLoc()); 10524 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 10525 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 10526 IndexExpr->getLocStart()); 10527 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 10528 return; 10529 } 10530 } 10531 10532 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 10533 if (ASE) 10534 DiagID = diag::warn_array_index_exceeds_bounds; 10535 10536 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10537 PDiag(DiagID) << index.toString(10, true) 10538 << size.toString(10, true) 10539 << (unsigned)size.getLimitedValue(~0U) 10540 << IndexExpr->getSourceRange()); 10541 } else { 10542 unsigned DiagID = diag::warn_array_index_precedes_bounds; 10543 if (!ASE) { 10544 DiagID = diag::warn_ptr_arith_precedes_bounds; 10545 if (index.isNegative()) index = -index; 10546 } 10547 10548 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10549 PDiag(DiagID) << index.toString(10, true) 10550 << IndexExpr->getSourceRange()); 10551 } 10552 10553 if (!ND) { 10554 // Try harder to find a NamedDecl to point at in the note. 10555 while (const ArraySubscriptExpr *ASE = 10556 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 10557 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 10558 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10559 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10560 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10561 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10562 } 10563 10564 if (ND) 10565 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 10566 PDiag(diag::note_array_index_out_of_bounds) 10567 << ND->getDeclName()); 10568 } 10569 10570 void Sema::CheckArrayAccess(const Expr *expr) { 10571 int AllowOnePastEnd = 0; 10572 while (expr) { 10573 expr = expr->IgnoreParenImpCasts(); 10574 switch (expr->getStmtClass()) { 10575 case Stmt::ArraySubscriptExprClass: { 10576 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 10577 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 10578 AllowOnePastEnd > 0); 10579 return; 10580 } 10581 case Stmt::OMPArraySectionExprClass: { 10582 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 10583 if (ASE->getLowerBound()) 10584 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 10585 /*ASE=*/nullptr, AllowOnePastEnd > 0); 10586 return; 10587 } 10588 case Stmt::UnaryOperatorClass: { 10589 // Only unwrap the * and & unary operators 10590 const UnaryOperator *UO = cast<UnaryOperator>(expr); 10591 expr = UO->getSubExpr(); 10592 switch (UO->getOpcode()) { 10593 case UO_AddrOf: 10594 AllowOnePastEnd++; 10595 break; 10596 case UO_Deref: 10597 AllowOnePastEnd--; 10598 break; 10599 default: 10600 return; 10601 } 10602 break; 10603 } 10604 case Stmt::ConditionalOperatorClass: { 10605 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 10606 if (const Expr *lhs = cond->getLHS()) 10607 CheckArrayAccess(lhs); 10608 if (const Expr *rhs = cond->getRHS()) 10609 CheckArrayAccess(rhs); 10610 return; 10611 } 10612 default: 10613 return; 10614 } 10615 } 10616 } 10617 10618 //===--- CHECK: Objective-C retain cycles ----------------------------------// 10619 10620 namespace { 10621 struct RetainCycleOwner { 10622 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 10623 VarDecl *Variable; 10624 SourceRange Range; 10625 SourceLocation Loc; 10626 bool Indirect; 10627 10628 void setLocsFrom(Expr *e) { 10629 Loc = e->getExprLoc(); 10630 Range = e->getSourceRange(); 10631 } 10632 }; 10633 } // end anonymous namespace 10634 10635 /// Consider whether capturing the given variable can possibly lead to 10636 /// a retain cycle. 10637 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 10638 // In ARC, it's captured strongly iff the variable has __strong 10639 // lifetime. In MRR, it's captured strongly if the variable is 10640 // __block and has an appropriate type. 10641 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 10642 return false; 10643 10644 owner.Variable = var; 10645 if (ref) 10646 owner.setLocsFrom(ref); 10647 return true; 10648 } 10649 10650 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 10651 while (true) { 10652 e = e->IgnoreParens(); 10653 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 10654 switch (cast->getCastKind()) { 10655 case CK_BitCast: 10656 case CK_LValueBitCast: 10657 case CK_LValueToRValue: 10658 case CK_ARCReclaimReturnedObject: 10659 e = cast->getSubExpr(); 10660 continue; 10661 10662 default: 10663 return false; 10664 } 10665 } 10666 10667 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 10668 ObjCIvarDecl *ivar = ref->getDecl(); 10669 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 10670 return false; 10671 10672 // Try to find a retain cycle in the base. 10673 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 10674 return false; 10675 10676 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 10677 owner.Indirect = true; 10678 return true; 10679 } 10680 10681 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 10682 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 10683 if (!var) return false; 10684 return considerVariable(var, ref, owner); 10685 } 10686 10687 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 10688 if (member->isArrow()) return false; 10689 10690 // Don't count this as an indirect ownership. 10691 e = member->getBase(); 10692 continue; 10693 } 10694 10695 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 10696 // Only pay attention to pseudo-objects on property references. 10697 ObjCPropertyRefExpr *pre 10698 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 10699 ->IgnoreParens()); 10700 if (!pre) return false; 10701 if (pre->isImplicitProperty()) return false; 10702 ObjCPropertyDecl *property = pre->getExplicitProperty(); 10703 if (!property->isRetaining() && 10704 !(property->getPropertyIvarDecl() && 10705 property->getPropertyIvarDecl()->getType() 10706 .getObjCLifetime() == Qualifiers::OCL_Strong)) 10707 return false; 10708 10709 owner.Indirect = true; 10710 if (pre->isSuperReceiver()) { 10711 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 10712 if (!owner.Variable) 10713 return false; 10714 owner.Loc = pre->getLocation(); 10715 owner.Range = pre->getSourceRange(); 10716 return true; 10717 } 10718 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 10719 ->getSourceExpr()); 10720 continue; 10721 } 10722 10723 // Array ivars? 10724 10725 return false; 10726 } 10727 } 10728 10729 namespace { 10730 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 10731 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 10732 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 10733 Context(Context), Variable(variable), Capturer(nullptr), 10734 VarWillBeReased(false) {} 10735 ASTContext &Context; 10736 VarDecl *Variable; 10737 Expr *Capturer; 10738 bool VarWillBeReased; 10739 10740 void VisitDeclRefExpr(DeclRefExpr *ref) { 10741 if (ref->getDecl() == Variable && !Capturer) 10742 Capturer = ref; 10743 } 10744 10745 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 10746 if (Capturer) return; 10747 Visit(ref->getBase()); 10748 if (Capturer && ref->isFreeIvar()) 10749 Capturer = ref; 10750 } 10751 10752 void VisitBlockExpr(BlockExpr *block) { 10753 // Look inside nested blocks 10754 if (block->getBlockDecl()->capturesVariable(Variable)) 10755 Visit(block->getBlockDecl()->getBody()); 10756 } 10757 10758 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 10759 if (Capturer) return; 10760 if (OVE->getSourceExpr()) 10761 Visit(OVE->getSourceExpr()); 10762 } 10763 void VisitBinaryOperator(BinaryOperator *BinOp) { 10764 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 10765 return; 10766 Expr *LHS = BinOp->getLHS(); 10767 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 10768 if (DRE->getDecl() != Variable) 10769 return; 10770 if (Expr *RHS = BinOp->getRHS()) { 10771 RHS = RHS->IgnoreParenCasts(); 10772 llvm::APSInt Value; 10773 VarWillBeReased = 10774 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 10775 } 10776 } 10777 } 10778 }; 10779 } // end anonymous namespace 10780 10781 /// Check whether the given argument is a block which captures a 10782 /// variable. 10783 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 10784 assert(owner.Variable && owner.Loc.isValid()); 10785 10786 e = e->IgnoreParenCasts(); 10787 10788 // Look through [^{...} copy] and Block_copy(^{...}). 10789 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 10790 Selector Cmd = ME->getSelector(); 10791 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 10792 e = ME->getInstanceReceiver(); 10793 if (!e) 10794 return nullptr; 10795 e = e->IgnoreParenCasts(); 10796 } 10797 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 10798 if (CE->getNumArgs() == 1) { 10799 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 10800 if (Fn) { 10801 const IdentifierInfo *FnI = Fn->getIdentifier(); 10802 if (FnI && FnI->isStr("_Block_copy")) { 10803 e = CE->getArg(0)->IgnoreParenCasts(); 10804 } 10805 } 10806 } 10807 } 10808 10809 BlockExpr *block = dyn_cast<BlockExpr>(e); 10810 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 10811 return nullptr; 10812 10813 FindCaptureVisitor visitor(S.Context, owner.Variable); 10814 visitor.Visit(block->getBlockDecl()->getBody()); 10815 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 10816 } 10817 10818 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 10819 RetainCycleOwner &owner) { 10820 assert(capturer); 10821 assert(owner.Variable && owner.Loc.isValid()); 10822 10823 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 10824 << owner.Variable << capturer->getSourceRange(); 10825 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 10826 << owner.Indirect << owner.Range; 10827 } 10828 10829 /// Check for a keyword selector that starts with the word 'add' or 10830 /// 'set'. 10831 static bool isSetterLikeSelector(Selector sel) { 10832 if (sel.isUnarySelector()) return false; 10833 10834 StringRef str = sel.getNameForSlot(0); 10835 while (!str.empty() && str.front() == '_') str = str.substr(1); 10836 if (str.startswith("set")) 10837 str = str.substr(3); 10838 else if (str.startswith("add")) { 10839 // Specially whitelist 'addOperationWithBlock:'. 10840 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 10841 return false; 10842 str = str.substr(3); 10843 } 10844 else 10845 return false; 10846 10847 if (str.empty()) return true; 10848 return !isLowercase(str.front()); 10849 } 10850 10851 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 10852 ObjCMessageExpr *Message) { 10853 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 10854 Message->getReceiverInterface(), 10855 NSAPI::ClassId_NSMutableArray); 10856 if (!IsMutableArray) { 10857 return None; 10858 } 10859 10860 Selector Sel = Message->getSelector(); 10861 10862 Optional<NSAPI::NSArrayMethodKind> MKOpt = 10863 S.NSAPIObj->getNSArrayMethodKind(Sel); 10864 if (!MKOpt) { 10865 return None; 10866 } 10867 10868 NSAPI::NSArrayMethodKind MK = *MKOpt; 10869 10870 switch (MK) { 10871 case NSAPI::NSMutableArr_addObject: 10872 case NSAPI::NSMutableArr_insertObjectAtIndex: 10873 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 10874 return 0; 10875 case NSAPI::NSMutableArr_replaceObjectAtIndex: 10876 return 1; 10877 10878 default: 10879 return None; 10880 } 10881 10882 return None; 10883 } 10884 10885 static 10886 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 10887 ObjCMessageExpr *Message) { 10888 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 10889 Message->getReceiverInterface(), 10890 NSAPI::ClassId_NSMutableDictionary); 10891 if (!IsMutableDictionary) { 10892 return None; 10893 } 10894 10895 Selector Sel = Message->getSelector(); 10896 10897 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 10898 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 10899 if (!MKOpt) { 10900 return None; 10901 } 10902 10903 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 10904 10905 switch (MK) { 10906 case NSAPI::NSMutableDict_setObjectForKey: 10907 case NSAPI::NSMutableDict_setValueForKey: 10908 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 10909 return 0; 10910 10911 default: 10912 return None; 10913 } 10914 10915 return None; 10916 } 10917 10918 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 10919 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 10920 Message->getReceiverInterface(), 10921 NSAPI::ClassId_NSMutableSet); 10922 10923 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 10924 Message->getReceiverInterface(), 10925 NSAPI::ClassId_NSMutableOrderedSet); 10926 if (!IsMutableSet && !IsMutableOrderedSet) { 10927 return None; 10928 } 10929 10930 Selector Sel = Message->getSelector(); 10931 10932 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 10933 if (!MKOpt) { 10934 return None; 10935 } 10936 10937 NSAPI::NSSetMethodKind MK = *MKOpt; 10938 10939 switch (MK) { 10940 case NSAPI::NSMutableSet_addObject: 10941 case NSAPI::NSOrderedSet_setObjectAtIndex: 10942 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 10943 case NSAPI::NSOrderedSet_insertObjectAtIndex: 10944 return 0; 10945 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 10946 return 1; 10947 } 10948 10949 return None; 10950 } 10951 10952 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 10953 if (!Message->isInstanceMessage()) { 10954 return; 10955 } 10956 10957 Optional<int> ArgOpt; 10958 10959 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 10960 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 10961 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 10962 return; 10963 } 10964 10965 int ArgIndex = *ArgOpt; 10966 10967 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 10968 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 10969 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 10970 } 10971 10972 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 10973 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 10974 if (ArgRE->isObjCSelfExpr()) { 10975 Diag(Message->getSourceRange().getBegin(), 10976 diag::warn_objc_circular_container) 10977 << ArgRE->getDecl()->getName() << StringRef("super"); 10978 } 10979 } 10980 } else { 10981 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 10982 10983 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 10984 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 10985 } 10986 10987 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 10988 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 10989 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 10990 ValueDecl *Decl = ReceiverRE->getDecl(); 10991 Diag(Message->getSourceRange().getBegin(), 10992 diag::warn_objc_circular_container) 10993 << Decl->getName() << Decl->getName(); 10994 if (!ArgRE->isObjCSelfExpr()) { 10995 Diag(Decl->getLocation(), 10996 diag::note_objc_circular_container_declared_here) 10997 << Decl->getName(); 10998 } 10999 } 11000 } 11001 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 11002 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 11003 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 11004 ObjCIvarDecl *Decl = IvarRE->getDecl(); 11005 Diag(Message->getSourceRange().getBegin(), 11006 diag::warn_objc_circular_container) 11007 << Decl->getName() << Decl->getName(); 11008 Diag(Decl->getLocation(), 11009 diag::note_objc_circular_container_declared_here) 11010 << Decl->getName(); 11011 } 11012 } 11013 } 11014 } 11015 } 11016 11017 /// Check a message send to see if it's likely to cause a retain cycle. 11018 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 11019 // Only check instance methods whose selector looks like a setter. 11020 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 11021 return; 11022 11023 // Try to find a variable that the receiver is strongly owned by. 11024 RetainCycleOwner owner; 11025 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 11026 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 11027 return; 11028 } else { 11029 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 11030 owner.Variable = getCurMethodDecl()->getSelfDecl(); 11031 owner.Loc = msg->getSuperLoc(); 11032 owner.Range = msg->getSuperLoc(); 11033 } 11034 11035 // Check whether the receiver is captured by any of the arguments. 11036 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 11037 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 11038 return diagnoseRetainCycle(*this, capturer, owner); 11039 } 11040 11041 /// Check a property assign to see if it's likely to cause a retain cycle. 11042 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 11043 RetainCycleOwner owner; 11044 if (!findRetainCycleOwner(*this, receiver, owner)) 11045 return; 11046 11047 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 11048 diagnoseRetainCycle(*this, capturer, owner); 11049 } 11050 11051 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 11052 RetainCycleOwner Owner; 11053 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 11054 return; 11055 11056 // Because we don't have an expression for the variable, we have to set the 11057 // location explicitly here. 11058 Owner.Loc = Var->getLocation(); 11059 Owner.Range = Var->getSourceRange(); 11060 11061 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 11062 diagnoseRetainCycle(*this, Capturer, Owner); 11063 } 11064 11065 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 11066 Expr *RHS, bool isProperty) { 11067 // Check if RHS is an Objective-C object literal, which also can get 11068 // immediately zapped in a weak reference. Note that we explicitly 11069 // allow ObjCStringLiterals, since those are designed to never really die. 11070 RHS = RHS->IgnoreParenImpCasts(); 11071 11072 // This enum needs to match with the 'select' in 11073 // warn_objc_arc_literal_assign (off-by-1). 11074 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 11075 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 11076 return false; 11077 11078 S.Diag(Loc, diag::warn_arc_literal_assign) 11079 << (unsigned) Kind 11080 << (isProperty ? 0 : 1) 11081 << RHS->getSourceRange(); 11082 11083 return true; 11084 } 11085 11086 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 11087 Qualifiers::ObjCLifetime LT, 11088 Expr *RHS, bool isProperty) { 11089 // Strip off any implicit cast added to get to the one ARC-specific. 11090 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11091 if (cast->getCastKind() == CK_ARCConsumeObject) { 11092 S.Diag(Loc, diag::warn_arc_retained_assign) 11093 << (LT == Qualifiers::OCL_ExplicitNone) 11094 << (isProperty ? 0 : 1) 11095 << RHS->getSourceRange(); 11096 return true; 11097 } 11098 RHS = cast->getSubExpr(); 11099 } 11100 11101 if (LT == Qualifiers::OCL_Weak && 11102 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 11103 return true; 11104 11105 return false; 11106 } 11107 11108 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 11109 QualType LHS, Expr *RHS) { 11110 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 11111 11112 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 11113 return false; 11114 11115 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 11116 return true; 11117 11118 return false; 11119 } 11120 11121 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 11122 Expr *LHS, Expr *RHS) { 11123 QualType LHSType; 11124 // PropertyRef on LHS type need be directly obtained from 11125 // its declaration as it has a PseudoType. 11126 ObjCPropertyRefExpr *PRE 11127 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 11128 if (PRE && !PRE->isImplicitProperty()) { 11129 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11130 if (PD) 11131 LHSType = PD->getType(); 11132 } 11133 11134 if (LHSType.isNull()) 11135 LHSType = LHS->getType(); 11136 11137 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 11138 11139 if (LT == Qualifiers::OCL_Weak) { 11140 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 11141 getCurFunction()->markSafeWeakUse(LHS); 11142 } 11143 11144 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 11145 return; 11146 11147 // FIXME. Check for other life times. 11148 if (LT != Qualifiers::OCL_None) 11149 return; 11150 11151 if (PRE) { 11152 if (PRE->isImplicitProperty()) 11153 return; 11154 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11155 if (!PD) 11156 return; 11157 11158 unsigned Attributes = PD->getPropertyAttributes(); 11159 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 11160 // when 'assign' attribute was not explicitly specified 11161 // by user, ignore it and rely on property type itself 11162 // for lifetime info. 11163 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 11164 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 11165 LHSType->isObjCRetainableType()) 11166 return; 11167 11168 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11169 if (cast->getCastKind() == CK_ARCConsumeObject) { 11170 Diag(Loc, diag::warn_arc_retained_property_assign) 11171 << RHS->getSourceRange(); 11172 return; 11173 } 11174 RHS = cast->getSubExpr(); 11175 } 11176 } 11177 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 11178 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 11179 return; 11180 } 11181 } 11182 } 11183 11184 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 11185 11186 namespace { 11187 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 11188 SourceLocation StmtLoc, 11189 const NullStmt *Body) { 11190 // Do not warn if the body is a macro that expands to nothing, e.g: 11191 // 11192 // #define CALL(x) 11193 // if (condition) 11194 // CALL(0); 11195 // 11196 if (Body->hasLeadingEmptyMacro()) 11197 return false; 11198 11199 // Get line numbers of statement and body. 11200 bool StmtLineInvalid; 11201 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 11202 &StmtLineInvalid); 11203 if (StmtLineInvalid) 11204 return false; 11205 11206 bool BodyLineInvalid; 11207 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 11208 &BodyLineInvalid); 11209 if (BodyLineInvalid) 11210 return false; 11211 11212 // Warn if null statement and body are on the same line. 11213 if (StmtLine != BodyLine) 11214 return false; 11215 11216 return true; 11217 } 11218 } // end anonymous namespace 11219 11220 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 11221 const Stmt *Body, 11222 unsigned DiagID) { 11223 // Since this is a syntactic check, don't emit diagnostic for template 11224 // instantiations, this just adds noise. 11225 if (CurrentInstantiationScope) 11226 return; 11227 11228 // The body should be a null statement. 11229 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11230 if (!NBody) 11231 return; 11232 11233 // Do the usual checks. 11234 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11235 return; 11236 11237 Diag(NBody->getSemiLoc(), DiagID); 11238 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11239 } 11240 11241 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 11242 const Stmt *PossibleBody) { 11243 assert(!CurrentInstantiationScope); // Ensured by caller 11244 11245 SourceLocation StmtLoc; 11246 const Stmt *Body; 11247 unsigned DiagID; 11248 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 11249 StmtLoc = FS->getRParenLoc(); 11250 Body = FS->getBody(); 11251 DiagID = diag::warn_empty_for_body; 11252 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 11253 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 11254 Body = WS->getBody(); 11255 DiagID = diag::warn_empty_while_body; 11256 } else 11257 return; // Neither `for' nor `while'. 11258 11259 // The body should be a null statement. 11260 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11261 if (!NBody) 11262 return; 11263 11264 // Skip expensive checks if diagnostic is disabled. 11265 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 11266 return; 11267 11268 // Do the usual checks. 11269 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11270 return; 11271 11272 // `for(...);' and `while(...);' are popular idioms, so in order to keep 11273 // noise level low, emit diagnostics only if for/while is followed by a 11274 // CompoundStmt, e.g.: 11275 // for (int i = 0; i < n; i++); 11276 // { 11277 // a(i); 11278 // } 11279 // or if for/while is followed by a statement with more indentation 11280 // than for/while itself: 11281 // for (int i = 0; i < n; i++); 11282 // a(i); 11283 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 11284 if (!ProbableTypo) { 11285 bool BodyColInvalid; 11286 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 11287 PossibleBody->getLocStart(), 11288 &BodyColInvalid); 11289 if (BodyColInvalid) 11290 return; 11291 11292 bool StmtColInvalid; 11293 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 11294 S->getLocStart(), 11295 &StmtColInvalid); 11296 if (StmtColInvalid) 11297 return; 11298 11299 if (BodyCol > StmtCol) 11300 ProbableTypo = true; 11301 } 11302 11303 if (ProbableTypo) { 11304 Diag(NBody->getSemiLoc(), DiagID); 11305 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11306 } 11307 } 11308 11309 //===--- CHECK: Warn on self move with std::move. -------------------------===// 11310 11311 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 11312 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 11313 SourceLocation OpLoc) { 11314 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 11315 return; 11316 11317 if (!ActiveTemplateInstantiations.empty()) 11318 return; 11319 11320 // Strip parens and casts away. 11321 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11322 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11323 11324 // Check for a call expression 11325 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 11326 if (!CE || CE->getNumArgs() != 1) 11327 return; 11328 11329 // Check for a call to std::move 11330 const FunctionDecl *FD = CE->getDirectCallee(); 11331 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() || 11332 !FD->getIdentifier()->isStr("move")) 11333 return; 11334 11335 // Get argument from std::move 11336 RHSExpr = CE->getArg(0); 11337 11338 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11339 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11340 11341 // Two DeclRefExpr's, check that the decls are the same. 11342 if (LHSDeclRef && RHSDeclRef) { 11343 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11344 return; 11345 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11346 RHSDeclRef->getDecl()->getCanonicalDecl()) 11347 return; 11348 11349 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11350 << LHSExpr->getSourceRange() 11351 << RHSExpr->getSourceRange(); 11352 return; 11353 } 11354 11355 // Member variables require a different approach to check for self moves. 11356 // MemberExpr's are the same if every nested MemberExpr refers to the same 11357 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 11358 // the base Expr's are CXXThisExpr's. 11359 const Expr *LHSBase = LHSExpr; 11360 const Expr *RHSBase = RHSExpr; 11361 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 11362 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 11363 if (!LHSME || !RHSME) 11364 return; 11365 11366 while (LHSME && RHSME) { 11367 if (LHSME->getMemberDecl()->getCanonicalDecl() != 11368 RHSME->getMemberDecl()->getCanonicalDecl()) 11369 return; 11370 11371 LHSBase = LHSME->getBase(); 11372 RHSBase = RHSME->getBase(); 11373 LHSME = dyn_cast<MemberExpr>(LHSBase); 11374 RHSME = dyn_cast<MemberExpr>(RHSBase); 11375 } 11376 11377 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 11378 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 11379 if (LHSDeclRef && RHSDeclRef) { 11380 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11381 return; 11382 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11383 RHSDeclRef->getDecl()->getCanonicalDecl()) 11384 return; 11385 11386 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11387 << LHSExpr->getSourceRange() 11388 << RHSExpr->getSourceRange(); 11389 return; 11390 } 11391 11392 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 11393 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11394 << LHSExpr->getSourceRange() 11395 << RHSExpr->getSourceRange(); 11396 } 11397 11398 //===--- Layout compatibility ----------------------------------------------// 11399 11400 namespace { 11401 11402 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 11403 11404 /// \brief Check if two enumeration types are layout-compatible. 11405 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 11406 // C++11 [dcl.enum] p8: 11407 // Two enumeration types are layout-compatible if they have the same 11408 // underlying type. 11409 return ED1->isComplete() && ED2->isComplete() && 11410 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 11411 } 11412 11413 /// \brief Check if two fields are layout-compatible. 11414 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 11415 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 11416 return false; 11417 11418 if (Field1->isBitField() != Field2->isBitField()) 11419 return false; 11420 11421 if (Field1->isBitField()) { 11422 // Make sure that the bit-fields are the same length. 11423 unsigned Bits1 = Field1->getBitWidthValue(C); 11424 unsigned Bits2 = Field2->getBitWidthValue(C); 11425 11426 if (Bits1 != Bits2) 11427 return false; 11428 } 11429 11430 return true; 11431 } 11432 11433 /// \brief Check if two standard-layout structs are layout-compatible. 11434 /// (C++11 [class.mem] p17) 11435 bool isLayoutCompatibleStruct(ASTContext &C, 11436 RecordDecl *RD1, 11437 RecordDecl *RD2) { 11438 // If both records are C++ classes, check that base classes match. 11439 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 11440 // If one of records is a CXXRecordDecl we are in C++ mode, 11441 // thus the other one is a CXXRecordDecl, too. 11442 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 11443 // Check number of base classes. 11444 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 11445 return false; 11446 11447 // Check the base classes. 11448 for (CXXRecordDecl::base_class_const_iterator 11449 Base1 = D1CXX->bases_begin(), 11450 BaseEnd1 = D1CXX->bases_end(), 11451 Base2 = D2CXX->bases_begin(); 11452 Base1 != BaseEnd1; 11453 ++Base1, ++Base2) { 11454 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 11455 return false; 11456 } 11457 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 11458 // If only RD2 is a C++ class, it should have zero base classes. 11459 if (D2CXX->getNumBases() > 0) 11460 return false; 11461 } 11462 11463 // Check the fields. 11464 RecordDecl::field_iterator Field2 = RD2->field_begin(), 11465 Field2End = RD2->field_end(), 11466 Field1 = RD1->field_begin(), 11467 Field1End = RD1->field_end(); 11468 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 11469 if (!isLayoutCompatible(C, *Field1, *Field2)) 11470 return false; 11471 } 11472 if (Field1 != Field1End || Field2 != Field2End) 11473 return false; 11474 11475 return true; 11476 } 11477 11478 /// \brief Check if two standard-layout unions are layout-compatible. 11479 /// (C++11 [class.mem] p18) 11480 bool isLayoutCompatibleUnion(ASTContext &C, 11481 RecordDecl *RD1, 11482 RecordDecl *RD2) { 11483 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 11484 for (auto *Field2 : RD2->fields()) 11485 UnmatchedFields.insert(Field2); 11486 11487 for (auto *Field1 : RD1->fields()) { 11488 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 11489 I = UnmatchedFields.begin(), 11490 E = UnmatchedFields.end(); 11491 11492 for ( ; I != E; ++I) { 11493 if (isLayoutCompatible(C, Field1, *I)) { 11494 bool Result = UnmatchedFields.erase(*I); 11495 (void) Result; 11496 assert(Result); 11497 break; 11498 } 11499 } 11500 if (I == E) 11501 return false; 11502 } 11503 11504 return UnmatchedFields.empty(); 11505 } 11506 11507 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 11508 if (RD1->isUnion() != RD2->isUnion()) 11509 return false; 11510 11511 if (RD1->isUnion()) 11512 return isLayoutCompatibleUnion(C, RD1, RD2); 11513 else 11514 return isLayoutCompatibleStruct(C, RD1, RD2); 11515 } 11516 11517 /// \brief Check if two types are layout-compatible in C++11 sense. 11518 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 11519 if (T1.isNull() || T2.isNull()) 11520 return false; 11521 11522 // C++11 [basic.types] p11: 11523 // If two types T1 and T2 are the same type, then T1 and T2 are 11524 // layout-compatible types. 11525 if (C.hasSameType(T1, T2)) 11526 return true; 11527 11528 T1 = T1.getCanonicalType().getUnqualifiedType(); 11529 T2 = T2.getCanonicalType().getUnqualifiedType(); 11530 11531 const Type::TypeClass TC1 = T1->getTypeClass(); 11532 const Type::TypeClass TC2 = T2->getTypeClass(); 11533 11534 if (TC1 != TC2) 11535 return false; 11536 11537 if (TC1 == Type::Enum) { 11538 return isLayoutCompatible(C, 11539 cast<EnumType>(T1)->getDecl(), 11540 cast<EnumType>(T2)->getDecl()); 11541 } else if (TC1 == Type::Record) { 11542 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 11543 return false; 11544 11545 return isLayoutCompatible(C, 11546 cast<RecordType>(T1)->getDecl(), 11547 cast<RecordType>(T2)->getDecl()); 11548 } 11549 11550 return false; 11551 } 11552 } // end anonymous namespace 11553 11554 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 11555 11556 namespace { 11557 /// \brief Given a type tag expression find the type tag itself. 11558 /// 11559 /// \param TypeExpr Type tag expression, as it appears in user's code. 11560 /// 11561 /// \param VD Declaration of an identifier that appears in a type tag. 11562 /// 11563 /// \param MagicValue Type tag magic value. 11564 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 11565 const ValueDecl **VD, uint64_t *MagicValue) { 11566 while(true) { 11567 if (!TypeExpr) 11568 return false; 11569 11570 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 11571 11572 switch (TypeExpr->getStmtClass()) { 11573 case Stmt::UnaryOperatorClass: { 11574 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 11575 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 11576 TypeExpr = UO->getSubExpr(); 11577 continue; 11578 } 11579 return false; 11580 } 11581 11582 case Stmt::DeclRefExprClass: { 11583 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 11584 *VD = DRE->getDecl(); 11585 return true; 11586 } 11587 11588 case Stmt::IntegerLiteralClass: { 11589 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 11590 llvm::APInt MagicValueAPInt = IL->getValue(); 11591 if (MagicValueAPInt.getActiveBits() <= 64) { 11592 *MagicValue = MagicValueAPInt.getZExtValue(); 11593 return true; 11594 } else 11595 return false; 11596 } 11597 11598 case Stmt::BinaryConditionalOperatorClass: 11599 case Stmt::ConditionalOperatorClass: { 11600 const AbstractConditionalOperator *ACO = 11601 cast<AbstractConditionalOperator>(TypeExpr); 11602 bool Result; 11603 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 11604 if (Result) 11605 TypeExpr = ACO->getTrueExpr(); 11606 else 11607 TypeExpr = ACO->getFalseExpr(); 11608 continue; 11609 } 11610 return false; 11611 } 11612 11613 case Stmt::BinaryOperatorClass: { 11614 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 11615 if (BO->getOpcode() == BO_Comma) { 11616 TypeExpr = BO->getRHS(); 11617 continue; 11618 } 11619 return false; 11620 } 11621 11622 default: 11623 return false; 11624 } 11625 } 11626 } 11627 11628 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 11629 /// 11630 /// \param TypeExpr Expression that specifies a type tag. 11631 /// 11632 /// \param MagicValues Registered magic values. 11633 /// 11634 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 11635 /// kind. 11636 /// 11637 /// \param TypeInfo Information about the corresponding C type. 11638 /// 11639 /// \returns true if the corresponding C type was found. 11640 bool GetMatchingCType( 11641 const IdentifierInfo *ArgumentKind, 11642 const Expr *TypeExpr, const ASTContext &Ctx, 11643 const llvm::DenseMap<Sema::TypeTagMagicValue, 11644 Sema::TypeTagData> *MagicValues, 11645 bool &FoundWrongKind, 11646 Sema::TypeTagData &TypeInfo) { 11647 FoundWrongKind = false; 11648 11649 // Variable declaration that has type_tag_for_datatype attribute. 11650 const ValueDecl *VD = nullptr; 11651 11652 uint64_t MagicValue; 11653 11654 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 11655 return false; 11656 11657 if (VD) { 11658 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 11659 if (I->getArgumentKind() != ArgumentKind) { 11660 FoundWrongKind = true; 11661 return false; 11662 } 11663 TypeInfo.Type = I->getMatchingCType(); 11664 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 11665 TypeInfo.MustBeNull = I->getMustBeNull(); 11666 return true; 11667 } 11668 return false; 11669 } 11670 11671 if (!MagicValues) 11672 return false; 11673 11674 llvm::DenseMap<Sema::TypeTagMagicValue, 11675 Sema::TypeTagData>::const_iterator I = 11676 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 11677 if (I == MagicValues->end()) 11678 return false; 11679 11680 TypeInfo = I->second; 11681 return true; 11682 } 11683 } // end anonymous namespace 11684 11685 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 11686 uint64_t MagicValue, QualType Type, 11687 bool LayoutCompatible, 11688 bool MustBeNull) { 11689 if (!TypeTagForDatatypeMagicValues) 11690 TypeTagForDatatypeMagicValues.reset( 11691 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 11692 11693 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 11694 (*TypeTagForDatatypeMagicValues)[Magic] = 11695 TypeTagData(Type, LayoutCompatible, MustBeNull); 11696 } 11697 11698 namespace { 11699 bool IsSameCharType(QualType T1, QualType T2) { 11700 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 11701 if (!BT1) 11702 return false; 11703 11704 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 11705 if (!BT2) 11706 return false; 11707 11708 BuiltinType::Kind T1Kind = BT1->getKind(); 11709 BuiltinType::Kind T2Kind = BT2->getKind(); 11710 11711 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 11712 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 11713 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 11714 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 11715 } 11716 } // end anonymous namespace 11717 11718 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 11719 const Expr * const *ExprArgs) { 11720 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 11721 bool IsPointerAttr = Attr->getIsPointer(); 11722 11723 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 11724 bool FoundWrongKind; 11725 TypeTagData TypeInfo; 11726 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 11727 TypeTagForDatatypeMagicValues.get(), 11728 FoundWrongKind, TypeInfo)) { 11729 if (FoundWrongKind) 11730 Diag(TypeTagExpr->getExprLoc(), 11731 diag::warn_type_tag_for_datatype_wrong_kind) 11732 << TypeTagExpr->getSourceRange(); 11733 return; 11734 } 11735 11736 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 11737 if (IsPointerAttr) { 11738 // Skip implicit cast of pointer to `void *' (as a function argument). 11739 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 11740 if (ICE->getType()->isVoidPointerType() && 11741 ICE->getCastKind() == CK_BitCast) 11742 ArgumentExpr = ICE->getSubExpr(); 11743 } 11744 QualType ArgumentType = ArgumentExpr->getType(); 11745 11746 // Passing a `void*' pointer shouldn't trigger a warning. 11747 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 11748 return; 11749 11750 if (TypeInfo.MustBeNull) { 11751 // Type tag with matching void type requires a null pointer. 11752 if (!ArgumentExpr->isNullPointerConstant(Context, 11753 Expr::NPC_ValueDependentIsNotNull)) { 11754 Diag(ArgumentExpr->getExprLoc(), 11755 diag::warn_type_safety_null_pointer_required) 11756 << ArgumentKind->getName() 11757 << ArgumentExpr->getSourceRange() 11758 << TypeTagExpr->getSourceRange(); 11759 } 11760 return; 11761 } 11762 11763 QualType RequiredType = TypeInfo.Type; 11764 if (IsPointerAttr) 11765 RequiredType = Context.getPointerType(RequiredType); 11766 11767 bool mismatch = false; 11768 if (!TypeInfo.LayoutCompatible) { 11769 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 11770 11771 // C++11 [basic.fundamental] p1: 11772 // Plain char, signed char, and unsigned char are three distinct types. 11773 // 11774 // But we treat plain `char' as equivalent to `signed char' or `unsigned 11775 // char' depending on the current char signedness mode. 11776 if (mismatch) 11777 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 11778 RequiredType->getPointeeType())) || 11779 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 11780 mismatch = false; 11781 } else 11782 if (IsPointerAttr) 11783 mismatch = !isLayoutCompatible(Context, 11784 ArgumentType->getPointeeType(), 11785 RequiredType->getPointeeType()); 11786 else 11787 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 11788 11789 if (mismatch) 11790 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 11791 << ArgumentType << ArgumentKind 11792 << TypeInfo.LayoutCompatible << RequiredType 11793 << ArgumentExpr->getSourceRange() 11794 << TypeTagExpr->getSourceRange(); 11795 } 11796 11797 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 11798 CharUnits Alignment) { 11799 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 11800 } 11801 11802 void Sema::DiagnoseMisalignedMembers() { 11803 for (MisalignedMember &m : MisalignedMembers) { 11804 const NamedDecl *ND = m.RD; 11805 if (ND->getName().empty()) { 11806 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 11807 ND = TD; 11808 } 11809 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 11810 << m.MD << ND << m.E->getSourceRange(); 11811 } 11812 MisalignedMembers.clear(); 11813 } 11814 11815 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 11816 E = E->IgnoreParens(); 11817 if (!T->isPointerType() && !T->isIntegerType()) 11818 return; 11819 if (isa<UnaryOperator>(E) && 11820 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 11821 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 11822 if (isa<MemberExpr>(Op)) { 11823 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 11824 MisalignedMember(Op)); 11825 if (MA != MisalignedMembers.end() && 11826 (T->isIntegerType() || 11827 (T->isPointerType() && 11828 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment))) 11829 MisalignedMembers.erase(MA); 11830 } 11831 } 11832 } 11833 11834 void Sema::RefersToMemberWithReducedAlignment( 11835 Expr *E, 11836 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 11837 Action) { 11838 const auto *ME = dyn_cast<MemberExpr>(E); 11839 if (!ME) 11840 return; 11841 11842 // For a chain of MemberExpr like "a.b.c.d" this list 11843 // will keep FieldDecl's like [d, c, b]. 11844 SmallVector<FieldDecl *, 4> ReverseMemberChain; 11845 const MemberExpr *TopME = nullptr; 11846 bool AnyIsPacked = false; 11847 do { 11848 QualType BaseType = ME->getBase()->getType(); 11849 if (ME->isArrow()) 11850 BaseType = BaseType->getPointeeType(); 11851 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 11852 11853 ValueDecl *MD = ME->getMemberDecl(); 11854 auto *FD = dyn_cast<FieldDecl>(MD); 11855 // We do not care about non-data members. 11856 if (!FD || FD->isInvalidDecl()) 11857 return; 11858 11859 AnyIsPacked = 11860 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 11861 ReverseMemberChain.push_back(FD); 11862 11863 TopME = ME; 11864 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 11865 } while (ME); 11866 assert(TopME && "We did not compute a topmost MemberExpr!"); 11867 11868 // Not the scope of this diagnostic. 11869 if (!AnyIsPacked) 11870 return; 11871 11872 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 11873 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 11874 // TODO: The innermost base of the member expression may be too complicated. 11875 // For now, just disregard these cases. This is left for future 11876 // improvement. 11877 if (!DRE && !isa<CXXThisExpr>(TopBase)) 11878 return; 11879 11880 // Alignment expected by the whole expression. 11881 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 11882 11883 // No need to do anything else with this case. 11884 if (ExpectedAlignment.isOne()) 11885 return; 11886 11887 // Synthesize offset of the whole access. 11888 CharUnits Offset; 11889 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 11890 I++) { 11891 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 11892 } 11893 11894 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 11895 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 11896 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 11897 11898 // The base expression of the innermost MemberExpr may give 11899 // stronger guarantees than the class containing the member. 11900 if (DRE && !TopME->isArrow()) { 11901 const ValueDecl *VD = DRE->getDecl(); 11902 if (!VD->getType()->isReferenceType()) 11903 CompleteObjectAlignment = 11904 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 11905 } 11906 11907 // Check if the synthesized offset fulfills the alignment. 11908 if (Offset % ExpectedAlignment != 0 || 11909 // It may fulfill the offset it but the effective alignment may still be 11910 // lower than the expected expression alignment. 11911 CompleteObjectAlignment < ExpectedAlignment) { 11912 // If this happens, we want to determine a sensible culprit of this. 11913 // Intuitively, watching the chain of member expressions from right to 11914 // left, we start with the required alignment (as required by the field 11915 // type) but some packed attribute in that chain has reduced the alignment. 11916 // It may happen that another packed structure increases it again. But if 11917 // we are here such increase has not been enough. So pointing the first 11918 // FieldDecl that either is packed or else its RecordDecl is, 11919 // seems reasonable. 11920 FieldDecl *FD = nullptr; 11921 CharUnits Alignment; 11922 for (FieldDecl *FDI : ReverseMemberChain) { 11923 if (FDI->hasAttr<PackedAttr>() || 11924 FDI->getParent()->hasAttr<PackedAttr>()) { 11925 FD = FDI; 11926 Alignment = std::min( 11927 Context.getTypeAlignInChars(FD->getType()), 11928 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 11929 break; 11930 } 11931 } 11932 assert(FD && "We did not find a packed FieldDecl!"); 11933 Action(E, FD->getParent(), FD, Alignment); 11934 } 11935 } 11936 11937 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 11938 using namespace std::placeholders; 11939 RefersToMemberWithReducedAlignment( 11940 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 11941 _2, _3, _4)); 11942 } 11943 11944