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/Sema/SemaInternal.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/CharUnits.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/EvaluatedExprVisitor.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/ExprObjC.h" 24 #include "clang/AST/ExprOpenMP.h" 25 #include "clang/AST/StmtCXX.h" 26 #include "clang/AST/StmtObjC.h" 27 #include "clang/Analysis/Analyses/FormatString.h" 28 #include "clang/Basic/CharInfo.h" 29 #include "clang/Basic/TargetBuiltins.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 32 #include "clang/Sema/Initialization.h" 33 #include "clang/Sema/Lookup.h" 34 #include "clang/Sema/ScopeInfo.h" 35 #include "clang/Sema/Sema.h" 36 #include "llvm/ADT/STLExtras.h" 37 #include "llvm/ADT/SmallBitVector.h" 38 #include "llvm/ADT/SmallString.h" 39 #include "llvm/Support/Format.h" 40 #include "llvm/Support/Locale.h" 41 #include "llvm/Support/ConvertUTF.h" 42 #include "llvm/Support/raw_ostream.h" 43 #include <limits> 44 45 using namespace clang; 46 using namespace sema; 47 48 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 49 unsigned ByteNo) const { 50 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 51 Context.getTargetInfo()); 52 } 53 54 /// Checks that a call expression's argument count is the desired number. 55 /// This is useful when doing custom type-checking. Returns true on error. 56 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 57 unsigned argCount = call->getNumArgs(); 58 if (argCount == desiredArgCount) return false; 59 60 if (argCount < desiredArgCount) 61 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 62 << 0 /*function call*/ << desiredArgCount << argCount 63 << call->getSourceRange(); 64 65 // Highlight all the excess arguments. 66 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 67 call->getArg(argCount - 1)->getLocEnd()); 68 69 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 70 << 0 /*function call*/ << desiredArgCount << argCount 71 << call->getArg(1)->getSourceRange(); 72 } 73 74 /// Check that the first argument to __builtin_annotation is an integer 75 /// and the second argument is a non-wide string literal. 76 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 77 if (checkArgCount(S, TheCall, 2)) 78 return true; 79 80 // First argument should be an integer. 81 Expr *ValArg = TheCall->getArg(0); 82 QualType Ty = ValArg->getType(); 83 if (!Ty->isIntegerType()) { 84 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 85 << ValArg->getSourceRange(); 86 return true; 87 } 88 89 // Second argument should be a constant string. 90 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 91 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 92 if (!Literal || !Literal->isAscii()) { 93 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 94 << StrArg->getSourceRange(); 95 return true; 96 } 97 98 TheCall->setType(Ty); 99 return false; 100 } 101 102 /// Check that the argument to __builtin_addressof is a glvalue, and set the 103 /// result type to the corresponding pointer type. 104 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 105 if (checkArgCount(S, TheCall, 1)) 106 return true; 107 108 ExprResult Arg(TheCall->getArg(0)); 109 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 110 if (ResultType.isNull()) 111 return true; 112 113 TheCall->setArg(0, Arg.get()); 114 TheCall->setType(ResultType); 115 return false; 116 } 117 118 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 119 if (checkArgCount(S, TheCall, 3)) 120 return true; 121 122 // First two arguments should be integers. 123 for (unsigned I = 0; I < 2; ++I) { 124 Expr *Arg = TheCall->getArg(I); 125 QualType Ty = Arg->getType(); 126 if (!Ty->isIntegerType()) { 127 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int) 128 << Ty << Arg->getSourceRange(); 129 return true; 130 } 131 } 132 133 // Third argument should be a pointer to a non-const integer. 134 // IRGen correctly handles volatile, restrict, and address spaces, and 135 // the other qualifiers aren't possible. 136 { 137 Expr *Arg = TheCall->getArg(2); 138 QualType Ty = Arg->getType(); 139 const auto *PtrTy = Ty->getAs<PointerType>(); 140 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 141 !PtrTy->getPointeeType().isConstQualified())) { 142 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int) 143 << Ty << Arg->getSourceRange(); 144 return true; 145 } 146 } 147 148 return false; 149 } 150 151 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 152 CallExpr *TheCall, unsigned SizeIdx, 153 unsigned DstSizeIdx) { 154 if (TheCall->getNumArgs() <= SizeIdx || 155 TheCall->getNumArgs() <= DstSizeIdx) 156 return; 157 158 const Expr *SizeArg = TheCall->getArg(SizeIdx); 159 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 160 161 llvm::APSInt Size, DstSize; 162 163 // find out if both sizes are known at compile time 164 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 165 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 166 return; 167 168 if (Size.ule(DstSize)) 169 return; 170 171 // confirmed overflow so generate the diagnostic. 172 IdentifierInfo *FnName = FDecl->getIdentifier(); 173 SourceLocation SL = TheCall->getLocStart(); 174 SourceRange SR = TheCall->getSourceRange(); 175 176 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; 177 } 178 179 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 180 if (checkArgCount(S, BuiltinCall, 2)) 181 return true; 182 183 SourceLocation BuiltinLoc = BuiltinCall->getLocStart(); 184 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 185 Expr *Call = BuiltinCall->getArg(0); 186 Expr *Chain = BuiltinCall->getArg(1); 187 188 if (Call->getStmtClass() != Stmt::CallExprClass) { 189 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 190 << Call->getSourceRange(); 191 return true; 192 } 193 194 auto CE = cast<CallExpr>(Call); 195 if (CE->getCallee()->getType()->isBlockPointerType()) { 196 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 197 << Call->getSourceRange(); 198 return true; 199 } 200 201 const Decl *TargetDecl = CE->getCalleeDecl(); 202 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 203 if (FD->getBuiltinID()) { 204 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 205 << Call->getSourceRange(); 206 return true; 207 } 208 209 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 210 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 211 << Call->getSourceRange(); 212 return true; 213 } 214 215 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 216 if (ChainResult.isInvalid()) 217 return true; 218 if (!ChainResult.get()->getType()->isPointerType()) { 219 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 220 << Chain->getSourceRange(); 221 return true; 222 } 223 224 QualType ReturnTy = CE->getCallReturnType(S.Context); 225 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 226 QualType BuiltinTy = S.Context.getFunctionType( 227 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 228 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 229 230 Builtin = 231 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 232 233 BuiltinCall->setType(CE->getType()); 234 BuiltinCall->setValueKind(CE->getValueKind()); 235 BuiltinCall->setObjectKind(CE->getObjectKind()); 236 BuiltinCall->setCallee(Builtin); 237 BuiltinCall->setArg(1, ChainResult.get()); 238 239 return false; 240 } 241 242 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 243 Scope::ScopeFlags NeededScopeFlags, 244 unsigned DiagID) { 245 // Scopes aren't available during instantiation. Fortunately, builtin 246 // functions cannot be template args so they cannot be formed through template 247 // instantiation. Therefore checking once during the parse is sufficient. 248 if (!SemaRef.ActiveTemplateInstantiations.empty()) 249 return false; 250 251 Scope *S = SemaRef.getCurScope(); 252 while (S && !S->isSEHExceptScope()) 253 S = S->getParent(); 254 if (!S || !(S->getFlags() & NeededScopeFlags)) { 255 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 256 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 257 << DRE->getDecl()->getIdentifier(); 258 return true; 259 } 260 261 return false; 262 } 263 264 static inline bool isBlockPointer(Expr *Arg) { 265 return Arg->getType()->isBlockPointerType(); 266 } 267 268 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 269 /// void*, which is a requirement of device side enqueue. 270 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 271 const BlockPointerType *BPT = 272 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 273 ArrayRef<QualType> Params = 274 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 275 unsigned ArgCounter = 0; 276 bool IllegalParams = false; 277 // Iterate through the block parameters until either one is found that is not 278 // a local void*, or the block is valid. 279 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 280 I != E; ++I, ++ArgCounter) { 281 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 282 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 283 LangAS::opencl_local) { 284 // Get the location of the error. If a block literal has been passed 285 // (BlockExpr) then we can point straight to the offending argument, 286 // else we just point to the variable reference. 287 SourceLocation ErrorLoc; 288 if (isa<BlockExpr>(BlockArg)) { 289 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 290 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart(); 291 } else if (isa<DeclRefExpr>(BlockArg)) { 292 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart(); 293 } 294 S.Diag(ErrorLoc, 295 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 296 IllegalParams = true; 297 } 298 } 299 300 return IllegalParams; 301 } 302 303 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 304 /// get_kernel_work_group_size 305 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 306 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 307 if (checkArgCount(S, TheCall, 1)) 308 return true; 309 310 Expr *BlockArg = TheCall->getArg(0); 311 if (!isBlockPointer(BlockArg)) { 312 S.Diag(BlockArg->getLocStart(), 313 diag::err_opencl_enqueue_kernel_expected_type) << "block"; 314 return true; 315 } 316 return checkOpenCLBlockArgs(S, BlockArg); 317 } 318 319 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 320 unsigned Start, unsigned End); 321 322 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 323 /// 'local void*' parameter of passed block. 324 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 325 Expr *BlockArg, 326 unsigned NumNonVarArgs) { 327 const BlockPointerType *BPT = 328 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 329 unsigned NumBlockParams = 330 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 331 unsigned TotalNumArgs = TheCall->getNumArgs(); 332 333 // For each argument passed to the block, a corresponding uint needs to 334 // be passed to describe the size of the local memory. 335 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 336 S.Diag(TheCall->getLocStart(), 337 diag::err_opencl_enqueue_kernel_local_size_args); 338 return true; 339 } 340 341 // Check that the sizes of the local memory are specified by integers. 342 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 343 TotalNumArgs - 1); 344 } 345 346 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 347 /// overload formats specified in Table 6.13.17.1. 348 /// int enqueue_kernel(queue_t queue, 349 /// kernel_enqueue_flags_t flags, 350 /// const ndrange_t ndrange, 351 /// void (^block)(void)) 352 /// int enqueue_kernel(queue_t queue, 353 /// kernel_enqueue_flags_t flags, 354 /// const ndrange_t ndrange, 355 /// uint num_events_in_wait_list, 356 /// clk_event_t *event_wait_list, 357 /// clk_event_t *event_ret, 358 /// void (^block)(void)) 359 /// int enqueue_kernel(queue_t queue, 360 /// kernel_enqueue_flags_t flags, 361 /// const ndrange_t ndrange, 362 /// void (^block)(local void*, ...), 363 /// uint size0, ...) 364 /// int enqueue_kernel(queue_t queue, 365 /// kernel_enqueue_flags_t flags, 366 /// const ndrange_t ndrange, 367 /// uint num_events_in_wait_list, 368 /// clk_event_t *event_wait_list, 369 /// clk_event_t *event_ret, 370 /// void (^block)(local void*, ...), 371 /// uint size0, ...) 372 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 373 unsigned NumArgs = TheCall->getNumArgs(); 374 375 if (NumArgs < 4) { 376 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args); 377 return true; 378 } 379 380 Expr *Arg0 = TheCall->getArg(0); 381 Expr *Arg1 = TheCall->getArg(1); 382 Expr *Arg2 = TheCall->getArg(2); 383 Expr *Arg3 = TheCall->getArg(3); 384 385 // First argument always needs to be a queue_t type. 386 if (!Arg0->getType()->isQueueT()) { 387 S.Diag(TheCall->getArg(0)->getLocStart(), 388 diag::err_opencl_enqueue_kernel_expected_type) 389 << S.Context.OCLQueueTy; 390 return true; 391 } 392 393 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 394 if (!Arg1->getType()->isIntegerType()) { 395 S.Diag(TheCall->getArg(1)->getLocStart(), 396 diag::err_opencl_enqueue_kernel_expected_type) 397 << "'kernel_enqueue_flags_t' (i.e. uint)"; 398 return true; 399 } 400 401 // Third argument is always an ndrange_t type. 402 if (!Arg2->getType()->isNDRangeT()) { 403 S.Diag(TheCall->getArg(2)->getLocStart(), 404 diag::err_opencl_enqueue_kernel_expected_type) 405 << S.Context.OCLNDRangeTy; 406 return true; 407 } 408 409 // With four arguments, there is only one form that the function could be 410 // called in: no events and no variable arguments. 411 if (NumArgs == 4) { 412 // check that the last argument is the right block type. 413 if (!isBlockPointer(Arg3)) { 414 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type) 415 << "block"; 416 return true; 417 } 418 // we have a block type, check the prototype 419 const BlockPointerType *BPT = 420 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 421 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 422 S.Diag(Arg3->getLocStart(), 423 diag::err_opencl_enqueue_kernel_blocks_no_args); 424 return true; 425 } 426 return false; 427 } 428 // we can have block + varargs. 429 if (isBlockPointer(Arg3)) 430 return (checkOpenCLBlockArgs(S, Arg3) || 431 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 432 // last two cases with either exactly 7 args or 7 args and varargs. 433 if (NumArgs >= 7) { 434 // check common block argument. 435 Expr *Arg6 = TheCall->getArg(6); 436 if (!isBlockPointer(Arg6)) { 437 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type) 438 << "block"; 439 return true; 440 } 441 if (checkOpenCLBlockArgs(S, Arg6)) 442 return true; 443 444 // Forth argument has to be any integer type. 445 if (!Arg3->getType()->isIntegerType()) { 446 S.Diag(TheCall->getArg(3)->getLocStart(), 447 diag::err_opencl_enqueue_kernel_expected_type) 448 << "integer"; 449 return true; 450 } 451 // check remaining common arguments. 452 Expr *Arg4 = TheCall->getArg(4); 453 Expr *Arg5 = TheCall->getArg(5); 454 455 // Fith argument is always passed as pointers to clk_event_t. 456 if (!Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 457 S.Diag(TheCall->getArg(4)->getLocStart(), 458 diag::err_opencl_enqueue_kernel_expected_type) 459 << S.Context.getPointerType(S.Context.OCLClkEventTy); 460 return true; 461 } 462 463 // Sixth argument is always passed as pointers to clk_event_t. 464 if (!(Arg5->getType()->isPointerType() && 465 Arg5->getType()->getPointeeType()->isClkEventT())) { 466 S.Diag(TheCall->getArg(5)->getLocStart(), 467 diag::err_opencl_enqueue_kernel_expected_type) 468 << S.Context.getPointerType(S.Context.OCLClkEventTy); 469 return true; 470 } 471 472 if (NumArgs == 7) 473 return false; 474 475 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 476 } 477 478 // None of the specific case has been detected, give generic error 479 S.Diag(TheCall->getLocStart(), 480 diag::err_opencl_enqueue_kernel_incorrect_args); 481 return true; 482 } 483 484 /// Returns OpenCL access qual. 485 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 486 return D->getAttr<OpenCLAccessAttr>(); 487 } 488 489 /// Returns true if pipe element type is different from the pointer. 490 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 491 const Expr *Arg0 = Call->getArg(0); 492 // First argument type should always be pipe. 493 if (!Arg0->getType()->isPipeType()) { 494 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 495 << Call->getDirectCallee() << Arg0->getSourceRange(); 496 return true; 497 } 498 OpenCLAccessAttr *AccessQual = 499 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 500 // Validates the access qualifier is compatible with the call. 501 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 502 // read_only and write_only, and assumed to be read_only if no qualifier is 503 // specified. 504 switch (Call->getDirectCallee()->getBuiltinID()) { 505 case Builtin::BIread_pipe: 506 case Builtin::BIreserve_read_pipe: 507 case Builtin::BIcommit_read_pipe: 508 case Builtin::BIwork_group_reserve_read_pipe: 509 case Builtin::BIsub_group_reserve_read_pipe: 510 case Builtin::BIwork_group_commit_read_pipe: 511 case Builtin::BIsub_group_commit_read_pipe: 512 if (!(!AccessQual || AccessQual->isReadOnly())) { 513 S.Diag(Arg0->getLocStart(), 514 diag::err_opencl_builtin_pipe_invalid_access_modifier) 515 << "read_only" << Arg0->getSourceRange(); 516 return true; 517 } 518 break; 519 case Builtin::BIwrite_pipe: 520 case Builtin::BIreserve_write_pipe: 521 case Builtin::BIcommit_write_pipe: 522 case Builtin::BIwork_group_reserve_write_pipe: 523 case Builtin::BIsub_group_reserve_write_pipe: 524 case Builtin::BIwork_group_commit_write_pipe: 525 case Builtin::BIsub_group_commit_write_pipe: 526 if (!(AccessQual && AccessQual->isWriteOnly())) { 527 S.Diag(Arg0->getLocStart(), 528 diag::err_opencl_builtin_pipe_invalid_access_modifier) 529 << "write_only" << Arg0->getSourceRange(); 530 return true; 531 } 532 break; 533 default: 534 break; 535 } 536 return false; 537 } 538 539 /// Returns true if pipe element type is different from the pointer. 540 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 541 const Expr *Arg0 = Call->getArg(0); 542 const Expr *ArgIdx = Call->getArg(Idx); 543 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 544 const QualType EltTy = PipeTy->getElementType(); 545 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 546 // The Idx argument should be a pointer and the type of the pointer and 547 // the type of pipe element should also be the same. 548 if (!ArgTy || 549 !S.Context.hasSameType( 550 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 551 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 552 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 553 << ArgIdx->getType() << ArgIdx->getSourceRange(); 554 return true; 555 } 556 return false; 557 } 558 559 // \brief Performs semantic analysis for the read/write_pipe call. 560 // \param S Reference to the semantic analyzer. 561 // \param Call A pointer to the builtin call. 562 // \return True if a semantic error has been found, false otherwise. 563 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 564 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 565 // functions have two forms. 566 switch (Call->getNumArgs()) { 567 case 2: { 568 if (checkOpenCLPipeArg(S, Call)) 569 return true; 570 // The call with 2 arguments should be 571 // read/write_pipe(pipe T, T*). 572 // Check packet type T. 573 if (checkOpenCLPipePacketType(S, Call, 1)) 574 return true; 575 } break; 576 577 case 4: { 578 if (checkOpenCLPipeArg(S, Call)) 579 return true; 580 // The call with 4 arguments should be 581 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 582 // Check reserve_id_t. 583 if (!Call->getArg(1)->getType()->isReserveIDT()) { 584 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 585 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 586 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 587 return true; 588 } 589 590 // Check the index. 591 const Expr *Arg2 = Call->getArg(2); 592 if (!Arg2->getType()->isIntegerType() && 593 !Arg2->getType()->isUnsignedIntegerType()) { 594 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 595 << Call->getDirectCallee() << S.Context.UnsignedIntTy 596 << Arg2->getType() << Arg2->getSourceRange(); 597 return true; 598 } 599 600 // Check packet type T. 601 if (checkOpenCLPipePacketType(S, Call, 3)) 602 return true; 603 } break; 604 default: 605 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) 606 << Call->getDirectCallee() << Call->getSourceRange(); 607 return true; 608 } 609 610 return false; 611 } 612 613 // \brief Performs a semantic analysis on the {work_group_/sub_group_ 614 // /_}reserve_{read/write}_pipe 615 // \param S Reference to the semantic analyzer. 616 // \param Call The call to the builtin function to be analyzed. 617 // \return True if a semantic error was found, false otherwise. 618 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 619 if (checkArgCount(S, Call, 2)) 620 return true; 621 622 if (checkOpenCLPipeArg(S, Call)) 623 return true; 624 625 // Check the reserve size. 626 if (!Call->getArg(1)->getType()->isIntegerType() && 627 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 628 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 629 << Call->getDirectCallee() << S.Context.UnsignedIntTy 630 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 631 return true; 632 } 633 634 return false; 635 } 636 637 // \brief Performs a semantic analysis on {work_group_/sub_group_ 638 // /_}commit_{read/write}_pipe 639 // \param S Reference to the semantic analyzer. 640 // \param Call The call to the builtin function to be analyzed. 641 // \return True if a semantic error was found, false otherwise. 642 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 643 if (checkArgCount(S, Call, 2)) 644 return true; 645 646 if (checkOpenCLPipeArg(S, Call)) 647 return true; 648 649 // Check reserve_id_t. 650 if (!Call->getArg(1)->getType()->isReserveIDT()) { 651 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 652 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 653 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 654 return true; 655 } 656 657 return false; 658 } 659 660 // \brief Performs a semantic analysis on the call to built-in Pipe 661 // Query Functions. 662 // \param S Reference to the semantic analyzer. 663 // \param Call The call to the builtin function to be analyzed. 664 // \return True if a semantic error was found, false otherwise. 665 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 666 if (checkArgCount(S, Call, 1)) 667 return true; 668 669 if (!Call->getArg(0)->getType()->isPipeType()) { 670 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 671 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 672 return true; 673 } 674 675 return false; 676 } 677 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions. 678 // \brief Performs semantic analysis for the to_global/local/private call. 679 // \param S Reference to the semantic analyzer. 680 // \param BuiltinID ID of the builtin function. 681 // \param Call A pointer to the builtin call. 682 // \return True if a semantic error has been found, false otherwise. 683 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 684 CallExpr *Call) { 685 if (Call->getNumArgs() != 1) { 686 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 687 << Call->getDirectCallee() << Call->getSourceRange(); 688 return true; 689 } 690 691 auto RT = Call->getArg(0)->getType(); 692 if (!RT->isPointerType() || RT->getPointeeType() 693 .getAddressSpace() == LangAS::opencl_constant) { 694 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 695 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 696 return true; 697 } 698 699 RT = RT->getPointeeType(); 700 auto Qual = RT.getQualifiers(); 701 switch (BuiltinID) { 702 case Builtin::BIto_global: 703 Qual.setAddressSpace(LangAS::opencl_global); 704 break; 705 case Builtin::BIto_local: 706 Qual.setAddressSpace(LangAS::opencl_local); 707 break; 708 default: 709 Qual.removeAddressSpace(); 710 } 711 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 712 RT.getUnqualifiedType(), Qual))); 713 714 return false; 715 } 716 717 ExprResult 718 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 719 CallExpr *TheCall) { 720 ExprResult TheCallResult(TheCall); 721 722 // Find out if any arguments are required to be integer constant expressions. 723 unsigned ICEArguments = 0; 724 ASTContext::GetBuiltinTypeError Error; 725 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 726 if (Error != ASTContext::GE_None) 727 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 728 729 // If any arguments are required to be ICE's, check and diagnose. 730 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 731 // Skip arguments not required to be ICE's. 732 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 733 734 llvm::APSInt Result; 735 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 736 return true; 737 ICEArguments &= ~(1 << ArgNo); 738 } 739 740 switch (BuiltinID) { 741 case Builtin::BI__builtin___CFStringMakeConstantString: 742 assert(TheCall->getNumArgs() == 1 && 743 "Wrong # arguments to builtin CFStringMakeConstantString"); 744 if (CheckObjCString(TheCall->getArg(0))) 745 return ExprError(); 746 break; 747 case Builtin::BI__builtin_stdarg_start: 748 case Builtin::BI__builtin_va_start: 749 if (SemaBuiltinVAStart(TheCall)) 750 return ExprError(); 751 break; 752 case Builtin::BI__va_start: { 753 switch (Context.getTargetInfo().getTriple().getArch()) { 754 case llvm::Triple::arm: 755 case llvm::Triple::thumb: 756 if (SemaBuiltinVAStartARM(TheCall)) 757 return ExprError(); 758 break; 759 default: 760 if (SemaBuiltinVAStart(TheCall)) 761 return ExprError(); 762 break; 763 } 764 break; 765 } 766 case Builtin::BI__builtin_isgreater: 767 case Builtin::BI__builtin_isgreaterequal: 768 case Builtin::BI__builtin_isless: 769 case Builtin::BI__builtin_islessequal: 770 case Builtin::BI__builtin_islessgreater: 771 case Builtin::BI__builtin_isunordered: 772 if (SemaBuiltinUnorderedCompare(TheCall)) 773 return ExprError(); 774 break; 775 case Builtin::BI__builtin_fpclassify: 776 if (SemaBuiltinFPClassification(TheCall, 6)) 777 return ExprError(); 778 break; 779 case Builtin::BI__builtin_isfinite: 780 case Builtin::BI__builtin_isinf: 781 case Builtin::BI__builtin_isinf_sign: 782 case Builtin::BI__builtin_isnan: 783 case Builtin::BI__builtin_isnormal: 784 if (SemaBuiltinFPClassification(TheCall, 1)) 785 return ExprError(); 786 break; 787 case Builtin::BI__builtin_shufflevector: 788 return SemaBuiltinShuffleVector(TheCall); 789 // TheCall will be freed by the smart pointer here, but that's fine, since 790 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 791 case Builtin::BI__builtin_prefetch: 792 if (SemaBuiltinPrefetch(TheCall)) 793 return ExprError(); 794 break; 795 case Builtin::BI__assume: 796 case Builtin::BI__builtin_assume: 797 if (SemaBuiltinAssume(TheCall)) 798 return ExprError(); 799 break; 800 case Builtin::BI__builtin_assume_aligned: 801 if (SemaBuiltinAssumeAligned(TheCall)) 802 return ExprError(); 803 break; 804 case Builtin::BI__builtin_object_size: 805 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 806 return ExprError(); 807 break; 808 case Builtin::BI__builtin_longjmp: 809 if (SemaBuiltinLongjmp(TheCall)) 810 return ExprError(); 811 break; 812 case Builtin::BI__builtin_setjmp: 813 if (SemaBuiltinSetjmp(TheCall)) 814 return ExprError(); 815 break; 816 case Builtin::BI_setjmp: 817 case Builtin::BI_setjmpex: 818 if (checkArgCount(*this, TheCall, 1)) 819 return true; 820 break; 821 822 case Builtin::BI__builtin_classify_type: 823 if (checkArgCount(*this, TheCall, 1)) return true; 824 TheCall->setType(Context.IntTy); 825 break; 826 case Builtin::BI__builtin_constant_p: 827 if (checkArgCount(*this, TheCall, 1)) return true; 828 TheCall->setType(Context.IntTy); 829 break; 830 case Builtin::BI__sync_fetch_and_add: 831 case Builtin::BI__sync_fetch_and_add_1: 832 case Builtin::BI__sync_fetch_and_add_2: 833 case Builtin::BI__sync_fetch_and_add_4: 834 case Builtin::BI__sync_fetch_and_add_8: 835 case Builtin::BI__sync_fetch_and_add_16: 836 case Builtin::BI__sync_fetch_and_sub: 837 case Builtin::BI__sync_fetch_and_sub_1: 838 case Builtin::BI__sync_fetch_and_sub_2: 839 case Builtin::BI__sync_fetch_and_sub_4: 840 case Builtin::BI__sync_fetch_and_sub_8: 841 case Builtin::BI__sync_fetch_and_sub_16: 842 case Builtin::BI__sync_fetch_and_or: 843 case Builtin::BI__sync_fetch_and_or_1: 844 case Builtin::BI__sync_fetch_and_or_2: 845 case Builtin::BI__sync_fetch_and_or_4: 846 case Builtin::BI__sync_fetch_and_or_8: 847 case Builtin::BI__sync_fetch_and_or_16: 848 case Builtin::BI__sync_fetch_and_and: 849 case Builtin::BI__sync_fetch_and_and_1: 850 case Builtin::BI__sync_fetch_and_and_2: 851 case Builtin::BI__sync_fetch_and_and_4: 852 case Builtin::BI__sync_fetch_and_and_8: 853 case Builtin::BI__sync_fetch_and_and_16: 854 case Builtin::BI__sync_fetch_and_xor: 855 case Builtin::BI__sync_fetch_and_xor_1: 856 case Builtin::BI__sync_fetch_and_xor_2: 857 case Builtin::BI__sync_fetch_and_xor_4: 858 case Builtin::BI__sync_fetch_and_xor_8: 859 case Builtin::BI__sync_fetch_and_xor_16: 860 case Builtin::BI__sync_fetch_and_nand: 861 case Builtin::BI__sync_fetch_and_nand_1: 862 case Builtin::BI__sync_fetch_and_nand_2: 863 case Builtin::BI__sync_fetch_and_nand_4: 864 case Builtin::BI__sync_fetch_and_nand_8: 865 case Builtin::BI__sync_fetch_and_nand_16: 866 case Builtin::BI__sync_add_and_fetch: 867 case Builtin::BI__sync_add_and_fetch_1: 868 case Builtin::BI__sync_add_and_fetch_2: 869 case Builtin::BI__sync_add_and_fetch_4: 870 case Builtin::BI__sync_add_and_fetch_8: 871 case Builtin::BI__sync_add_and_fetch_16: 872 case Builtin::BI__sync_sub_and_fetch: 873 case Builtin::BI__sync_sub_and_fetch_1: 874 case Builtin::BI__sync_sub_and_fetch_2: 875 case Builtin::BI__sync_sub_and_fetch_4: 876 case Builtin::BI__sync_sub_and_fetch_8: 877 case Builtin::BI__sync_sub_and_fetch_16: 878 case Builtin::BI__sync_and_and_fetch: 879 case Builtin::BI__sync_and_and_fetch_1: 880 case Builtin::BI__sync_and_and_fetch_2: 881 case Builtin::BI__sync_and_and_fetch_4: 882 case Builtin::BI__sync_and_and_fetch_8: 883 case Builtin::BI__sync_and_and_fetch_16: 884 case Builtin::BI__sync_or_and_fetch: 885 case Builtin::BI__sync_or_and_fetch_1: 886 case Builtin::BI__sync_or_and_fetch_2: 887 case Builtin::BI__sync_or_and_fetch_4: 888 case Builtin::BI__sync_or_and_fetch_8: 889 case Builtin::BI__sync_or_and_fetch_16: 890 case Builtin::BI__sync_xor_and_fetch: 891 case Builtin::BI__sync_xor_and_fetch_1: 892 case Builtin::BI__sync_xor_and_fetch_2: 893 case Builtin::BI__sync_xor_and_fetch_4: 894 case Builtin::BI__sync_xor_and_fetch_8: 895 case Builtin::BI__sync_xor_and_fetch_16: 896 case Builtin::BI__sync_nand_and_fetch: 897 case Builtin::BI__sync_nand_and_fetch_1: 898 case Builtin::BI__sync_nand_and_fetch_2: 899 case Builtin::BI__sync_nand_and_fetch_4: 900 case Builtin::BI__sync_nand_and_fetch_8: 901 case Builtin::BI__sync_nand_and_fetch_16: 902 case Builtin::BI__sync_val_compare_and_swap: 903 case Builtin::BI__sync_val_compare_and_swap_1: 904 case Builtin::BI__sync_val_compare_and_swap_2: 905 case Builtin::BI__sync_val_compare_and_swap_4: 906 case Builtin::BI__sync_val_compare_and_swap_8: 907 case Builtin::BI__sync_val_compare_and_swap_16: 908 case Builtin::BI__sync_bool_compare_and_swap: 909 case Builtin::BI__sync_bool_compare_and_swap_1: 910 case Builtin::BI__sync_bool_compare_and_swap_2: 911 case Builtin::BI__sync_bool_compare_and_swap_4: 912 case Builtin::BI__sync_bool_compare_and_swap_8: 913 case Builtin::BI__sync_bool_compare_and_swap_16: 914 case Builtin::BI__sync_lock_test_and_set: 915 case Builtin::BI__sync_lock_test_and_set_1: 916 case Builtin::BI__sync_lock_test_and_set_2: 917 case Builtin::BI__sync_lock_test_and_set_4: 918 case Builtin::BI__sync_lock_test_and_set_8: 919 case Builtin::BI__sync_lock_test_and_set_16: 920 case Builtin::BI__sync_lock_release: 921 case Builtin::BI__sync_lock_release_1: 922 case Builtin::BI__sync_lock_release_2: 923 case Builtin::BI__sync_lock_release_4: 924 case Builtin::BI__sync_lock_release_8: 925 case Builtin::BI__sync_lock_release_16: 926 case Builtin::BI__sync_swap: 927 case Builtin::BI__sync_swap_1: 928 case Builtin::BI__sync_swap_2: 929 case Builtin::BI__sync_swap_4: 930 case Builtin::BI__sync_swap_8: 931 case Builtin::BI__sync_swap_16: 932 return SemaBuiltinAtomicOverloaded(TheCallResult); 933 case Builtin::BI__builtin_nontemporal_load: 934 case Builtin::BI__builtin_nontemporal_store: 935 return SemaBuiltinNontemporalOverloaded(TheCallResult); 936 #define BUILTIN(ID, TYPE, ATTRS) 937 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 938 case Builtin::BI##ID: \ 939 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 940 #include "clang/Basic/Builtins.def" 941 case Builtin::BI__builtin_annotation: 942 if (SemaBuiltinAnnotation(*this, TheCall)) 943 return ExprError(); 944 break; 945 case Builtin::BI__builtin_addressof: 946 if (SemaBuiltinAddressof(*this, TheCall)) 947 return ExprError(); 948 break; 949 case Builtin::BI__builtin_add_overflow: 950 case Builtin::BI__builtin_sub_overflow: 951 case Builtin::BI__builtin_mul_overflow: 952 if (SemaBuiltinOverflow(*this, TheCall)) 953 return ExprError(); 954 break; 955 case Builtin::BI__builtin_operator_new: 956 case Builtin::BI__builtin_operator_delete: 957 if (!getLangOpts().CPlusPlus) { 958 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 959 << (BuiltinID == Builtin::BI__builtin_operator_new 960 ? "__builtin_operator_new" 961 : "__builtin_operator_delete") 962 << "C++"; 963 return ExprError(); 964 } 965 // CodeGen assumes it can find the global new and delete to call, 966 // so ensure that they are declared. 967 DeclareGlobalNewDelete(); 968 break; 969 970 // check secure string manipulation functions where overflows 971 // are detectable at compile time 972 case Builtin::BI__builtin___memcpy_chk: 973 case Builtin::BI__builtin___memmove_chk: 974 case Builtin::BI__builtin___memset_chk: 975 case Builtin::BI__builtin___strlcat_chk: 976 case Builtin::BI__builtin___strlcpy_chk: 977 case Builtin::BI__builtin___strncat_chk: 978 case Builtin::BI__builtin___strncpy_chk: 979 case Builtin::BI__builtin___stpncpy_chk: 980 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 981 break; 982 case Builtin::BI__builtin___memccpy_chk: 983 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 984 break; 985 case Builtin::BI__builtin___snprintf_chk: 986 case Builtin::BI__builtin___vsnprintf_chk: 987 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 988 break; 989 case Builtin::BI__builtin_call_with_static_chain: 990 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 991 return ExprError(); 992 break; 993 case Builtin::BI__exception_code: 994 case Builtin::BI_exception_code: 995 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 996 diag::err_seh___except_block)) 997 return ExprError(); 998 break; 999 case Builtin::BI__exception_info: 1000 case Builtin::BI_exception_info: 1001 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1002 diag::err_seh___except_filter)) 1003 return ExprError(); 1004 break; 1005 case Builtin::BI__GetExceptionInfo: 1006 if (checkArgCount(*this, TheCall, 1)) 1007 return ExprError(); 1008 1009 if (CheckCXXThrowOperand( 1010 TheCall->getLocStart(), 1011 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1012 TheCall)) 1013 return ExprError(); 1014 1015 TheCall->setType(Context.VoidPtrTy); 1016 break; 1017 // OpenCL v2.0, s6.13.16 - Pipe functions 1018 case Builtin::BIread_pipe: 1019 case Builtin::BIwrite_pipe: 1020 // Since those two functions are declared with var args, we need a semantic 1021 // check for the argument. 1022 if (SemaBuiltinRWPipe(*this, TheCall)) 1023 return ExprError(); 1024 break; 1025 case Builtin::BIreserve_read_pipe: 1026 case Builtin::BIreserve_write_pipe: 1027 case Builtin::BIwork_group_reserve_read_pipe: 1028 case Builtin::BIwork_group_reserve_write_pipe: 1029 case Builtin::BIsub_group_reserve_read_pipe: 1030 case Builtin::BIsub_group_reserve_write_pipe: 1031 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1032 return ExprError(); 1033 // Since return type of reserve_read/write_pipe built-in function is 1034 // reserve_id_t, which is not defined in the builtin def file , we used int 1035 // as return type and need to override the return type of these functions. 1036 TheCall->setType(Context.OCLReserveIDTy); 1037 break; 1038 case Builtin::BIcommit_read_pipe: 1039 case Builtin::BIcommit_write_pipe: 1040 case Builtin::BIwork_group_commit_read_pipe: 1041 case Builtin::BIwork_group_commit_write_pipe: 1042 case Builtin::BIsub_group_commit_read_pipe: 1043 case Builtin::BIsub_group_commit_write_pipe: 1044 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1045 return ExprError(); 1046 break; 1047 case Builtin::BIget_pipe_num_packets: 1048 case Builtin::BIget_pipe_max_packets: 1049 if (SemaBuiltinPipePackets(*this, TheCall)) 1050 return ExprError(); 1051 break; 1052 case Builtin::BIto_global: 1053 case Builtin::BIto_local: 1054 case Builtin::BIto_private: 1055 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1056 return ExprError(); 1057 break; 1058 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1059 case Builtin::BIenqueue_kernel: 1060 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1061 return ExprError(); 1062 break; 1063 case Builtin::BIget_kernel_work_group_size: 1064 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1065 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1066 return ExprError(); 1067 } 1068 1069 // Since the target specific builtins for each arch overlap, only check those 1070 // of the arch we are compiling for. 1071 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1072 switch (Context.getTargetInfo().getTriple().getArch()) { 1073 case llvm::Triple::arm: 1074 case llvm::Triple::armeb: 1075 case llvm::Triple::thumb: 1076 case llvm::Triple::thumbeb: 1077 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1078 return ExprError(); 1079 break; 1080 case llvm::Triple::aarch64: 1081 case llvm::Triple::aarch64_be: 1082 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1083 return ExprError(); 1084 break; 1085 case llvm::Triple::mips: 1086 case llvm::Triple::mipsel: 1087 case llvm::Triple::mips64: 1088 case llvm::Triple::mips64el: 1089 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1090 return ExprError(); 1091 break; 1092 case llvm::Triple::systemz: 1093 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1094 return ExprError(); 1095 break; 1096 case llvm::Triple::x86: 1097 case llvm::Triple::x86_64: 1098 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1099 return ExprError(); 1100 break; 1101 case llvm::Triple::ppc: 1102 case llvm::Triple::ppc64: 1103 case llvm::Triple::ppc64le: 1104 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1105 return ExprError(); 1106 break; 1107 default: 1108 break; 1109 } 1110 } 1111 1112 return TheCallResult; 1113 } 1114 1115 // Get the valid immediate range for the specified NEON type code. 1116 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1117 NeonTypeFlags Type(t); 1118 int IsQuad = ForceQuad ? true : Type.isQuad(); 1119 switch (Type.getEltType()) { 1120 case NeonTypeFlags::Int8: 1121 case NeonTypeFlags::Poly8: 1122 return shift ? 7 : (8 << IsQuad) - 1; 1123 case NeonTypeFlags::Int16: 1124 case NeonTypeFlags::Poly16: 1125 return shift ? 15 : (4 << IsQuad) - 1; 1126 case NeonTypeFlags::Int32: 1127 return shift ? 31 : (2 << IsQuad) - 1; 1128 case NeonTypeFlags::Int64: 1129 case NeonTypeFlags::Poly64: 1130 return shift ? 63 : (1 << IsQuad) - 1; 1131 case NeonTypeFlags::Poly128: 1132 return shift ? 127 : (1 << IsQuad) - 1; 1133 case NeonTypeFlags::Float16: 1134 assert(!shift && "cannot shift float types!"); 1135 return (4 << IsQuad) - 1; 1136 case NeonTypeFlags::Float32: 1137 assert(!shift && "cannot shift float types!"); 1138 return (2 << IsQuad) - 1; 1139 case NeonTypeFlags::Float64: 1140 assert(!shift && "cannot shift float types!"); 1141 return (1 << IsQuad) - 1; 1142 } 1143 llvm_unreachable("Invalid NeonTypeFlag!"); 1144 } 1145 1146 /// getNeonEltType - Return the QualType corresponding to the elements of 1147 /// the vector type specified by the NeonTypeFlags. This is used to check 1148 /// the pointer arguments for Neon load/store intrinsics. 1149 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1150 bool IsPolyUnsigned, bool IsInt64Long) { 1151 switch (Flags.getEltType()) { 1152 case NeonTypeFlags::Int8: 1153 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1154 case NeonTypeFlags::Int16: 1155 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1156 case NeonTypeFlags::Int32: 1157 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1158 case NeonTypeFlags::Int64: 1159 if (IsInt64Long) 1160 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1161 else 1162 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1163 : Context.LongLongTy; 1164 case NeonTypeFlags::Poly8: 1165 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1166 case NeonTypeFlags::Poly16: 1167 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1168 case NeonTypeFlags::Poly64: 1169 if (IsInt64Long) 1170 return Context.UnsignedLongTy; 1171 else 1172 return Context.UnsignedLongLongTy; 1173 case NeonTypeFlags::Poly128: 1174 break; 1175 case NeonTypeFlags::Float16: 1176 return Context.HalfTy; 1177 case NeonTypeFlags::Float32: 1178 return Context.FloatTy; 1179 case NeonTypeFlags::Float64: 1180 return Context.DoubleTy; 1181 } 1182 llvm_unreachable("Invalid NeonTypeFlag!"); 1183 } 1184 1185 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1186 llvm::APSInt Result; 1187 uint64_t mask = 0; 1188 unsigned TV = 0; 1189 int PtrArgNum = -1; 1190 bool HasConstPtr = false; 1191 switch (BuiltinID) { 1192 #define GET_NEON_OVERLOAD_CHECK 1193 #include "clang/Basic/arm_neon.inc" 1194 #undef GET_NEON_OVERLOAD_CHECK 1195 } 1196 1197 // For NEON intrinsics which are overloaded on vector element type, validate 1198 // the immediate which specifies which variant to emit. 1199 unsigned ImmArg = TheCall->getNumArgs()-1; 1200 if (mask) { 1201 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1202 return true; 1203 1204 TV = Result.getLimitedValue(64); 1205 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1206 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1207 << TheCall->getArg(ImmArg)->getSourceRange(); 1208 } 1209 1210 if (PtrArgNum >= 0) { 1211 // Check that pointer arguments have the specified type. 1212 Expr *Arg = TheCall->getArg(PtrArgNum); 1213 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1214 Arg = ICE->getSubExpr(); 1215 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1216 QualType RHSTy = RHS.get()->getType(); 1217 1218 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1219 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64; 1220 bool IsInt64Long = 1221 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1222 QualType EltTy = 1223 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1224 if (HasConstPtr) 1225 EltTy = EltTy.withConst(); 1226 QualType LHSTy = Context.getPointerType(EltTy); 1227 AssignConvertType ConvTy; 1228 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1229 if (RHS.isInvalid()) 1230 return true; 1231 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1232 RHS.get(), AA_Assigning)) 1233 return true; 1234 } 1235 1236 // For NEON intrinsics which take an immediate value as part of the 1237 // instruction, range check them here. 1238 unsigned i = 0, l = 0, u = 0; 1239 switch (BuiltinID) { 1240 default: 1241 return false; 1242 #define GET_NEON_IMMEDIATE_CHECK 1243 #include "clang/Basic/arm_neon.inc" 1244 #undef GET_NEON_IMMEDIATE_CHECK 1245 } 1246 1247 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1248 } 1249 1250 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1251 unsigned MaxWidth) { 1252 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1253 BuiltinID == ARM::BI__builtin_arm_ldaex || 1254 BuiltinID == ARM::BI__builtin_arm_strex || 1255 BuiltinID == ARM::BI__builtin_arm_stlex || 1256 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1257 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1258 BuiltinID == AArch64::BI__builtin_arm_strex || 1259 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1260 "unexpected ARM builtin"); 1261 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1262 BuiltinID == ARM::BI__builtin_arm_ldaex || 1263 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1264 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1265 1266 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1267 1268 // Ensure that we have the proper number of arguments. 1269 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1270 return true; 1271 1272 // Inspect the pointer argument of the atomic builtin. This should always be 1273 // a pointer type, whose element is an integral scalar or pointer type. 1274 // Because it is a pointer type, we don't have to worry about any implicit 1275 // casts here. 1276 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1277 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1278 if (PointerArgRes.isInvalid()) 1279 return true; 1280 PointerArg = PointerArgRes.get(); 1281 1282 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1283 if (!pointerType) { 1284 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1285 << PointerArg->getType() << PointerArg->getSourceRange(); 1286 return true; 1287 } 1288 1289 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1290 // task is to insert the appropriate casts into the AST. First work out just 1291 // what the appropriate type is. 1292 QualType ValType = pointerType->getPointeeType(); 1293 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1294 if (IsLdrex) 1295 AddrType.addConst(); 1296 1297 // Issue a warning if the cast is dodgy. 1298 CastKind CastNeeded = CK_NoOp; 1299 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1300 CastNeeded = CK_BitCast; 1301 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1302 << PointerArg->getType() 1303 << Context.getPointerType(AddrType) 1304 << AA_Passing << PointerArg->getSourceRange(); 1305 } 1306 1307 // Finally, do the cast and replace the argument with the corrected version. 1308 AddrType = Context.getPointerType(AddrType); 1309 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1310 if (PointerArgRes.isInvalid()) 1311 return true; 1312 PointerArg = PointerArgRes.get(); 1313 1314 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1315 1316 // In general, we allow ints, floats and pointers to be loaded and stored. 1317 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1318 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1319 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1320 << PointerArg->getType() << PointerArg->getSourceRange(); 1321 return true; 1322 } 1323 1324 // But ARM doesn't have instructions to deal with 128-bit versions. 1325 if (Context.getTypeSize(ValType) > MaxWidth) { 1326 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1327 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1328 << PointerArg->getType() << PointerArg->getSourceRange(); 1329 return true; 1330 } 1331 1332 switch (ValType.getObjCLifetime()) { 1333 case Qualifiers::OCL_None: 1334 case Qualifiers::OCL_ExplicitNone: 1335 // okay 1336 break; 1337 1338 case Qualifiers::OCL_Weak: 1339 case Qualifiers::OCL_Strong: 1340 case Qualifiers::OCL_Autoreleasing: 1341 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1342 << ValType << PointerArg->getSourceRange(); 1343 return true; 1344 } 1345 1346 if (IsLdrex) { 1347 TheCall->setType(ValType); 1348 return false; 1349 } 1350 1351 // Initialize the argument to be stored. 1352 ExprResult ValArg = TheCall->getArg(0); 1353 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1354 Context, ValType, /*consume*/ false); 1355 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1356 if (ValArg.isInvalid()) 1357 return true; 1358 TheCall->setArg(0, ValArg.get()); 1359 1360 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1361 // but the custom checker bypasses all default analysis. 1362 TheCall->setType(Context.IntTy); 1363 return false; 1364 } 1365 1366 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1367 llvm::APSInt Result; 1368 1369 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1370 BuiltinID == ARM::BI__builtin_arm_ldaex || 1371 BuiltinID == ARM::BI__builtin_arm_strex || 1372 BuiltinID == ARM::BI__builtin_arm_stlex) { 1373 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1374 } 1375 1376 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1377 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1378 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1379 } 1380 1381 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1382 BuiltinID == ARM::BI__builtin_arm_wsr64) 1383 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1384 1385 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1386 BuiltinID == ARM::BI__builtin_arm_rsrp || 1387 BuiltinID == ARM::BI__builtin_arm_wsr || 1388 BuiltinID == ARM::BI__builtin_arm_wsrp) 1389 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1390 1391 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1392 return true; 1393 1394 // For intrinsics which take an immediate value as part of the instruction, 1395 // range check them here. 1396 unsigned i = 0, l = 0, u = 0; 1397 switch (BuiltinID) { 1398 default: return false; 1399 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 1400 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 1401 case ARM::BI__builtin_arm_vcvtr_f: 1402 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 1403 case ARM::BI__builtin_arm_dmb: 1404 case ARM::BI__builtin_arm_dsb: 1405 case ARM::BI__builtin_arm_isb: 1406 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break; 1407 } 1408 1409 // FIXME: VFP Intrinsics should error if VFP not present. 1410 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1411 } 1412 1413 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1414 CallExpr *TheCall) { 1415 llvm::APSInt Result; 1416 1417 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1418 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1419 BuiltinID == AArch64::BI__builtin_arm_strex || 1420 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1421 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1422 } 1423 1424 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1425 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1426 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1427 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1428 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1429 } 1430 1431 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1432 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1433 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1434 1435 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1436 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1437 BuiltinID == AArch64::BI__builtin_arm_wsr || 1438 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1439 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1440 1441 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1442 return true; 1443 1444 // For intrinsics which take an immediate value as part of the instruction, 1445 // range check them here. 1446 unsigned i = 0, l = 0, u = 0; 1447 switch (BuiltinID) { 1448 default: return false; 1449 case AArch64::BI__builtin_arm_dmb: 1450 case AArch64::BI__builtin_arm_dsb: 1451 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1452 } 1453 1454 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1455 } 1456 1457 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1458 unsigned i = 0, l = 0, u = 0; 1459 switch (BuiltinID) { 1460 default: return false; 1461 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1462 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1463 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1464 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1465 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1466 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1467 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1468 } 1469 1470 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1471 } 1472 1473 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1474 unsigned i = 0, l = 0, u = 0; 1475 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 1476 BuiltinID == PPC::BI__builtin_divdeu || 1477 BuiltinID == PPC::BI__builtin_bpermd; 1478 bool IsTarget64Bit = Context.getTargetInfo() 1479 .getTypeWidth(Context 1480 .getTargetInfo() 1481 .getIntPtrType()) == 64; 1482 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 1483 BuiltinID == PPC::BI__builtin_divweu || 1484 BuiltinID == PPC::BI__builtin_divde || 1485 BuiltinID == PPC::BI__builtin_divdeu; 1486 1487 if (Is64BitBltin && !IsTarget64Bit) 1488 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 1489 << TheCall->getSourceRange(); 1490 1491 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 1492 (BuiltinID == PPC::BI__builtin_bpermd && 1493 !Context.getTargetInfo().hasFeature("bpermd"))) 1494 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 1495 << TheCall->getSourceRange(); 1496 1497 switch (BuiltinID) { 1498 default: return false; 1499 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 1500 case PPC::BI__builtin_altivec_crypto_vshasigmad: 1501 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1502 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1503 case PPC::BI__builtin_tbegin: 1504 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 1505 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 1506 case PPC::BI__builtin_tabortwc: 1507 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 1508 case PPC::BI__builtin_tabortwci: 1509 case PPC::BI__builtin_tabortdci: 1510 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 1511 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 1512 } 1513 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1514 } 1515 1516 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 1517 CallExpr *TheCall) { 1518 if (BuiltinID == SystemZ::BI__builtin_tabort) { 1519 Expr *Arg = TheCall->getArg(0); 1520 llvm::APSInt AbortCode(32); 1521 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 1522 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 1523 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 1524 << Arg->getSourceRange(); 1525 } 1526 1527 // For intrinsics which take an immediate value as part of the instruction, 1528 // range check them here. 1529 unsigned i = 0, l = 0, u = 0; 1530 switch (BuiltinID) { 1531 default: return false; 1532 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 1533 case SystemZ::BI__builtin_s390_verimb: 1534 case SystemZ::BI__builtin_s390_verimh: 1535 case SystemZ::BI__builtin_s390_verimf: 1536 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 1537 case SystemZ::BI__builtin_s390_vfaeb: 1538 case SystemZ::BI__builtin_s390_vfaeh: 1539 case SystemZ::BI__builtin_s390_vfaef: 1540 case SystemZ::BI__builtin_s390_vfaebs: 1541 case SystemZ::BI__builtin_s390_vfaehs: 1542 case SystemZ::BI__builtin_s390_vfaefs: 1543 case SystemZ::BI__builtin_s390_vfaezb: 1544 case SystemZ::BI__builtin_s390_vfaezh: 1545 case SystemZ::BI__builtin_s390_vfaezf: 1546 case SystemZ::BI__builtin_s390_vfaezbs: 1547 case SystemZ::BI__builtin_s390_vfaezhs: 1548 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 1549 case SystemZ::BI__builtin_s390_vfidb: 1550 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 1551 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1552 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 1553 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 1554 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 1555 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 1556 case SystemZ::BI__builtin_s390_vstrcb: 1557 case SystemZ::BI__builtin_s390_vstrch: 1558 case SystemZ::BI__builtin_s390_vstrcf: 1559 case SystemZ::BI__builtin_s390_vstrczb: 1560 case SystemZ::BI__builtin_s390_vstrczh: 1561 case SystemZ::BI__builtin_s390_vstrczf: 1562 case SystemZ::BI__builtin_s390_vstrcbs: 1563 case SystemZ::BI__builtin_s390_vstrchs: 1564 case SystemZ::BI__builtin_s390_vstrcfs: 1565 case SystemZ::BI__builtin_s390_vstrczbs: 1566 case SystemZ::BI__builtin_s390_vstrczhs: 1567 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 1568 } 1569 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1570 } 1571 1572 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 1573 /// This checks that the target supports __builtin_cpu_supports and 1574 /// that the string argument is constant and valid. 1575 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 1576 Expr *Arg = TheCall->getArg(0); 1577 1578 // Check if the argument is a string literal. 1579 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1580 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1581 << Arg->getSourceRange(); 1582 1583 // Check the contents of the string. 1584 StringRef Feature = 1585 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1586 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 1587 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 1588 << Arg->getSourceRange(); 1589 return false; 1590 } 1591 1592 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1593 int i = 0, l = 0, u = 0; 1594 switch (BuiltinID) { 1595 default: 1596 return false; 1597 case X86::BI__builtin_cpu_supports: 1598 return SemaBuiltinCpuSupports(*this, TheCall); 1599 case X86::BI__builtin_ms_va_start: 1600 return SemaBuiltinMSVAStart(TheCall); 1601 case X86::BI__builtin_ia32_extractf64x4_mask: 1602 case X86::BI__builtin_ia32_extracti64x4_mask: 1603 case X86::BI__builtin_ia32_extractf32x8_mask: 1604 case X86::BI__builtin_ia32_extracti32x8_mask: 1605 case X86::BI__builtin_ia32_extractf64x2_256_mask: 1606 case X86::BI__builtin_ia32_extracti64x2_256_mask: 1607 case X86::BI__builtin_ia32_extractf32x4_256_mask: 1608 case X86::BI__builtin_ia32_extracti32x4_256_mask: 1609 i = 1; l = 0; u = 1; 1610 break; 1611 case X86::BI_mm_prefetch: 1612 case X86::BI__builtin_ia32_extractf32x4_mask: 1613 case X86::BI__builtin_ia32_extracti32x4_mask: 1614 case X86::BI__builtin_ia32_extractf64x2_512_mask: 1615 case X86::BI__builtin_ia32_extracti64x2_512_mask: 1616 i = 1; l = 0; u = 3; 1617 break; 1618 case X86::BI__builtin_ia32_insertf32x8_mask: 1619 case X86::BI__builtin_ia32_inserti32x8_mask: 1620 case X86::BI__builtin_ia32_insertf64x4_mask: 1621 case X86::BI__builtin_ia32_inserti64x4_mask: 1622 case X86::BI__builtin_ia32_insertf64x2_256_mask: 1623 case X86::BI__builtin_ia32_inserti64x2_256_mask: 1624 case X86::BI__builtin_ia32_insertf32x4_256_mask: 1625 case X86::BI__builtin_ia32_inserti32x4_256_mask: 1626 i = 2; l = 0; u = 1; 1627 break; 1628 case X86::BI__builtin_ia32_sha1rnds4: 1629 case X86::BI__builtin_ia32_shuf_f32x4_256_mask: 1630 case X86::BI__builtin_ia32_shuf_f64x2_256_mask: 1631 case X86::BI__builtin_ia32_shuf_i32x4_256_mask: 1632 case X86::BI__builtin_ia32_shuf_i64x2_256_mask: 1633 case X86::BI__builtin_ia32_shufpd128_mask: 1634 case X86::BI__builtin_ia32_insertf64x2_512_mask: 1635 case X86::BI__builtin_ia32_inserti64x2_512_mask: 1636 case X86::BI__builtin_ia32_insertf32x4_mask: 1637 case X86::BI__builtin_ia32_inserti32x4_mask: 1638 i = 2; l = 0; u = 3; 1639 break; 1640 case X86::BI__builtin_ia32_vpermil2pd: 1641 case X86::BI__builtin_ia32_vpermil2pd256: 1642 case X86::BI__builtin_ia32_vpermil2ps: 1643 case X86::BI__builtin_ia32_vpermil2ps256: 1644 i = 3; l = 0; u = 3; 1645 break; 1646 case X86::BI__builtin_ia32_cmpb128_mask: 1647 case X86::BI__builtin_ia32_cmpw128_mask: 1648 case X86::BI__builtin_ia32_cmpd128_mask: 1649 case X86::BI__builtin_ia32_cmpq128_mask: 1650 case X86::BI__builtin_ia32_cmpb256_mask: 1651 case X86::BI__builtin_ia32_cmpw256_mask: 1652 case X86::BI__builtin_ia32_cmpd256_mask: 1653 case X86::BI__builtin_ia32_cmpq256_mask: 1654 case X86::BI__builtin_ia32_cmpb512_mask: 1655 case X86::BI__builtin_ia32_cmpw512_mask: 1656 case X86::BI__builtin_ia32_cmpd512_mask: 1657 case X86::BI__builtin_ia32_cmpq512_mask: 1658 case X86::BI__builtin_ia32_ucmpb128_mask: 1659 case X86::BI__builtin_ia32_ucmpw128_mask: 1660 case X86::BI__builtin_ia32_ucmpd128_mask: 1661 case X86::BI__builtin_ia32_ucmpq128_mask: 1662 case X86::BI__builtin_ia32_ucmpb256_mask: 1663 case X86::BI__builtin_ia32_ucmpw256_mask: 1664 case X86::BI__builtin_ia32_ucmpd256_mask: 1665 case X86::BI__builtin_ia32_ucmpq256_mask: 1666 case X86::BI__builtin_ia32_ucmpb512_mask: 1667 case X86::BI__builtin_ia32_ucmpw512_mask: 1668 case X86::BI__builtin_ia32_ucmpd512_mask: 1669 case X86::BI__builtin_ia32_ucmpq512_mask: 1670 case X86::BI__builtin_ia32_vpcomub: 1671 case X86::BI__builtin_ia32_vpcomuw: 1672 case X86::BI__builtin_ia32_vpcomud: 1673 case X86::BI__builtin_ia32_vpcomuq: 1674 case X86::BI__builtin_ia32_vpcomb: 1675 case X86::BI__builtin_ia32_vpcomw: 1676 case X86::BI__builtin_ia32_vpcomd: 1677 case X86::BI__builtin_ia32_vpcomq: 1678 i = 2; l = 0; u = 7; 1679 break; 1680 case X86::BI__builtin_ia32_roundps: 1681 case X86::BI__builtin_ia32_roundpd: 1682 case X86::BI__builtin_ia32_roundps256: 1683 case X86::BI__builtin_ia32_roundpd256: 1684 i = 1; l = 0; u = 15; 1685 break; 1686 case X86::BI__builtin_ia32_roundss: 1687 case X86::BI__builtin_ia32_roundsd: 1688 case X86::BI__builtin_ia32_rangepd128_mask: 1689 case X86::BI__builtin_ia32_rangepd256_mask: 1690 case X86::BI__builtin_ia32_rangepd512_mask: 1691 case X86::BI__builtin_ia32_rangeps128_mask: 1692 case X86::BI__builtin_ia32_rangeps256_mask: 1693 case X86::BI__builtin_ia32_rangeps512_mask: 1694 case X86::BI__builtin_ia32_getmantsd_round_mask: 1695 case X86::BI__builtin_ia32_getmantss_round_mask: 1696 case X86::BI__builtin_ia32_shufpd256_mask: 1697 i = 2; l = 0; u = 15; 1698 break; 1699 case X86::BI__builtin_ia32_cmpps: 1700 case X86::BI__builtin_ia32_cmpss: 1701 case X86::BI__builtin_ia32_cmppd: 1702 case X86::BI__builtin_ia32_cmpsd: 1703 case X86::BI__builtin_ia32_cmpps256: 1704 case X86::BI__builtin_ia32_cmppd256: 1705 case X86::BI__builtin_ia32_cmpps128_mask: 1706 case X86::BI__builtin_ia32_cmppd128_mask: 1707 case X86::BI__builtin_ia32_cmpps256_mask: 1708 case X86::BI__builtin_ia32_cmppd256_mask: 1709 case X86::BI__builtin_ia32_cmpps512_mask: 1710 case X86::BI__builtin_ia32_cmppd512_mask: 1711 case X86::BI__builtin_ia32_cmpsd_mask: 1712 case X86::BI__builtin_ia32_cmpss_mask: 1713 i = 2; l = 0; u = 31; 1714 break; 1715 case X86::BI__builtin_ia32_xabort: 1716 i = 0; l = -128; u = 255; 1717 break; 1718 case X86::BI__builtin_ia32_pshufw: 1719 case X86::BI__builtin_ia32_aeskeygenassist128: 1720 i = 1; l = -128; u = 255; 1721 break; 1722 case X86::BI__builtin_ia32_vcvtps2ph: 1723 case X86::BI__builtin_ia32_vcvtps2ph256: 1724 case X86::BI__builtin_ia32_vcvtps2ph512: 1725 case X86::BI__builtin_ia32_rndscaleps_128_mask: 1726 case X86::BI__builtin_ia32_rndscalepd_128_mask: 1727 case X86::BI__builtin_ia32_rndscaleps_256_mask: 1728 case X86::BI__builtin_ia32_rndscalepd_256_mask: 1729 case X86::BI__builtin_ia32_rndscaleps_mask: 1730 case X86::BI__builtin_ia32_rndscalepd_mask: 1731 case X86::BI__builtin_ia32_reducepd128_mask: 1732 case X86::BI__builtin_ia32_reducepd256_mask: 1733 case X86::BI__builtin_ia32_reducepd512_mask: 1734 case X86::BI__builtin_ia32_reduceps128_mask: 1735 case X86::BI__builtin_ia32_reduceps256_mask: 1736 case X86::BI__builtin_ia32_reduceps512_mask: 1737 case X86::BI__builtin_ia32_prold512_mask: 1738 case X86::BI__builtin_ia32_prolq512_mask: 1739 case X86::BI__builtin_ia32_prold128_mask: 1740 case X86::BI__builtin_ia32_prold256_mask: 1741 case X86::BI__builtin_ia32_prolq128_mask: 1742 case X86::BI__builtin_ia32_prolq256_mask: 1743 case X86::BI__builtin_ia32_prord128_mask: 1744 case X86::BI__builtin_ia32_prord256_mask: 1745 case X86::BI__builtin_ia32_prorq128_mask: 1746 case X86::BI__builtin_ia32_prorq256_mask: 1747 case X86::BI__builtin_ia32_psllwi512_mask: 1748 case X86::BI__builtin_ia32_psllwi128_mask: 1749 case X86::BI__builtin_ia32_psllwi256_mask: 1750 case X86::BI__builtin_ia32_psrldi128_mask: 1751 case X86::BI__builtin_ia32_psrldi256_mask: 1752 case X86::BI__builtin_ia32_psrldi512_mask: 1753 case X86::BI__builtin_ia32_psrlqi128_mask: 1754 case X86::BI__builtin_ia32_psrlqi256_mask: 1755 case X86::BI__builtin_ia32_psrlqi512_mask: 1756 case X86::BI__builtin_ia32_psrawi512_mask: 1757 case X86::BI__builtin_ia32_psrawi128_mask: 1758 case X86::BI__builtin_ia32_psrawi256_mask: 1759 case X86::BI__builtin_ia32_psrlwi512_mask: 1760 case X86::BI__builtin_ia32_psrlwi128_mask: 1761 case X86::BI__builtin_ia32_psrlwi256_mask: 1762 case X86::BI__builtin_ia32_psradi128_mask: 1763 case X86::BI__builtin_ia32_psradi256_mask: 1764 case X86::BI__builtin_ia32_psradi512_mask: 1765 case X86::BI__builtin_ia32_psraqi128_mask: 1766 case X86::BI__builtin_ia32_psraqi256_mask: 1767 case X86::BI__builtin_ia32_psraqi512_mask: 1768 case X86::BI__builtin_ia32_pslldi128_mask: 1769 case X86::BI__builtin_ia32_pslldi256_mask: 1770 case X86::BI__builtin_ia32_pslldi512_mask: 1771 case X86::BI__builtin_ia32_psllqi128_mask: 1772 case X86::BI__builtin_ia32_psllqi256_mask: 1773 case X86::BI__builtin_ia32_psllqi512_mask: 1774 case X86::BI__builtin_ia32_fpclasspd128_mask: 1775 case X86::BI__builtin_ia32_fpclasspd256_mask: 1776 case X86::BI__builtin_ia32_fpclassps128_mask: 1777 case X86::BI__builtin_ia32_fpclassps256_mask: 1778 case X86::BI__builtin_ia32_fpclassps512_mask: 1779 case X86::BI__builtin_ia32_fpclasspd512_mask: 1780 case X86::BI__builtin_ia32_fpclasssd_mask: 1781 case X86::BI__builtin_ia32_fpclassss_mask: 1782 i = 1; l = 0; u = 255; 1783 break; 1784 case X86::BI__builtin_ia32_palignr: 1785 case X86::BI__builtin_ia32_insertps128: 1786 case X86::BI__builtin_ia32_dpps: 1787 case X86::BI__builtin_ia32_dppd: 1788 case X86::BI__builtin_ia32_dpps256: 1789 case X86::BI__builtin_ia32_mpsadbw128: 1790 case X86::BI__builtin_ia32_mpsadbw256: 1791 case X86::BI__builtin_ia32_pcmpistrm128: 1792 case X86::BI__builtin_ia32_pcmpistri128: 1793 case X86::BI__builtin_ia32_pcmpistria128: 1794 case X86::BI__builtin_ia32_pcmpistric128: 1795 case X86::BI__builtin_ia32_pcmpistrio128: 1796 case X86::BI__builtin_ia32_pcmpistris128: 1797 case X86::BI__builtin_ia32_pcmpistriz128: 1798 case X86::BI__builtin_ia32_pclmulqdq128: 1799 case X86::BI__builtin_ia32_vperm2f128_pd256: 1800 case X86::BI__builtin_ia32_vperm2f128_ps256: 1801 case X86::BI__builtin_ia32_vperm2f128_si256: 1802 case X86::BI__builtin_ia32_permti256: 1803 i = 2; l = -128; u = 255; 1804 break; 1805 case X86::BI__builtin_ia32_palignr128: 1806 case X86::BI__builtin_ia32_palignr256: 1807 case X86::BI__builtin_ia32_palignr128_mask: 1808 case X86::BI__builtin_ia32_palignr256_mask: 1809 case X86::BI__builtin_ia32_palignr512_mask: 1810 case X86::BI__builtin_ia32_alignq512_mask: 1811 case X86::BI__builtin_ia32_alignd512_mask: 1812 case X86::BI__builtin_ia32_alignd128_mask: 1813 case X86::BI__builtin_ia32_alignd256_mask: 1814 case X86::BI__builtin_ia32_alignq128_mask: 1815 case X86::BI__builtin_ia32_alignq256_mask: 1816 case X86::BI__builtin_ia32_vcomisd: 1817 case X86::BI__builtin_ia32_vcomiss: 1818 case X86::BI__builtin_ia32_shuf_f32x4_mask: 1819 case X86::BI__builtin_ia32_shuf_f64x2_mask: 1820 case X86::BI__builtin_ia32_shuf_i32x4_mask: 1821 case X86::BI__builtin_ia32_shuf_i64x2_mask: 1822 case X86::BI__builtin_ia32_shufpd512_mask: 1823 case X86::BI__builtin_ia32_shufps128_mask: 1824 case X86::BI__builtin_ia32_shufps256_mask: 1825 case X86::BI__builtin_ia32_shufps512_mask: 1826 case X86::BI__builtin_ia32_dbpsadbw128_mask: 1827 case X86::BI__builtin_ia32_dbpsadbw256_mask: 1828 case X86::BI__builtin_ia32_dbpsadbw512_mask: 1829 i = 2; l = 0; u = 255; 1830 break; 1831 case X86::BI__builtin_ia32_fixupimmpd512_mask: 1832 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 1833 case X86::BI__builtin_ia32_fixupimmps512_mask: 1834 case X86::BI__builtin_ia32_fixupimmps512_maskz: 1835 case X86::BI__builtin_ia32_fixupimmsd_mask: 1836 case X86::BI__builtin_ia32_fixupimmsd_maskz: 1837 case X86::BI__builtin_ia32_fixupimmss_mask: 1838 case X86::BI__builtin_ia32_fixupimmss_maskz: 1839 case X86::BI__builtin_ia32_fixupimmpd128_mask: 1840 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 1841 case X86::BI__builtin_ia32_fixupimmpd256_mask: 1842 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 1843 case X86::BI__builtin_ia32_fixupimmps128_mask: 1844 case X86::BI__builtin_ia32_fixupimmps128_maskz: 1845 case X86::BI__builtin_ia32_fixupimmps256_mask: 1846 case X86::BI__builtin_ia32_fixupimmps256_maskz: 1847 case X86::BI__builtin_ia32_pternlogd512_mask: 1848 case X86::BI__builtin_ia32_pternlogd512_maskz: 1849 case X86::BI__builtin_ia32_pternlogq512_mask: 1850 case X86::BI__builtin_ia32_pternlogq512_maskz: 1851 case X86::BI__builtin_ia32_pternlogd128_mask: 1852 case X86::BI__builtin_ia32_pternlogd128_maskz: 1853 case X86::BI__builtin_ia32_pternlogd256_mask: 1854 case X86::BI__builtin_ia32_pternlogd256_maskz: 1855 case X86::BI__builtin_ia32_pternlogq128_mask: 1856 case X86::BI__builtin_ia32_pternlogq128_maskz: 1857 case X86::BI__builtin_ia32_pternlogq256_mask: 1858 case X86::BI__builtin_ia32_pternlogq256_maskz: 1859 i = 3; l = 0; u = 255; 1860 break; 1861 case X86::BI__builtin_ia32_pcmpestrm128: 1862 case X86::BI__builtin_ia32_pcmpestri128: 1863 case X86::BI__builtin_ia32_pcmpestria128: 1864 case X86::BI__builtin_ia32_pcmpestric128: 1865 case X86::BI__builtin_ia32_pcmpestrio128: 1866 case X86::BI__builtin_ia32_pcmpestris128: 1867 case X86::BI__builtin_ia32_pcmpestriz128: 1868 i = 4; l = -128; u = 255; 1869 break; 1870 case X86::BI__builtin_ia32_rndscalesd_round_mask: 1871 case X86::BI__builtin_ia32_rndscaless_round_mask: 1872 i = 4; l = 0; u = 255; 1873 break; 1874 } 1875 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1876 } 1877 1878 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 1879 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 1880 /// Returns true when the format fits the function and the FormatStringInfo has 1881 /// been populated. 1882 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 1883 FormatStringInfo *FSI) { 1884 FSI->HasVAListArg = Format->getFirstArg() == 0; 1885 FSI->FormatIdx = Format->getFormatIdx() - 1; 1886 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 1887 1888 // The way the format attribute works in GCC, the implicit this argument 1889 // of member functions is counted. However, it doesn't appear in our own 1890 // lists, so decrement format_idx in that case. 1891 if (IsCXXMember) { 1892 if(FSI->FormatIdx == 0) 1893 return false; 1894 --FSI->FormatIdx; 1895 if (FSI->FirstDataArg != 0) 1896 --FSI->FirstDataArg; 1897 } 1898 return true; 1899 } 1900 1901 /// Checks if a the given expression evaluates to null. 1902 /// 1903 /// \brief Returns true if the value evaluates to null. 1904 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 1905 // If the expression has non-null type, it doesn't evaluate to null. 1906 if (auto nullability 1907 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 1908 if (*nullability == NullabilityKind::NonNull) 1909 return false; 1910 } 1911 1912 // As a special case, transparent unions initialized with zero are 1913 // considered null for the purposes of the nonnull attribute. 1914 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 1915 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1916 if (const CompoundLiteralExpr *CLE = 1917 dyn_cast<CompoundLiteralExpr>(Expr)) 1918 if (const InitListExpr *ILE = 1919 dyn_cast<InitListExpr>(CLE->getInitializer())) 1920 Expr = ILE->getInit(0); 1921 } 1922 1923 bool Result; 1924 return (!Expr->isValueDependent() && 1925 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 1926 !Result); 1927 } 1928 1929 static void CheckNonNullArgument(Sema &S, 1930 const Expr *ArgExpr, 1931 SourceLocation CallSiteLoc) { 1932 if (CheckNonNullExpr(S, ArgExpr)) 1933 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 1934 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 1935 } 1936 1937 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 1938 FormatStringInfo FSI; 1939 if ((GetFormatStringType(Format) == FST_NSString) && 1940 getFormatStringInfo(Format, false, &FSI)) { 1941 Idx = FSI.FormatIdx; 1942 return true; 1943 } 1944 return false; 1945 } 1946 /// \brief Diagnose use of %s directive in an NSString which is being passed 1947 /// as formatting string to formatting method. 1948 static void 1949 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 1950 const NamedDecl *FDecl, 1951 Expr **Args, 1952 unsigned NumArgs) { 1953 unsigned Idx = 0; 1954 bool Format = false; 1955 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 1956 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 1957 Idx = 2; 1958 Format = true; 1959 } 1960 else 1961 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 1962 if (S.GetFormatNSStringIdx(I, Idx)) { 1963 Format = true; 1964 break; 1965 } 1966 } 1967 if (!Format || NumArgs <= Idx) 1968 return; 1969 const Expr *FormatExpr = Args[Idx]; 1970 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 1971 FormatExpr = CSCE->getSubExpr(); 1972 const StringLiteral *FormatString; 1973 if (const ObjCStringLiteral *OSL = 1974 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 1975 FormatString = OSL->getString(); 1976 else 1977 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 1978 if (!FormatString) 1979 return; 1980 if (S.FormatStringHasSArg(FormatString)) { 1981 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 1982 << "%s" << 1 << 1; 1983 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 1984 << FDecl->getDeclName(); 1985 } 1986 } 1987 1988 /// Determine whether the given type has a non-null nullability annotation. 1989 static bool isNonNullType(ASTContext &ctx, QualType type) { 1990 if (auto nullability = type->getNullability(ctx)) 1991 return *nullability == NullabilityKind::NonNull; 1992 1993 return false; 1994 } 1995 1996 static void CheckNonNullArguments(Sema &S, 1997 const NamedDecl *FDecl, 1998 const FunctionProtoType *Proto, 1999 ArrayRef<const Expr *> Args, 2000 SourceLocation CallSiteLoc) { 2001 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2002 2003 // Check the attributes attached to the method/function itself. 2004 llvm::SmallBitVector NonNullArgs; 2005 if (FDecl) { 2006 // Handle the nonnull attribute on the function/method declaration itself. 2007 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2008 if (!NonNull->args_size()) { 2009 // Easy case: all pointer arguments are nonnull. 2010 for (const auto *Arg : Args) 2011 if (S.isValidPointerAttrType(Arg->getType())) 2012 CheckNonNullArgument(S, Arg, CallSiteLoc); 2013 return; 2014 } 2015 2016 for (unsigned Val : NonNull->args()) { 2017 if (Val >= Args.size()) 2018 continue; 2019 if (NonNullArgs.empty()) 2020 NonNullArgs.resize(Args.size()); 2021 NonNullArgs.set(Val); 2022 } 2023 } 2024 } 2025 2026 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2027 // Handle the nonnull attribute on the parameters of the 2028 // function/method. 2029 ArrayRef<ParmVarDecl*> parms; 2030 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2031 parms = FD->parameters(); 2032 else 2033 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2034 2035 unsigned ParamIndex = 0; 2036 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2037 I != E; ++I, ++ParamIndex) { 2038 const ParmVarDecl *PVD = *I; 2039 if (PVD->hasAttr<NonNullAttr>() || 2040 isNonNullType(S.Context, PVD->getType())) { 2041 if (NonNullArgs.empty()) 2042 NonNullArgs.resize(Args.size()); 2043 2044 NonNullArgs.set(ParamIndex); 2045 } 2046 } 2047 } else { 2048 // If we have a non-function, non-method declaration but no 2049 // function prototype, try to dig out the function prototype. 2050 if (!Proto) { 2051 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2052 QualType type = VD->getType().getNonReferenceType(); 2053 if (auto pointerType = type->getAs<PointerType>()) 2054 type = pointerType->getPointeeType(); 2055 else if (auto blockType = type->getAs<BlockPointerType>()) 2056 type = blockType->getPointeeType(); 2057 // FIXME: data member pointers? 2058 2059 // Dig out the function prototype, if there is one. 2060 Proto = type->getAs<FunctionProtoType>(); 2061 } 2062 } 2063 2064 // Fill in non-null argument information from the nullability 2065 // information on the parameter types (if we have them). 2066 if (Proto) { 2067 unsigned Index = 0; 2068 for (auto paramType : Proto->getParamTypes()) { 2069 if (isNonNullType(S.Context, paramType)) { 2070 if (NonNullArgs.empty()) 2071 NonNullArgs.resize(Args.size()); 2072 2073 NonNullArgs.set(Index); 2074 } 2075 2076 ++Index; 2077 } 2078 } 2079 } 2080 2081 // Check for non-null arguments. 2082 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2083 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2084 if (NonNullArgs[ArgIndex]) 2085 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2086 } 2087 } 2088 2089 /// Handles the checks for format strings, non-POD arguments to vararg 2090 /// functions, and NULL arguments passed to non-NULL parameters. 2091 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2092 ArrayRef<const Expr *> Args, bool IsMemberFunction, 2093 SourceLocation Loc, SourceRange Range, 2094 VariadicCallType CallType) { 2095 // FIXME: We should check as much as we can in the template definition. 2096 if (CurContext->isDependentContext()) 2097 return; 2098 2099 // Printf and scanf checking. 2100 llvm::SmallBitVector CheckedVarArgs; 2101 if (FDecl) { 2102 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2103 // Only create vector if there are format attributes. 2104 CheckedVarArgs.resize(Args.size()); 2105 2106 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2107 CheckedVarArgs); 2108 } 2109 } 2110 2111 // Refuse POD arguments that weren't caught by the format string 2112 // checks above. 2113 if (CallType != VariadicDoesNotApply) { 2114 unsigned NumParams = Proto ? Proto->getNumParams() 2115 : FDecl && isa<FunctionDecl>(FDecl) 2116 ? cast<FunctionDecl>(FDecl)->getNumParams() 2117 : FDecl && isa<ObjCMethodDecl>(FDecl) 2118 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2119 : 0; 2120 2121 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2122 // Args[ArgIdx] can be null in malformed code. 2123 if (const Expr *Arg = Args[ArgIdx]) { 2124 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 2125 checkVariadicArgument(Arg, CallType); 2126 } 2127 } 2128 } 2129 2130 if (FDecl || Proto) { 2131 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 2132 2133 // Type safety checking. 2134 if (FDecl) { 2135 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 2136 CheckArgumentWithTypeTag(I, Args.data()); 2137 } 2138 } 2139 } 2140 2141 /// CheckConstructorCall - Check a constructor call for correctness and safety 2142 /// properties not enforced by the C type system. 2143 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 2144 ArrayRef<const Expr *> Args, 2145 const FunctionProtoType *Proto, 2146 SourceLocation Loc) { 2147 VariadicCallType CallType = 2148 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 2149 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(), 2150 CallType); 2151 } 2152 2153 /// CheckFunctionCall - Check a direct function call for various correctness 2154 /// and safety properties not strictly enforced by the C type system. 2155 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2156 const FunctionProtoType *Proto) { 2157 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 2158 isa<CXXMethodDecl>(FDecl); 2159 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 2160 IsMemberOperatorCall; 2161 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 2162 TheCall->getCallee()); 2163 Expr** Args = TheCall->getArgs(); 2164 unsigned NumArgs = TheCall->getNumArgs(); 2165 if (IsMemberOperatorCall) { 2166 // If this is a call to a member operator, hide the first argument 2167 // from checkCall. 2168 // FIXME: Our choice of AST representation here is less than ideal. 2169 ++Args; 2170 --NumArgs; 2171 } 2172 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs), 2173 IsMemberFunction, TheCall->getRParenLoc(), 2174 TheCall->getCallee()->getSourceRange(), CallType); 2175 2176 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 2177 // None of the checks below are needed for functions that don't have 2178 // simple names (e.g., C++ conversion functions). 2179 if (!FnInfo) 2180 return false; 2181 2182 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo); 2183 if (getLangOpts().ObjC1) 2184 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 2185 2186 unsigned CMId = FDecl->getMemoryFunctionKind(); 2187 if (CMId == 0) 2188 return false; 2189 2190 // Handle memory setting and copying functions. 2191 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 2192 CheckStrlcpycatArguments(TheCall, FnInfo); 2193 else if (CMId == Builtin::BIstrncat) 2194 CheckStrncatArguments(TheCall, FnInfo); 2195 else 2196 CheckMemaccessArguments(TheCall, CMId, FnInfo); 2197 2198 return false; 2199 } 2200 2201 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 2202 ArrayRef<const Expr *> Args) { 2203 VariadicCallType CallType = 2204 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 2205 2206 checkCall(Method, nullptr, Args, 2207 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 2208 CallType); 2209 2210 return false; 2211 } 2212 2213 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2214 const FunctionProtoType *Proto) { 2215 QualType Ty; 2216 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 2217 Ty = V->getType().getNonReferenceType(); 2218 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 2219 Ty = F->getType().getNonReferenceType(); 2220 else 2221 return false; 2222 2223 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 2224 !Ty->isFunctionProtoType()) 2225 return false; 2226 2227 VariadicCallType CallType; 2228 if (!Proto || !Proto->isVariadic()) { 2229 CallType = VariadicDoesNotApply; 2230 } else if (Ty->isBlockPointerType()) { 2231 CallType = VariadicBlock; 2232 } else { // Ty->isFunctionPointerType() 2233 CallType = VariadicFunction; 2234 } 2235 2236 checkCall(NDecl, Proto, 2237 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2238 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2239 TheCall->getCallee()->getSourceRange(), CallType); 2240 2241 return false; 2242 } 2243 2244 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2245 /// such as function pointers returned from functions. 2246 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 2247 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 2248 TheCall->getCallee()); 2249 checkCall(/*FDecl=*/nullptr, Proto, 2250 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2251 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2252 TheCall->getCallee()->getSourceRange(), CallType); 2253 2254 return false; 2255 } 2256 2257 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 2258 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 2259 return false; 2260 2261 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 2262 switch (Op) { 2263 case AtomicExpr::AO__c11_atomic_init: 2264 llvm_unreachable("There is no ordering argument for an init"); 2265 2266 case AtomicExpr::AO__c11_atomic_load: 2267 case AtomicExpr::AO__atomic_load_n: 2268 case AtomicExpr::AO__atomic_load: 2269 return OrderingCABI != llvm::AtomicOrderingCABI::release && 2270 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2271 2272 case AtomicExpr::AO__c11_atomic_store: 2273 case AtomicExpr::AO__atomic_store: 2274 case AtomicExpr::AO__atomic_store_n: 2275 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 2276 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 2277 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2278 2279 default: 2280 return true; 2281 } 2282 } 2283 2284 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 2285 AtomicExpr::AtomicOp Op) { 2286 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 2287 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2288 2289 // All these operations take one of the following forms: 2290 enum { 2291 // C __c11_atomic_init(A *, C) 2292 Init, 2293 // C __c11_atomic_load(A *, int) 2294 Load, 2295 // void __atomic_load(A *, CP, int) 2296 LoadCopy, 2297 // void __atomic_store(A *, CP, int) 2298 Copy, 2299 // C __c11_atomic_add(A *, M, int) 2300 Arithmetic, 2301 // C __atomic_exchange_n(A *, CP, int) 2302 Xchg, 2303 // void __atomic_exchange(A *, C *, CP, int) 2304 GNUXchg, 2305 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 2306 C11CmpXchg, 2307 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 2308 GNUCmpXchg 2309 } Form = Init; 2310 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 2311 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 2312 // where: 2313 // C is an appropriate type, 2314 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 2315 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 2316 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 2317 // the int parameters are for orderings. 2318 2319 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 2320 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 2321 AtomicExpr::AO__atomic_load, 2322 "need to update code for modified C11 atomics"); 2323 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init && 2324 Op <= AtomicExpr::AO__c11_atomic_fetch_xor; 2325 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 2326 Op == AtomicExpr::AO__atomic_store_n || 2327 Op == AtomicExpr::AO__atomic_exchange_n || 2328 Op == AtomicExpr::AO__atomic_compare_exchange_n; 2329 bool IsAddSub = false; 2330 2331 switch (Op) { 2332 case AtomicExpr::AO__c11_atomic_init: 2333 Form = Init; 2334 break; 2335 2336 case AtomicExpr::AO__c11_atomic_load: 2337 case AtomicExpr::AO__atomic_load_n: 2338 Form = Load; 2339 break; 2340 2341 case AtomicExpr::AO__atomic_load: 2342 Form = LoadCopy; 2343 break; 2344 2345 case AtomicExpr::AO__c11_atomic_store: 2346 case AtomicExpr::AO__atomic_store: 2347 case AtomicExpr::AO__atomic_store_n: 2348 Form = Copy; 2349 break; 2350 2351 case AtomicExpr::AO__c11_atomic_fetch_add: 2352 case AtomicExpr::AO__c11_atomic_fetch_sub: 2353 case AtomicExpr::AO__atomic_fetch_add: 2354 case AtomicExpr::AO__atomic_fetch_sub: 2355 case AtomicExpr::AO__atomic_add_fetch: 2356 case AtomicExpr::AO__atomic_sub_fetch: 2357 IsAddSub = true; 2358 // Fall through. 2359 case AtomicExpr::AO__c11_atomic_fetch_and: 2360 case AtomicExpr::AO__c11_atomic_fetch_or: 2361 case AtomicExpr::AO__c11_atomic_fetch_xor: 2362 case AtomicExpr::AO__atomic_fetch_and: 2363 case AtomicExpr::AO__atomic_fetch_or: 2364 case AtomicExpr::AO__atomic_fetch_xor: 2365 case AtomicExpr::AO__atomic_fetch_nand: 2366 case AtomicExpr::AO__atomic_and_fetch: 2367 case AtomicExpr::AO__atomic_or_fetch: 2368 case AtomicExpr::AO__atomic_xor_fetch: 2369 case AtomicExpr::AO__atomic_nand_fetch: 2370 Form = Arithmetic; 2371 break; 2372 2373 case AtomicExpr::AO__c11_atomic_exchange: 2374 case AtomicExpr::AO__atomic_exchange_n: 2375 Form = Xchg; 2376 break; 2377 2378 case AtomicExpr::AO__atomic_exchange: 2379 Form = GNUXchg; 2380 break; 2381 2382 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 2383 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 2384 Form = C11CmpXchg; 2385 break; 2386 2387 case AtomicExpr::AO__atomic_compare_exchange: 2388 case AtomicExpr::AO__atomic_compare_exchange_n: 2389 Form = GNUCmpXchg; 2390 break; 2391 } 2392 2393 // Check we have the right number of arguments. 2394 if (TheCall->getNumArgs() < NumArgs[Form]) { 2395 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 2396 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2397 << TheCall->getCallee()->getSourceRange(); 2398 return ExprError(); 2399 } else if (TheCall->getNumArgs() > NumArgs[Form]) { 2400 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(), 2401 diag::err_typecheck_call_too_many_args) 2402 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2403 << TheCall->getCallee()->getSourceRange(); 2404 return ExprError(); 2405 } 2406 2407 // Inspect the first argument of the atomic operation. 2408 Expr *Ptr = TheCall->getArg(0); 2409 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get(); 2410 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 2411 if (!pointerType) { 2412 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 2413 << Ptr->getType() << Ptr->getSourceRange(); 2414 return ExprError(); 2415 } 2416 2417 // For a __c11 builtin, this should be a pointer to an _Atomic type. 2418 QualType AtomTy = pointerType->getPointeeType(); // 'A' 2419 QualType ValType = AtomTy; // 'C' 2420 if (IsC11) { 2421 if (!AtomTy->isAtomicType()) { 2422 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 2423 << Ptr->getType() << Ptr->getSourceRange(); 2424 return ExprError(); 2425 } 2426 if (AtomTy.isConstQualified()) { 2427 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 2428 << Ptr->getType() << Ptr->getSourceRange(); 2429 return ExprError(); 2430 } 2431 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 2432 } else if (Form != Load && Form != LoadCopy) { 2433 if (ValType.isConstQualified()) { 2434 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 2435 << Ptr->getType() << Ptr->getSourceRange(); 2436 return ExprError(); 2437 } 2438 } 2439 2440 // For an arithmetic operation, the implied arithmetic must be well-formed. 2441 if (Form == Arithmetic) { 2442 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 2443 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 2444 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2445 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2446 return ExprError(); 2447 } 2448 if (!IsAddSub && !ValType->isIntegerType()) { 2449 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 2450 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2451 return ExprError(); 2452 } 2453 if (IsC11 && ValType->isPointerType() && 2454 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 2455 diag::err_incomplete_type)) { 2456 return ExprError(); 2457 } 2458 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 2459 // For __atomic_*_n operations, the value type must be a scalar integral or 2460 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 2461 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2462 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2463 return ExprError(); 2464 } 2465 2466 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 2467 !AtomTy->isScalarType()) { 2468 // For GNU atomics, require a trivially-copyable type. This is not part of 2469 // the GNU atomics specification, but we enforce it for sanity. 2470 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 2471 << Ptr->getType() << Ptr->getSourceRange(); 2472 return ExprError(); 2473 } 2474 2475 switch (ValType.getObjCLifetime()) { 2476 case Qualifiers::OCL_None: 2477 case Qualifiers::OCL_ExplicitNone: 2478 // okay 2479 break; 2480 2481 case Qualifiers::OCL_Weak: 2482 case Qualifiers::OCL_Strong: 2483 case Qualifiers::OCL_Autoreleasing: 2484 // FIXME: Can this happen? By this point, ValType should be known 2485 // to be trivially copyable. 2486 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 2487 << ValType << Ptr->getSourceRange(); 2488 return ExprError(); 2489 } 2490 2491 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 2492 // volatile-ness of the pointee-type inject itself into the result or the 2493 // other operands. Similarly atomic_load can take a pointer to a const 'A'. 2494 ValType.removeLocalVolatile(); 2495 ValType.removeLocalConst(); 2496 QualType ResultType = ValType; 2497 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init) 2498 ResultType = Context.VoidTy; 2499 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 2500 ResultType = Context.BoolTy; 2501 2502 // The type of a parameter passed 'by value'. In the GNU atomics, such 2503 // arguments are actually passed as pointers. 2504 QualType ByValType = ValType; // 'CP' 2505 if (!IsC11 && !IsN) 2506 ByValType = Ptr->getType(); 2507 2508 // The first argument --- the pointer --- has a fixed type; we 2509 // deduce the types of the rest of the arguments accordingly. Walk 2510 // the remaining arguments, converting them to the deduced value type. 2511 for (unsigned i = 1; i != NumArgs[Form]; ++i) { 2512 QualType Ty; 2513 if (i < NumVals[Form] + 1) { 2514 switch (i) { 2515 case 1: 2516 // The second argument is the non-atomic operand. For arithmetic, this 2517 // is always passed by value, and for a compare_exchange it is always 2518 // passed by address. For the rest, GNU uses by-address and C11 uses 2519 // by-value. 2520 assert(Form != Load); 2521 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 2522 Ty = ValType; 2523 else if (Form == Copy || Form == Xchg) 2524 Ty = ByValType; 2525 else if (Form == Arithmetic) 2526 Ty = Context.getPointerDiffType(); 2527 else { 2528 Expr *ValArg = TheCall->getArg(i); 2529 unsigned AS = 0; 2530 // Keep address space of non-atomic pointer type. 2531 if (const PointerType *PtrTy = 2532 ValArg->getType()->getAs<PointerType>()) { 2533 AS = PtrTy->getPointeeType().getAddressSpace(); 2534 } 2535 Ty = Context.getPointerType( 2536 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 2537 } 2538 break; 2539 case 2: 2540 // The third argument to compare_exchange / GNU exchange is a 2541 // (pointer to a) desired value. 2542 Ty = ByValType; 2543 break; 2544 case 3: 2545 // The fourth argument to GNU compare_exchange is a 'weak' flag. 2546 Ty = Context.BoolTy; 2547 break; 2548 } 2549 } else { 2550 // The order(s) are always converted to int. 2551 Ty = Context.IntTy; 2552 } 2553 2554 InitializedEntity Entity = 2555 InitializedEntity::InitializeParameter(Context, Ty, false); 2556 ExprResult Arg = TheCall->getArg(i); 2557 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 2558 if (Arg.isInvalid()) 2559 return true; 2560 TheCall->setArg(i, Arg.get()); 2561 } 2562 2563 // Permute the arguments into a 'consistent' order. 2564 SmallVector<Expr*, 5> SubExprs; 2565 SubExprs.push_back(Ptr); 2566 switch (Form) { 2567 case Init: 2568 // Note, AtomicExpr::getVal1() has a special case for this atomic. 2569 SubExprs.push_back(TheCall->getArg(1)); // Val1 2570 break; 2571 case Load: 2572 SubExprs.push_back(TheCall->getArg(1)); // Order 2573 break; 2574 case LoadCopy: 2575 case Copy: 2576 case Arithmetic: 2577 case Xchg: 2578 SubExprs.push_back(TheCall->getArg(2)); // Order 2579 SubExprs.push_back(TheCall->getArg(1)); // Val1 2580 break; 2581 case GNUXchg: 2582 // Note, AtomicExpr::getVal2() has a special case for this atomic. 2583 SubExprs.push_back(TheCall->getArg(3)); // Order 2584 SubExprs.push_back(TheCall->getArg(1)); // Val1 2585 SubExprs.push_back(TheCall->getArg(2)); // Val2 2586 break; 2587 case C11CmpXchg: 2588 SubExprs.push_back(TheCall->getArg(3)); // Order 2589 SubExprs.push_back(TheCall->getArg(1)); // Val1 2590 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 2591 SubExprs.push_back(TheCall->getArg(2)); // Val2 2592 break; 2593 case GNUCmpXchg: 2594 SubExprs.push_back(TheCall->getArg(4)); // Order 2595 SubExprs.push_back(TheCall->getArg(1)); // Val1 2596 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 2597 SubExprs.push_back(TheCall->getArg(2)); // Val2 2598 SubExprs.push_back(TheCall->getArg(3)); // Weak 2599 break; 2600 } 2601 2602 if (SubExprs.size() >= 2 && Form != Init) { 2603 llvm::APSInt Result(32); 2604 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 2605 !isValidOrderingForOp(Result.getSExtValue(), Op)) 2606 Diag(SubExprs[1]->getLocStart(), 2607 diag::warn_atomic_op_has_invalid_memory_order) 2608 << SubExprs[1]->getSourceRange(); 2609 } 2610 2611 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 2612 SubExprs, ResultType, Op, 2613 TheCall->getRParenLoc()); 2614 2615 if ((Op == AtomicExpr::AO__c11_atomic_load || 2616 (Op == AtomicExpr::AO__c11_atomic_store)) && 2617 Context.AtomicUsesUnsupportedLibcall(AE)) 2618 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) << 2619 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1); 2620 2621 return AE; 2622 } 2623 2624 /// checkBuiltinArgument - Given a call to a builtin function, perform 2625 /// normal type-checking on the given argument, updating the call in 2626 /// place. This is useful when a builtin function requires custom 2627 /// type-checking for some of its arguments but not necessarily all of 2628 /// them. 2629 /// 2630 /// Returns true on error. 2631 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 2632 FunctionDecl *Fn = E->getDirectCallee(); 2633 assert(Fn && "builtin call without direct callee!"); 2634 2635 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 2636 InitializedEntity Entity = 2637 InitializedEntity::InitializeParameter(S.Context, Param); 2638 2639 ExprResult Arg = E->getArg(0); 2640 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 2641 if (Arg.isInvalid()) 2642 return true; 2643 2644 E->setArg(ArgIndex, Arg.get()); 2645 return false; 2646 } 2647 2648 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 2649 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 2650 /// type of its first argument. The main ActOnCallExpr routines have already 2651 /// promoted the types of arguments because all of these calls are prototyped as 2652 /// void(...). 2653 /// 2654 /// This function goes through and does final semantic checking for these 2655 /// builtins, 2656 ExprResult 2657 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 2658 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 2659 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2660 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 2661 2662 // Ensure that we have at least one argument to do type inference from. 2663 if (TheCall->getNumArgs() < 1) { 2664 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 2665 << 0 << 1 << TheCall->getNumArgs() 2666 << TheCall->getCallee()->getSourceRange(); 2667 return ExprError(); 2668 } 2669 2670 // Inspect the first argument of the atomic builtin. This should always be 2671 // a pointer type, whose element is an integral scalar or pointer type. 2672 // Because it is a pointer type, we don't have to worry about any implicit 2673 // casts here. 2674 // FIXME: We don't allow floating point scalars as input. 2675 Expr *FirstArg = TheCall->getArg(0); 2676 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 2677 if (FirstArgResult.isInvalid()) 2678 return ExprError(); 2679 FirstArg = FirstArgResult.get(); 2680 TheCall->setArg(0, FirstArg); 2681 2682 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 2683 if (!pointerType) { 2684 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 2685 << FirstArg->getType() << FirstArg->getSourceRange(); 2686 return ExprError(); 2687 } 2688 2689 QualType ValType = pointerType->getPointeeType(); 2690 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2691 !ValType->isBlockPointerType()) { 2692 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 2693 << FirstArg->getType() << FirstArg->getSourceRange(); 2694 return ExprError(); 2695 } 2696 2697 switch (ValType.getObjCLifetime()) { 2698 case Qualifiers::OCL_None: 2699 case Qualifiers::OCL_ExplicitNone: 2700 // okay 2701 break; 2702 2703 case Qualifiers::OCL_Weak: 2704 case Qualifiers::OCL_Strong: 2705 case Qualifiers::OCL_Autoreleasing: 2706 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 2707 << ValType << FirstArg->getSourceRange(); 2708 return ExprError(); 2709 } 2710 2711 // Strip any qualifiers off ValType. 2712 ValType = ValType.getUnqualifiedType(); 2713 2714 // The majority of builtins return a value, but a few have special return 2715 // types, so allow them to override appropriately below. 2716 QualType ResultType = ValType; 2717 2718 // We need to figure out which concrete builtin this maps onto. For example, 2719 // __sync_fetch_and_add with a 2 byte object turns into 2720 // __sync_fetch_and_add_2. 2721 #define BUILTIN_ROW(x) \ 2722 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 2723 Builtin::BI##x##_8, Builtin::BI##x##_16 } 2724 2725 static const unsigned BuiltinIndices[][5] = { 2726 BUILTIN_ROW(__sync_fetch_and_add), 2727 BUILTIN_ROW(__sync_fetch_and_sub), 2728 BUILTIN_ROW(__sync_fetch_and_or), 2729 BUILTIN_ROW(__sync_fetch_and_and), 2730 BUILTIN_ROW(__sync_fetch_and_xor), 2731 BUILTIN_ROW(__sync_fetch_and_nand), 2732 2733 BUILTIN_ROW(__sync_add_and_fetch), 2734 BUILTIN_ROW(__sync_sub_and_fetch), 2735 BUILTIN_ROW(__sync_and_and_fetch), 2736 BUILTIN_ROW(__sync_or_and_fetch), 2737 BUILTIN_ROW(__sync_xor_and_fetch), 2738 BUILTIN_ROW(__sync_nand_and_fetch), 2739 2740 BUILTIN_ROW(__sync_val_compare_and_swap), 2741 BUILTIN_ROW(__sync_bool_compare_and_swap), 2742 BUILTIN_ROW(__sync_lock_test_and_set), 2743 BUILTIN_ROW(__sync_lock_release), 2744 BUILTIN_ROW(__sync_swap) 2745 }; 2746 #undef BUILTIN_ROW 2747 2748 // Determine the index of the size. 2749 unsigned SizeIndex; 2750 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 2751 case 1: SizeIndex = 0; break; 2752 case 2: SizeIndex = 1; break; 2753 case 4: SizeIndex = 2; break; 2754 case 8: SizeIndex = 3; break; 2755 case 16: SizeIndex = 4; break; 2756 default: 2757 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 2758 << FirstArg->getType() << FirstArg->getSourceRange(); 2759 return ExprError(); 2760 } 2761 2762 // Each of these builtins has one pointer argument, followed by some number of 2763 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 2764 // that we ignore. Find out which row of BuiltinIndices to read from as well 2765 // as the number of fixed args. 2766 unsigned BuiltinID = FDecl->getBuiltinID(); 2767 unsigned BuiltinIndex, NumFixed = 1; 2768 bool WarnAboutSemanticsChange = false; 2769 switch (BuiltinID) { 2770 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 2771 case Builtin::BI__sync_fetch_and_add: 2772 case Builtin::BI__sync_fetch_and_add_1: 2773 case Builtin::BI__sync_fetch_and_add_2: 2774 case Builtin::BI__sync_fetch_and_add_4: 2775 case Builtin::BI__sync_fetch_and_add_8: 2776 case Builtin::BI__sync_fetch_and_add_16: 2777 BuiltinIndex = 0; 2778 break; 2779 2780 case Builtin::BI__sync_fetch_and_sub: 2781 case Builtin::BI__sync_fetch_and_sub_1: 2782 case Builtin::BI__sync_fetch_and_sub_2: 2783 case Builtin::BI__sync_fetch_and_sub_4: 2784 case Builtin::BI__sync_fetch_and_sub_8: 2785 case Builtin::BI__sync_fetch_and_sub_16: 2786 BuiltinIndex = 1; 2787 break; 2788 2789 case Builtin::BI__sync_fetch_and_or: 2790 case Builtin::BI__sync_fetch_and_or_1: 2791 case Builtin::BI__sync_fetch_and_or_2: 2792 case Builtin::BI__sync_fetch_and_or_4: 2793 case Builtin::BI__sync_fetch_and_or_8: 2794 case Builtin::BI__sync_fetch_and_or_16: 2795 BuiltinIndex = 2; 2796 break; 2797 2798 case Builtin::BI__sync_fetch_and_and: 2799 case Builtin::BI__sync_fetch_and_and_1: 2800 case Builtin::BI__sync_fetch_and_and_2: 2801 case Builtin::BI__sync_fetch_and_and_4: 2802 case Builtin::BI__sync_fetch_and_and_8: 2803 case Builtin::BI__sync_fetch_and_and_16: 2804 BuiltinIndex = 3; 2805 break; 2806 2807 case Builtin::BI__sync_fetch_and_xor: 2808 case Builtin::BI__sync_fetch_and_xor_1: 2809 case Builtin::BI__sync_fetch_and_xor_2: 2810 case Builtin::BI__sync_fetch_and_xor_4: 2811 case Builtin::BI__sync_fetch_and_xor_8: 2812 case Builtin::BI__sync_fetch_and_xor_16: 2813 BuiltinIndex = 4; 2814 break; 2815 2816 case Builtin::BI__sync_fetch_and_nand: 2817 case Builtin::BI__sync_fetch_and_nand_1: 2818 case Builtin::BI__sync_fetch_and_nand_2: 2819 case Builtin::BI__sync_fetch_and_nand_4: 2820 case Builtin::BI__sync_fetch_and_nand_8: 2821 case Builtin::BI__sync_fetch_and_nand_16: 2822 BuiltinIndex = 5; 2823 WarnAboutSemanticsChange = true; 2824 break; 2825 2826 case Builtin::BI__sync_add_and_fetch: 2827 case Builtin::BI__sync_add_and_fetch_1: 2828 case Builtin::BI__sync_add_and_fetch_2: 2829 case Builtin::BI__sync_add_and_fetch_4: 2830 case Builtin::BI__sync_add_and_fetch_8: 2831 case Builtin::BI__sync_add_and_fetch_16: 2832 BuiltinIndex = 6; 2833 break; 2834 2835 case Builtin::BI__sync_sub_and_fetch: 2836 case Builtin::BI__sync_sub_and_fetch_1: 2837 case Builtin::BI__sync_sub_and_fetch_2: 2838 case Builtin::BI__sync_sub_and_fetch_4: 2839 case Builtin::BI__sync_sub_and_fetch_8: 2840 case Builtin::BI__sync_sub_and_fetch_16: 2841 BuiltinIndex = 7; 2842 break; 2843 2844 case Builtin::BI__sync_and_and_fetch: 2845 case Builtin::BI__sync_and_and_fetch_1: 2846 case Builtin::BI__sync_and_and_fetch_2: 2847 case Builtin::BI__sync_and_and_fetch_4: 2848 case Builtin::BI__sync_and_and_fetch_8: 2849 case Builtin::BI__sync_and_and_fetch_16: 2850 BuiltinIndex = 8; 2851 break; 2852 2853 case Builtin::BI__sync_or_and_fetch: 2854 case Builtin::BI__sync_or_and_fetch_1: 2855 case Builtin::BI__sync_or_and_fetch_2: 2856 case Builtin::BI__sync_or_and_fetch_4: 2857 case Builtin::BI__sync_or_and_fetch_8: 2858 case Builtin::BI__sync_or_and_fetch_16: 2859 BuiltinIndex = 9; 2860 break; 2861 2862 case Builtin::BI__sync_xor_and_fetch: 2863 case Builtin::BI__sync_xor_and_fetch_1: 2864 case Builtin::BI__sync_xor_and_fetch_2: 2865 case Builtin::BI__sync_xor_and_fetch_4: 2866 case Builtin::BI__sync_xor_and_fetch_8: 2867 case Builtin::BI__sync_xor_and_fetch_16: 2868 BuiltinIndex = 10; 2869 break; 2870 2871 case Builtin::BI__sync_nand_and_fetch: 2872 case Builtin::BI__sync_nand_and_fetch_1: 2873 case Builtin::BI__sync_nand_and_fetch_2: 2874 case Builtin::BI__sync_nand_and_fetch_4: 2875 case Builtin::BI__sync_nand_and_fetch_8: 2876 case Builtin::BI__sync_nand_and_fetch_16: 2877 BuiltinIndex = 11; 2878 WarnAboutSemanticsChange = true; 2879 break; 2880 2881 case Builtin::BI__sync_val_compare_and_swap: 2882 case Builtin::BI__sync_val_compare_and_swap_1: 2883 case Builtin::BI__sync_val_compare_and_swap_2: 2884 case Builtin::BI__sync_val_compare_and_swap_4: 2885 case Builtin::BI__sync_val_compare_and_swap_8: 2886 case Builtin::BI__sync_val_compare_and_swap_16: 2887 BuiltinIndex = 12; 2888 NumFixed = 2; 2889 break; 2890 2891 case Builtin::BI__sync_bool_compare_and_swap: 2892 case Builtin::BI__sync_bool_compare_and_swap_1: 2893 case Builtin::BI__sync_bool_compare_and_swap_2: 2894 case Builtin::BI__sync_bool_compare_and_swap_4: 2895 case Builtin::BI__sync_bool_compare_and_swap_8: 2896 case Builtin::BI__sync_bool_compare_and_swap_16: 2897 BuiltinIndex = 13; 2898 NumFixed = 2; 2899 ResultType = Context.BoolTy; 2900 break; 2901 2902 case Builtin::BI__sync_lock_test_and_set: 2903 case Builtin::BI__sync_lock_test_and_set_1: 2904 case Builtin::BI__sync_lock_test_and_set_2: 2905 case Builtin::BI__sync_lock_test_and_set_4: 2906 case Builtin::BI__sync_lock_test_and_set_8: 2907 case Builtin::BI__sync_lock_test_and_set_16: 2908 BuiltinIndex = 14; 2909 break; 2910 2911 case Builtin::BI__sync_lock_release: 2912 case Builtin::BI__sync_lock_release_1: 2913 case Builtin::BI__sync_lock_release_2: 2914 case Builtin::BI__sync_lock_release_4: 2915 case Builtin::BI__sync_lock_release_8: 2916 case Builtin::BI__sync_lock_release_16: 2917 BuiltinIndex = 15; 2918 NumFixed = 0; 2919 ResultType = Context.VoidTy; 2920 break; 2921 2922 case Builtin::BI__sync_swap: 2923 case Builtin::BI__sync_swap_1: 2924 case Builtin::BI__sync_swap_2: 2925 case Builtin::BI__sync_swap_4: 2926 case Builtin::BI__sync_swap_8: 2927 case Builtin::BI__sync_swap_16: 2928 BuiltinIndex = 16; 2929 break; 2930 } 2931 2932 // Now that we know how many fixed arguments we expect, first check that we 2933 // have at least that many. 2934 if (TheCall->getNumArgs() < 1+NumFixed) { 2935 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 2936 << 0 << 1+NumFixed << TheCall->getNumArgs() 2937 << TheCall->getCallee()->getSourceRange(); 2938 return ExprError(); 2939 } 2940 2941 if (WarnAboutSemanticsChange) { 2942 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 2943 << TheCall->getCallee()->getSourceRange(); 2944 } 2945 2946 // Get the decl for the concrete builtin from this, we can tell what the 2947 // concrete integer type we should convert to is. 2948 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 2949 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 2950 FunctionDecl *NewBuiltinDecl; 2951 if (NewBuiltinID == BuiltinID) 2952 NewBuiltinDecl = FDecl; 2953 else { 2954 // Perform builtin lookup to avoid redeclaring it. 2955 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 2956 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 2957 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 2958 assert(Res.getFoundDecl()); 2959 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 2960 if (!NewBuiltinDecl) 2961 return ExprError(); 2962 } 2963 2964 // The first argument --- the pointer --- has a fixed type; we 2965 // deduce the types of the rest of the arguments accordingly. Walk 2966 // the remaining arguments, converting them to the deduced value type. 2967 for (unsigned i = 0; i != NumFixed; ++i) { 2968 ExprResult Arg = TheCall->getArg(i+1); 2969 2970 // GCC does an implicit conversion to the pointer or integer ValType. This 2971 // can fail in some cases (1i -> int**), check for this error case now. 2972 // Initialize the argument. 2973 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 2974 ValType, /*consume*/ false); 2975 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 2976 if (Arg.isInvalid()) 2977 return ExprError(); 2978 2979 // Okay, we have something that *can* be converted to the right type. Check 2980 // to see if there is a potentially weird extension going on here. This can 2981 // happen when you do an atomic operation on something like an char* and 2982 // pass in 42. The 42 gets converted to char. This is even more strange 2983 // for things like 45.123 -> char, etc. 2984 // FIXME: Do this check. 2985 TheCall->setArg(i+1, Arg.get()); 2986 } 2987 2988 ASTContext& Context = this->getASTContext(); 2989 2990 // Create a new DeclRefExpr to refer to the new decl. 2991 DeclRefExpr* NewDRE = DeclRefExpr::Create( 2992 Context, 2993 DRE->getQualifierLoc(), 2994 SourceLocation(), 2995 NewBuiltinDecl, 2996 /*enclosing*/ false, 2997 DRE->getLocation(), 2998 Context.BuiltinFnTy, 2999 DRE->getValueKind()); 3000 3001 // Set the callee in the CallExpr. 3002 // FIXME: This loses syntactic information. 3003 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3004 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3005 CK_BuiltinFnToFnPtr); 3006 TheCall->setCallee(PromotedCall.get()); 3007 3008 // Change the result type of the call to match the original value type. This 3009 // is arbitrary, but the codegen for these builtins ins design to handle it 3010 // gracefully. 3011 TheCall->setType(ResultType); 3012 3013 return TheCallResult; 3014 } 3015 3016 /// SemaBuiltinNontemporalOverloaded - We have a call to 3017 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 3018 /// overloaded function based on the pointer type of its last argument. 3019 /// 3020 /// This function goes through and does final semantic checking for these 3021 /// builtins. 3022 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 3023 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3024 DeclRefExpr *DRE = 3025 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3026 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3027 unsigned BuiltinID = FDecl->getBuiltinID(); 3028 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 3029 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 3030 "Unexpected nontemporal load/store builtin!"); 3031 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 3032 unsigned numArgs = isStore ? 2 : 1; 3033 3034 // Ensure that we have the proper number of arguments. 3035 if (checkArgCount(*this, TheCall, numArgs)) 3036 return ExprError(); 3037 3038 // Inspect the last argument of the nontemporal builtin. This should always 3039 // be a pointer type, from which we imply the type of the memory access. 3040 // Because it is a pointer type, we don't have to worry about any implicit 3041 // casts here. 3042 Expr *PointerArg = TheCall->getArg(numArgs - 1); 3043 ExprResult PointerArgResult = 3044 DefaultFunctionArrayLvalueConversion(PointerArg); 3045 3046 if (PointerArgResult.isInvalid()) 3047 return ExprError(); 3048 PointerArg = PointerArgResult.get(); 3049 TheCall->setArg(numArgs - 1, PointerArg); 3050 3051 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3052 if (!pointerType) { 3053 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 3054 << PointerArg->getType() << PointerArg->getSourceRange(); 3055 return ExprError(); 3056 } 3057 3058 QualType ValType = pointerType->getPointeeType(); 3059 3060 // Strip any qualifiers off ValType. 3061 ValType = ValType.getUnqualifiedType(); 3062 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3063 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 3064 !ValType->isVectorType()) { 3065 Diag(DRE->getLocStart(), 3066 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 3067 << PointerArg->getType() << PointerArg->getSourceRange(); 3068 return ExprError(); 3069 } 3070 3071 if (!isStore) { 3072 TheCall->setType(ValType); 3073 return TheCallResult; 3074 } 3075 3076 ExprResult ValArg = TheCall->getArg(0); 3077 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3078 Context, ValType, /*consume*/ false); 3079 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3080 if (ValArg.isInvalid()) 3081 return ExprError(); 3082 3083 TheCall->setArg(0, ValArg.get()); 3084 TheCall->setType(Context.VoidTy); 3085 return TheCallResult; 3086 } 3087 3088 /// CheckObjCString - Checks that the argument to the builtin 3089 /// CFString constructor is correct 3090 /// Note: It might also make sense to do the UTF-16 conversion here (would 3091 /// simplify the backend). 3092 bool Sema::CheckObjCString(Expr *Arg) { 3093 Arg = Arg->IgnoreParenCasts(); 3094 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 3095 3096 if (!Literal || !Literal->isAscii()) { 3097 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 3098 << Arg->getSourceRange(); 3099 return true; 3100 } 3101 3102 if (Literal->containsNonAsciiOrNull()) { 3103 StringRef String = Literal->getString(); 3104 unsigned NumBytes = String.size(); 3105 SmallVector<UTF16, 128> ToBuf(NumBytes); 3106 const UTF8 *FromPtr = (const UTF8 *)String.data(); 3107 UTF16 *ToPtr = &ToBuf[0]; 3108 3109 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 3110 &ToPtr, ToPtr + NumBytes, 3111 strictConversion); 3112 // Check for conversion failure. 3113 if (Result != conversionOK) 3114 Diag(Arg->getLocStart(), 3115 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 3116 } 3117 return false; 3118 } 3119 3120 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 3121 /// for validity. Emit an error and return true on failure; return false 3122 /// on success. 3123 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) { 3124 Expr *Fn = TheCall->getCallee(); 3125 if (TheCall->getNumArgs() > 2) { 3126 Diag(TheCall->getArg(2)->getLocStart(), 3127 diag::err_typecheck_call_too_many_args) 3128 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3129 << Fn->getSourceRange() 3130 << SourceRange(TheCall->getArg(2)->getLocStart(), 3131 (*(TheCall->arg_end()-1))->getLocEnd()); 3132 return true; 3133 } 3134 3135 if (TheCall->getNumArgs() < 2) { 3136 return Diag(TheCall->getLocEnd(), 3137 diag::err_typecheck_call_too_few_args_at_least) 3138 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 3139 } 3140 3141 // Type-check the first argument normally. 3142 if (checkBuiltinArgument(*this, TheCall, 0)) 3143 return true; 3144 3145 // Determine whether the current function is variadic or not. 3146 BlockScopeInfo *CurBlock = getCurBlock(); 3147 bool isVariadic; 3148 if (CurBlock) 3149 isVariadic = CurBlock->TheDecl->isVariadic(); 3150 else if (FunctionDecl *FD = getCurFunctionDecl()) 3151 isVariadic = FD->isVariadic(); 3152 else 3153 isVariadic = getCurMethodDecl()->isVariadic(); 3154 3155 if (!isVariadic) { 3156 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 3157 return true; 3158 } 3159 3160 // Verify that the second argument to the builtin is the last argument of the 3161 // current function or method. 3162 bool SecondArgIsLastNamedArgument = false; 3163 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 3164 3165 // These are valid if SecondArgIsLastNamedArgument is false after the next 3166 // block. 3167 QualType Type; 3168 SourceLocation ParamLoc; 3169 bool IsCRegister = false; 3170 3171 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 3172 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 3173 // FIXME: This isn't correct for methods (results in bogus warning). 3174 // Get the last formal in the current function. 3175 const ParmVarDecl *LastArg; 3176 if (CurBlock) 3177 LastArg = CurBlock->TheDecl->parameters().back(); 3178 else if (FunctionDecl *FD = getCurFunctionDecl()) 3179 LastArg = FD->parameters().back(); 3180 else 3181 LastArg = getCurMethodDecl()->parameters().back(); 3182 SecondArgIsLastNamedArgument = PV == LastArg; 3183 3184 Type = PV->getType(); 3185 ParamLoc = PV->getLocation(); 3186 IsCRegister = 3187 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 3188 } 3189 } 3190 3191 if (!SecondArgIsLastNamedArgument) 3192 Diag(TheCall->getArg(1)->getLocStart(), 3193 diag::warn_second_arg_of_va_start_not_last_named_param); 3194 else if (IsCRegister || Type->isReferenceType() || 3195 Type->isPromotableIntegerType() || 3196 Type->isSpecificBuiltinType(BuiltinType::Float)) { 3197 unsigned Reason = 0; 3198 if (Type->isReferenceType()) Reason = 1; 3199 else if (IsCRegister) Reason = 2; 3200 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 3201 Diag(ParamLoc, diag::note_parameter_type) << Type; 3202 } 3203 3204 TheCall->setType(Context.VoidTy); 3205 return false; 3206 } 3207 3208 /// Check the arguments to '__builtin_va_start' for validity, and that 3209 /// it was called from a function of the native ABI. 3210 /// Emit an error and return true on failure; return false on success. 3211 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 3212 // On x86-64 Unix, don't allow this in Win64 ABI functions. 3213 // On x64 Windows, don't allow this in System V ABI functions. 3214 // (Yes, that means there's no corresponding way to support variadic 3215 // System V ABI functions on Windows.) 3216 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) { 3217 unsigned OS = Context.getTargetInfo().getTriple().getOS(); 3218 clang::CallingConv CC = CC_C; 3219 if (const FunctionDecl *FD = getCurFunctionDecl()) 3220 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3221 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) || 3222 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64)) 3223 return Diag(TheCall->getCallee()->getLocStart(), 3224 diag::err_va_start_used_in_wrong_abi_function) 3225 << (OS != llvm::Triple::Win32); 3226 } 3227 return SemaBuiltinVAStartImpl(TheCall); 3228 } 3229 3230 /// Check the arguments to '__builtin_ms_va_start' for validity, and that 3231 /// it was called from a Win64 ABI function. 3232 /// Emit an error and return true on failure; return false on success. 3233 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) { 3234 // This only makes sense for x86-64. 3235 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3236 Expr *Callee = TheCall->getCallee(); 3237 if (TT.getArch() != llvm::Triple::x86_64) 3238 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt); 3239 // Don't allow this in System V ABI functions. 3240 clang::CallingConv CC = CC_C; 3241 if (const FunctionDecl *FD = getCurFunctionDecl()) 3242 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3243 if (CC == CC_X86_64SysV || 3244 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64)) 3245 return Diag(Callee->getLocStart(), 3246 diag::err_ms_va_start_used_in_sysv_function); 3247 return SemaBuiltinVAStartImpl(TheCall); 3248 } 3249 3250 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) { 3251 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 3252 // const char *named_addr); 3253 3254 Expr *Func = Call->getCallee(); 3255 3256 if (Call->getNumArgs() < 3) 3257 return Diag(Call->getLocEnd(), 3258 diag::err_typecheck_call_too_few_args_at_least) 3259 << 0 /*function call*/ << 3 << Call->getNumArgs(); 3260 3261 // Determine whether the current function is variadic or not. 3262 bool IsVariadic; 3263 if (BlockScopeInfo *CurBlock = getCurBlock()) 3264 IsVariadic = CurBlock->TheDecl->isVariadic(); 3265 else if (FunctionDecl *FD = getCurFunctionDecl()) 3266 IsVariadic = FD->isVariadic(); 3267 else if (ObjCMethodDecl *MD = getCurMethodDecl()) 3268 IsVariadic = MD->isVariadic(); 3269 else 3270 llvm_unreachable("unexpected statement type"); 3271 3272 if (!IsVariadic) { 3273 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 3274 return true; 3275 } 3276 3277 // Type-check the first argument normally. 3278 if (checkBuiltinArgument(*this, Call, 0)) 3279 return true; 3280 3281 const struct { 3282 unsigned ArgNo; 3283 QualType Type; 3284 } ArgumentTypes[] = { 3285 { 1, Context.getPointerType(Context.CharTy.withConst()) }, 3286 { 2, Context.getSizeType() }, 3287 }; 3288 3289 for (const auto &AT : ArgumentTypes) { 3290 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens(); 3291 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType()) 3292 continue; 3293 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible) 3294 << Arg->getType() << AT.Type << 1 /* different class */ 3295 << 0 /* qualifier difference */ << 3 /* parameter mismatch */ 3296 << AT.ArgNo + 1 << Arg->getType() << AT.Type; 3297 } 3298 3299 return false; 3300 } 3301 3302 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 3303 /// friends. This is declared to take (...), so we have to check everything. 3304 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 3305 if (TheCall->getNumArgs() < 2) 3306 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3307 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 3308 if (TheCall->getNumArgs() > 2) 3309 return Diag(TheCall->getArg(2)->getLocStart(), 3310 diag::err_typecheck_call_too_many_args) 3311 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3312 << SourceRange(TheCall->getArg(2)->getLocStart(), 3313 (*(TheCall->arg_end()-1))->getLocEnd()); 3314 3315 ExprResult OrigArg0 = TheCall->getArg(0); 3316 ExprResult OrigArg1 = TheCall->getArg(1); 3317 3318 // Do standard promotions between the two arguments, returning their common 3319 // type. 3320 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 3321 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 3322 return true; 3323 3324 // Make sure any conversions are pushed back into the call; this is 3325 // type safe since unordered compare builtins are declared as "_Bool 3326 // foo(...)". 3327 TheCall->setArg(0, OrigArg0.get()); 3328 TheCall->setArg(1, OrigArg1.get()); 3329 3330 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 3331 return false; 3332 3333 // If the common type isn't a real floating type, then the arguments were 3334 // invalid for this operation. 3335 if (Res.isNull() || !Res->isRealFloatingType()) 3336 return Diag(OrigArg0.get()->getLocStart(), 3337 diag::err_typecheck_call_invalid_ordered_compare) 3338 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 3339 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 3340 3341 return false; 3342 } 3343 3344 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 3345 /// __builtin_isnan and friends. This is declared to take (...), so we have 3346 /// to check everything. We expect the last argument to be a floating point 3347 /// value. 3348 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 3349 if (TheCall->getNumArgs() < NumArgs) 3350 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3351 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 3352 if (TheCall->getNumArgs() > NumArgs) 3353 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 3354 diag::err_typecheck_call_too_many_args) 3355 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 3356 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 3357 (*(TheCall->arg_end()-1))->getLocEnd()); 3358 3359 Expr *OrigArg = TheCall->getArg(NumArgs-1); 3360 3361 if (OrigArg->isTypeDependent()) 3362 return false; 3363 3364 // This operation requires a non-_Complex floating-point number. 3365 if (!OrigArg->getType()->isRealFloatingType()) 3366 return Diag(OrigArg->getLocStart(), 3367 diag::err_typecheck_call_invalid_unary_fp) 3368 << OrigArg->getType() << OrigArg->getSourceRange(); 3369 3370 // If this is an implicit conversion from float -> double, remove it. 3371 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 3372 Expr *CastArg = Cast->getSubExpr(); 3373 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 3374 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 3375 "promotion from float to double is the only expected cast here"); 3376 Cast->setSubExpr(nullptr); 3377 TheCall->setArg(NumArgs-1, CastArg); 3378 } 3379 } 3380 3381 return false; 3382 } 3383 3384 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 3385 // This is declared to take (...), so we have to check everything. 3386 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 3387 if (TheCall->getNumArgs() < 2) 3388 return ExprError(Diag(TheCall->getLocEnd(), 3389 diag::err_typecheck_call_too_few_args_at_least) 3390 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3391 << TheCall->getSourceRange()); 3392 3393 // Determine which of the following types of shufflevector we're checking: 3394 // 1) unary, vector mask: (lhs, mask) 3395 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 3396 QualType resType = TheCall->getArg(0)->getType(); 3397 unsigned numElements = 0; 3398 3399 if (!TheCall->getArg(0)->isTypeDependent() && 3400 !TheCall->getArg(1)->isTypeDependent()) { 3401 QualType LHSType = TheCall->getArg(0)->getType(); 3402 QualType RHSType = TheCall->getArg(1)->getType(); 3403 3404 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 3405 return ExprError(Diag(TheCall->getLocStart(), 3406 diag::err_shufflevector_non_vector) 3407 << SourceRange(TheCall->getArg(0)->getLocStart(), 3408 TheCall->getArg(1)->getLocEnd())); 3409 3410 numElements = LHSType->getAs<VectorType>()->getNumElements(); 3411 unsigned numResElements = TheCall->getNumArgs() - 2; 3412 3413 // Check to see if we have a call with 2 vector arguments, the unary shuffle 3414 // with mask. If so, verify that RHS is an integer vector type with the 3415 // same number of elts as lhs. 3416 if (TheCall->getNumArgs() == 2) { 3417 if (!RHSType->hasIntegerRepresentation() || 3418 RHSType->getAs<VectorType>()->getNumElements() != numElements) 3419 return ExprError(Diag(TheCall->getLocStart(), 3420 diag::err_shufflevector_incompatible_vector) 3421 << SourceRange(TheCall->getArg(1)->getLocStart(), 3422 TheCall->getArg(1)->getLocEnd())); 3423 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 3424 return ExprError(Diag(TheCall->getLocStart(), 3425 diag::err_shufflevector_incompatible_vector) 3426 << SourceRange(TheCall->getArg(0)->getLocStart(), 3427 TheCall->getArg(1)->getLocEnd())); 3428 } else if (numElements != numResElements) { 3429 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 3430 resType = Context.getVectorType(eltType, numResElements, 3431 VectorType::GenericVector); 3432 } 3433 } 3434 3435 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 3436 if (TheCall->getArg(i)->isTypeDependent() || 3437 TheCall->getArg(i)->isValueDependent()) 3438 continue; 3439 3440 llvm::APSInt Result(32); 3441 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 3442 return ExprError(Diag(TheCall->getLocStart(), 3443 diag::err_shufflevector_nonconstant_argument) 3444 << TheCall->getArg(i)->getSourceRange()); 3445 3446 // Allow -1 which will be translated to undef in the IR. 3447 if (Result.isSigned() && Result.isAllOnesValue()) 3448 continue; 3449 3450 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 3451 return ExprError(Diag(TheCall->getLocStart(), 3452 diag::err_shufflevector_argument_too_large) 3453 << TheCall->getArg(i)->getSourceRange()); 3454 } 3455 3456 SmallVector<Expr*, 32> exprs; 3457 3458 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 3459 exprs.push_back(TheCall->getArg(i)); 3460 TheCall->setArg(i, nullptr); 3461 } 3462 3463 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 3464 TheCall->getCallee()->getLocStart(), 3465 TheCall->getRParenLoc()); 3466 } 3467 3468 /// SemaConvertVectorExpr - Handle __builtin_convertvector 3469 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 3470 SourceLocation BuiltinLoc, 3471 SourceLocation RParenLoc) { 3472 ExprValueKind VK = VK_RValue; 3473 ExprObjectKind OK = OK_Ordinary; 3474 QualType DstTy = TInfo->getType(); 3475 QualType SrcTy = E->getType(); 3476 3477 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 3478 return ExprError(Diag(BuiltinLoc, 3479 diag::err_convertvector_non_vector) 3480 << E->getSourceRange()); 3481 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 3482 return ExprError(Diag(BuiltinLoc, 3483 diag::err_convertvector_non_vector_type)); 3484 3485 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 3486 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 3487 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 3488 if (SrcElts != DstElts) 3489 return ExprError(Diag(BuiltinLoc, 3490 diag::err_convertvector_incompatible_vector) 3491 << E->getSourceRange()); 3492 } 3493 3494 return new (Context) 3495 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 3496 } 3497 3498 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 3499 // This is declared to take (const void*, ...) and can take two 3500 // optional constant int args. 3501 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 3502 unsigned NumArgs = TheCall->getNumArgs(); 3503 3504 if (NumArgs > 3) 3505 return Diag(TheCall->getLocEnd(), 3506 diag::err_typecheck_call_too_many_args_at_most) 3507 << 0 /*function call*/ << 3 << NumArgs 3508 << TheCall->getSourceRange(); 3509 3510 // Argument 0 is checked for us and the remaining arguments must be 3511 // constant integers. 3512 for (unsigned i = 1; i != NumArgs; ++i) 3513 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 3514 return true; 3515 3516 return false; 3517 } 3518 3519 /// SemaBuiltinAssume - Handle __assume (MS Extension). 3520 // __assume does not evaluate its arguments, and should warn if its argument 3521 // has side effects. 3522 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 3523 Expr *Arg = TheCall->getArg(0); 3524 if (Arg->isInstantiationDependent()) return false; 3525 3526 if (Arg->HasSideEffects(Context)) 3527 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 3528 << Arg->getSourceRange() 3529 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 3530 3531 return false; 3532 } 3533 3534 /// Handle __builtin_assume_aligned. This is declared 3535 /// as (const void*, size_t, ...) and can take one optional constant int arg. 3536 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 3537 unsigned NumArgs = TheCall->getNumArgs(); 3538 3539 if (NumArgs > 3) 3540 return Diag(TheCall->getLocEnd(), 3541 diag::err_typecheck_call_too_many_args_at_most) 3542 << 0 /*function call*/ << 3 << NumArgs 3543 << TheCall->getSourceRange(); 3544 3545 // The alignment must be a constant integer. 3546 Expr *Arg = TheCall->getArg(1); 3547 3548 // We can't check the value of a dependent argument. 3549 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 3550 llvm::APSInt Result; 3551 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 3552 return true; 3553 3554 if (!Result.isPowerOf2()) 3555 return Diag(TheCall->getLocStart(), 3556 diag::err_alignment_not_power_of_two) 3557 << Arg->getSourceRange(); 3558 } 3559 3560 if (NumArgs > 2) { 3561 ExprResult Arg(TheCall->getArg(2)); 3562 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3563 Context.getSizeType(), false); 3564 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3565 if (Arg.isInvalid()) return true; 3566 TheCall->setArg(2, Arg.get()); 3567 } 3568 3569 return false; 3570 } 3571 3572 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 3573 /// TheCall is a constant expression. 3574 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 3575 llvm::APSInt &Result) { 3576 Expr *Arg = TheCall->getArg(ArgNum); 3577 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3578 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3579 3580 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 3581 3582 if (!Arg->isIntegerConstantExpr(Result, Context)) 3583 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 3584 << FDecl->getDeclName() << Arg->getSourceRange(); 3585 3586 return false; 3587 } 3588 3589 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 3590 /// TheCall is a constant expression in the range [Low, High]. 3591 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 3592 int Low, int High) { 3593 llvm::APSInt Result; 3594 3595 // We can't check the value of a dependent argument. 3596 Expr *Arg = TheCall->getArg(ArgNum); 3597 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3598 return false; 3599 3600 // Check constant-ness first. 3601 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3602 return true; 3603 3604 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 3605 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 3606 << Low << High << Arg->getSourceRange(); 3607 3608 return false; 3609 } 3610 3611 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 3612 /// TheCall is an ARM/AArch64 special register string literal. 3613 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 3614 int ArgNum, unsigned ExpectedFieldNum, 3615 bool AllowName) { 3616 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 3617 BuiltinID == ARM::BI__builtin_arm_wsr64 || 3618 BuiltinID == ARM::BI__builtin_arm_rsr || 3619 BuiltinID == ARM::BI__builtin_arm_rsrp || 3620 BuiltinID == ARM::BI__builtin_arm_wsr || 3621 BuiltinID == ARM::BI__builtin_arm_wsrp; 3622 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 3623 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 3624 BuiltinID == AArch64::BI__builtin_arm_rsr || 3625 BuiltinID == AArch64::BI__builtin_arm_rsrp || 3626 BuiltinID == AArch64::BI__builtin_arm_wsr || 3627 BuiltinID == AArch64::BI__builtin_arm_wsrp; 3628 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 3629 3630 // We can't check the value of a dependent argument. 3631 Expr *Arg = TheCall->getArg(ArgNum); 3632 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3633 return false; 3634 3635 // Check if the argument is a string literal. 3636 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3637 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 3638 << Arg->getSourceRange(); 3639 3640 // Check the type of special register given. 3641 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3642 SmallVector<StringRef, 6> Fields; 3643 Reg.split(Fields, ":"); 3644 3645 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 3646 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 3647 << Arg->getSourceRange(); 3648 3649 // If the string is the name of a register then we cannot check that it is 3650 // valid here but if the string is of one the forms described in ACLE then we 3651 // can check that the supplied fields are integers and within the valid 3652 // ranges. 3653 if (Fields.size() > 1) { 3654 bool FiveFields = Fields.size() == 5; 3655 3656 bool ValidString = true; 3657 if (IsARMBuiltin) { 3658 ValidString &= Fields[0].startswith_lower("cp") || 3659 Fields[0].startswith_lower("p"); 3660 if (ValidString) 3661 Fields[0] = 3662 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 3663 3664 ValidString &= Fields[2].startswith_lower("c"); 3665 if (ValidString) 3666 Fields[2] = Fields[2].drop_front(1); 3667 3668 if (FiveFields) { 3669 ValidString &= Fields[3].startswith_lower("c"); 3670 if (ValidString) 3671 Fields[3] = Fields[3].drop_front(1); 3672 } 3673 } 3674 3675 SmallVector<int, 5> Ranges; 3676 if (FiveFields) 3677 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15}); 3678 else 3679 Ranges.append({15, 7, 15}); 3680 3681 for (unsigned i=0; i<Fields.size(); ++i) { 3682 int IntField; 3683 ValidString &= !Fields[i].getAsInteger(10, IntField); 3684 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 3685 } 3686 3687 if (!ValidString) 3688 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 3689 << Arg->getSourceRange(); 3690 3691 } else if (IsAArch64Builtin && Fields.size() == 1) { 3692 // If the register name is one of those that appear in the condition below 3693 // and the special register builtin being used is one of the write builtins, 3694 // then we require that the argument provided for writing to the register 3695 // is an integer constant expression. This is because it will be lowered to 3696 // an MSR (immediate) instruction, so we need to know the immediate at 3697 // compile time. 3698 if (TheCall->getNumArgs() != 2) 3699 return false; 3700 3701 std::string RegLower = Reg.lower(); 3702 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 3703 RegLower != "pan" && RegLower != "uao") 3704 return false; 3705 3706 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 3707 } 3708 3709 return false; 3710 } 3711 3712 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 3713 /// This checks that the target supports __builtin_longjmp and 3714 /// that val is a constant 1. 3715 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 3716 if (!Context.getTargetInfo().hasSjLjLowering()) 3717 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 3718 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 3719 3720 Expr *Arg = TheCall->getArg(1); 3721 llvm::APSInt Result; 3722 3723 // TODO: This is less than ideal. Overload this to take a value. 3724 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 3725 return true; 3726 3727 if (Result != 1) 3728 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 3729 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 3730 3731 return false; 3732 } 3733 3734 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 3735 /// This checks that the target supports __builtin_setjmp. 3736 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 3737 if (!Context.getTargetInfo().hasSjLjLowering()) 3738 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 3739 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 3740 return false; 3741 } 3742 3743 namespace { 3744 class UncoveredArgHandler { 3745 enum { Unknown = -1, AllCovered = -2 }; 3746 signed FirstUncoveredArg; 3747 SmallVector<const Expr *, 4> DiagnosticExprs; 3748 3749 public: 3750 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { } 3751 3752 bool hasUncoveredArg() const { 3753 return (FirstUncoveredArg >= 0); 3754 } 3755 3756 unsigned getUncoveredArg() const { 3757 assert(hasUncoveredArg() && "no uncovered argument"); 3758 return FirstUncoveredArg; 3759 } 3760 3761 void setAllCovered() { 3762 // A string has been found with all arguments covered, so clear out 3763 // the diagnostics. 3764 DiagnosticExprs.clear(); 3765 FirstUncoveredArg = AllCovered; 3766 } 3767 3768 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 3769 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 3770 3771 // Don't update if a previous string covers all arguments. 3772 if (FirstUncoveredArg == AllCovered) 3773 return; 3774 3775 // UncoveredArgHandler tracks the highest uncovered argument index 3776 // and with it all the strings that match this index. 3777 if (NewFirstUncoveredArg == FirstUncoveredArg) 3778 DiagnosticExprs.push_back(StrExpr); 3779 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 3780 DiagnosticExprs.clear(); 3781 DiagnosticExprs.push_back(StrExpr); 3782 FirstUncoveredArg = NewFirstUncoveredArg; 3783 } 3784 } 3785 3786 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 3787 }; 3788 3789 enum StringLiteralCheckType { 3790 SLCT_NotALiteral, 3791 SLCT_UncheckedLiteral, 3792 SLCT_CheckedLiteral 3793 }; 3794 } // end anonymous namespace 3795 3796 static void CheckFormatString(Sema &S, const StringLiteral *FExpr, 3797 const Expr *OrigFormatExpr, 3798 ArrayRef<const Expr *> Args, 3799 bool HasVAListArg, unsigned format_idx, 3800 unsigned firstDataArg, 3801 Sema::FormatStringType Type, 3802 bool inFunctionCall, 3803 Sema::VariadicCallType CallType, 3804 llvm::SmallBitVector &CheckedVarArgs, 3805 UncoveredArgHandler &UncoveredArg); 3806 3807 // Determine if an expression is a string literal or constant string. 3808 // If this function returns false on the arguments to a function expecting a 3809 // format string, we will usually need to emit a warning. 3810 // True string literals are then checked by CheckFormatString. 3811 static StringLiteralCheckType 3812 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 3813 bool HasVAListArg, unsigned format_idx, 3814 unsigned firstDataArg, Sema::FormatStringType Type, 3815 Sema::VariadicCallType CallType, bool InFunctionCall, 3816 llvm::SmallBitVector &CheckedVarArgs, 3817 UncoveredArgHandler &UncoveredArg) { 3818 tryAgain: 3819 if (E->isTypeDependent() || E->isValueDependent()) 3820 return SLCT_NotALiteral; 3821 3822 E = E->IgnoreParenCasts(); 3823 3824 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 3825 // Technically -Wformat-nonliteral does not warn about this case. 3826 // The behavior of printf and friends in this case is implementation 3827 // dependent. Ideally if the format string cannot be null then 3828 // it should have a 'nonnull' attribute in the function prototype. 3829 return SLCT_UncheckedLiteral; 3830 3831 switch (E->getStmtClass()) { 3832 case Stmt::BinaryConditionalOperatorClass: 3833 case Stmt::ConditionalOperatorClass: { 3834 // The expression is a literal if both sub-expressions were, and it was 3835 // completely checked only if both sub-expressions were checked. 3836 const AbstractConditionalOperator *C = 3837 cast<AbstractConditionalOperator>(E); 3838 3839 // Determine whether it is necessary to check both sub-expressions, for 3840 // example, because the condition expression is a constant that can be 3841 // evaluated at compile time. 3842 bool CheckLeft = true, CheckRight = true; 3843 3844 bool Cond; 3845 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 3846 if (Cond) 3847 CheckRight = false; 3848 else 3849 CheckLeft = false; 3850 } 3851 3852 StringLiteralCheckType Left; 3853 if (!CheckLeft) 3854 Left = SLCT_UncheckedLiteral; 3855 else { 3856 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 3857 HasVAListArg, format_idx, firstDataArg, 3858 Type, CallType, InFunctionCall, 3859 CheckedVarArgs, UncoveredArg); 3860 if (Left == SLCT_NotALiteral || !CheckRight) 3861 return Left; 3862 } 3863 3864 StringLiteralCheckType Right = 3865 checkFormatStringExpr(S, C->getFalseExpr(), Args, 3866 HasVAListArg, format_idx, firstDataArg, 3867 Type, CallType, InFunctionCall, CheckedVarArgs, 3868 UncoveredArg); 3869 3870 return (CheckLeft && Left < Right) ? Left : Right; 3871 } 3872 3873 case Stmt::ImplicitCastExprClass: { 3874 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 3875 goto tryAgain; 3876 } 3877 3878 case Stmt::OpaqueValueExprClass: 3879 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 3880 E = src; 3881 goto tryAgain; 3882 } 3883 return SLCT_NotALiteral; 3884 3885 case Stmt::PredefinedExprClass: 3886 // While __func__, etc., are technically not string literals, they 3887 // cannot contain format specifiers and thus are not a security 3888 // liability. 3889 return SLCT_UncheckedLiteral; 3890 3891 case Stmt::DeclRefExprClass: { 3892 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 3893 3894 // As an exception, do not flag errors for variables binding to 3895 // const string literals. 3896 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 3897 bool isConstant = false; 3898 QualType T = DR->getType(); 3899 3900 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 3901 isConstant = AT->getElementType().isConstant(S.Context); 3902 } else if (const PointerType *PT = T->getAs<PointerType>()) { 3903 isConstant = T.isConstant(S.Context) && 3904 PT->getPointeeType().isConstant(S.Context); 3905 } else if (T->isObjCObjectPointerType()) { 3906 // In ObjC, there is usually no "const ObjectPointer" type, 3907 // so don't check if the pointee type is constant. 3908 isConstant = T.isConstant(S.Context); 3909 } 3910 3911 if (isConstant) { 3912 if (const Expr *Init = VD->getAnyInitializer()) { 3913 // Look through initializers like const char c[] = { "foo" } 3914 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3915 if (InitList->isStringLiteralInit()) 3916 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 3917 } 3918 return checkFormatStringExpr(S, Init, Args, 3919 HasVAListArg, format_idx, 3920 firstDataArg, Type, CallType, 3921 /*InFunctionCall*/false, CheckedVarArgs, 3922 UncoveredArg); 3923 } 3924 } 3925 3926 // For vprintf* functions (i.e., HasVAListArg==true), we add a 3927 // special check to see if the format string is a function parameter 3928 // of the function calling the printf function. If the function 3929 // has an attribute indicating it is a printf-like function, then we 3930 // should suppress warnings concerning non-literals being used in a call 3931 // to a vprintf function. For example: 3932 // 3933 // void 3934 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 3935 // va_list ap; 3936 // va_start(ap, fmt); 3937 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 3938 // ... 3939 // } 3940 if (HasVAListArg) { 3941 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 3942 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 3943 int PVIndex = PV->getFunctionScopeIndex() + 1; 3944 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 3945 // adjust for implicit parameter 3946 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 3947 if (MD->isInstance()) 3948 ++PVIndex; 3949 // We also check if the formats are compatible. 3950 // We can't pass a 'scanf' string to a 'printf' function. 3951 if (PVIndex == PVFormat->getFormatIdx() && 3952 Type == S.GetFormatStringType(PVFormat)) 3953 return SLCT_UncheckedLiteral; 3954 } 3955 } 3956 } 3957 } 3958 } 3959 3960 return SLCT_NotALiteral; 3961 } 3962 3963 case Stmt::CallExprClass: 3964 case Stmt::CXXMemberCallExprClass: { 3965 const CallExpr *CE = cast<CallExpr>(E); 3966 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 3967 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 3968 unsigned ArgIndex = FA->getFormatIdx(); 3969 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 3970 if (MD->isInstance()) 3971 --ArgIndex; 3972 const Expr *Arg = CE->getArg(ArgIndex - 1); 3973 3974 return checkFormatStringExpr(S, Arg, Args, 3975 HasVAListArg, format_idx, firstDataArg, 3976 Type, CallType, InFunctionCall, 3977 CheckedVarArgs, UncoveredArg); 3978 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 3979 unsigned BuiltinID = FD->getBuiltinID(); 3980 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 3981 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 3982 const Expr *Arg = CE->getArg(0); 3983 return checkFormatStringExpr(S, Arg, Args, 3984 HasVAListArg, format_idx, 3985 firstDataArg, Type, CallType, 3986 InFunctionCall, CheckedVarArgs, 3987 UncoveredArg); 3988 } 3989 } 3990 } 3991 3992 return SLCT_NotALiteral; 3993 } 3994 case Stmt::ObjCStringLiteralClass: 3995 case Stmt::StringLiteralClass: { 3996 const StringLiteral *StrE = nullptr; 3997 3998 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 3999 StrE = ObjCFExpr->getString(); 4000 else 4001 StrE = cast<StringLiteral>(E); 4002 4003 if (StrE) { 4004 CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx, 4005 firstDataArg, Type, InFunctionCall, CallType, 4006 CheckedVarArgs, UncoveredArg); 4007 return SLCT_CheckedLiteral; 4008 } 4009 4010 return SLCT_NotALiteral; 4011 } 4012 4013 default: 4014 return SLCT_NotALiteral; 4015 } 4016 } 4017 4018 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 4019 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 4020 .Case("scanf", FST_Scanf) 4021 .Cases("printf", "printf0", FST_Printf) 4022 .Cases("NSString", "CFString", FST_NSString) 4023 .Case("strftime", FST_Strftime) 4024 .Case("strfmon", FST_Strfmon) 4025 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 4026 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 4027 .Case("os_trace", FST_OSTrace) 4028 .Default(FST_Unknown); 4029 } 4030 4031 /// CheckFormatArguments - Check calls to printf and scanf (and similar 4032 /// functions) for correct use of format strings. 4033 /// Returns true if a format string has been fully checked. 4034 bool Sema::CheckFormatArguments(const FormatAttr *Format, 4035 ArrayRef<const Expr *> Args, 4036 bool IsCXXMember, 4037 VariadicCallType CallType, 4038 SourceLocation Loc, SourceRange Range, 4039 llvm::SmallBitVector &CheckedVarArgs) { 4040 FormatStringInfo FSI; 4041 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 4042 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 4043 FSI.FirstDataArg, GetFormatStringType(Format), 4044 CallType, Loc, Range, CheckedVarArgs); 4045 return false; 4046 } 4047 4048 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 4049 bool HasVAListArg, unsigned format_idx, 4050 unsigned firstDataArg, FormatStringType Type, 4051 VariadicCallType CallType, 4052 SourceLocation Loc, SourceRange Range, 4053 llvm::SmallBitVector &CheckedVarArgs) { 4054 // CHECK: printf/scanf-like function is called with no format string. 4055 if (format_idx >= Args.size()) { 4056 Diag(Loc, diag::warn_missing_format_string) << Range; 4057 return false; 4058 } 4059 4060 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 4061 4062 // CHECK: format string is not a string literal. 4063 // 4064 // Dynamically generated format strings are difficult to 4065 // automatically vet at compile time. Requiring that format strings 4066 // are string literals: (1) permits the checking of format strings by 4067 // the compiler and thereby (2) can practically remove the source of 4068 // many format string exploits. 4069 4070 // Format string can be either ObjC string (e.g. @"%d") or 4071 // C string (e.g. "%d") 4072 // ObjC string uses the same format specifiers as C string, so we can use 4073 // the same format string checking logic for both ObjC and C strings. 4074 UncoveredArgHandler UncoveredArg; 4075 StringLiteralCheckType CT = 4076 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 4077 format_idx, firstDataArg, Type, CallType, 4078 /*IsFunctionCall*/true, CheckedVarArgs, 4079 UncoveredArg); 4080 4081 // Generate a diagnostic where an uncovered argument is detected. 4082 if (UncoveredArg.hasUncoveredArg()) { 4083 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 4084 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 4085 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 4086 } 4087 4088 if (CT != SLCT_NotALiteral) 4089 // Literal format string found, check done! 4090 return CT == SLCT_CheckedLiteral; 4091 4092 // Strftime is particular as it always uses a single 'time' argument, 4093 // so it is safe to pass a non-literal string. 4094 if (Type == FST_Strftime) 4095 return false; 4096 4097 // Do not emit diag when the string param is a macro expansion and the 4098 // format is either NSString or CFString. This is a hack to prevent 4099 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 4100 // which are usually used in place of NS and CF string literals. 4101 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 4102 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 4103 return false; 4104 4105 // If there are no arguments specified, warn with -Wformat-security, otherwise 4106 // warn only with -Wformat-nonliteral. 4107 if (Args.size() == firstDataArg) { 4108 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 4109 << OrigFormatExpr->getSourceRange(); 4110 switch (Type) { 4111 default: 4112 break; 4113 case FST_Kprintf: 4114 case FST_FreeBSDKPrintf: 4115 case FST_Printf: 4116 Diag(FormatLoc, diag::note_format_security_fixit) 4117 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 4118 break; 4119 case FST_NSString: 4120 Diag(FormatLoc, diag::note_format_security_fixit) 4121 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 4122 break; 4123 } 4124 } else { 4125 Diag(FormatLoc, diag::warn_format_nonliteral) 4126 << OrigFormatExpr->getSourceRange(); 4127 } 4128 return false; 4129 } 4130 4131 namespace { 4132 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 4133 protected: 4134 Sema &S; 4135 const StringLiteral *FExpr; 4136 const Expr *OrigFormatExpr; 4137 const unsigned FirstDataArg; 4138 const unsigned NumDataArgs; 4139 const char *Beg; // Start of format string. 4140 const bool HasVAListArg; 4141 ArrayRef<const Expr *> Args; 4142 unsigned FormatIdx; 4143 llvm::SmallBitVector CoveredArgs; 4144 bool usesPositionalArgs; 4145 bool atFirstArg; 4146 bool inFunctionCall; 4147 Sema::VariadicCallType CallType; 4148 llvm::SmallBitVector &CheckedVarArgs; 4149 UncoveredArgHandler &UncoveredArg; 4150 4151 public: 4152 CheckFormatHandler(Sema &s, const StringLiteral *fexpr, 4153 const Expr *origFormatExpr, unsigned firstDataArg, 4154 unsigned numDataArgs, const char *beg, bool hasVAListArg, 4155 ArrayRef<const Expr *> Args, 4156 unsigned formatIdx, bool inFunctionCall, 4157 Sema::VariadicCallType callType, 4158 llvm::SmallBitVector &CheckedVarArgs, 4159 UncoveredArgHandler &UncoveredArg) 4160 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 4161 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), 4162 Beg(beg), HasVAListArg(hasVAListArg), 4163 Args(Args), FormatIdx(formatIdx), 4164 usesPositionalArgs(false), atFirstArg(true), 4165 inFunctionCall(inFunctionCall), CallType(callType), 4166 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 4167 CoveredArgs.resize(numDataArgs); 4168 CoveredArgs.reset(); 4169 } 4170 4171 void DoneProcessing(); 4172 4173 void HandleIncompleteSpecifier(const char *startSpecifier, 4174 unsigned specifierLen) override; 4175 4176 void HandleInvalidLengthModifier( 4177 const analyze_format_string::FormatSpecifier &FS, 4178 const analyze_format_string::ConversionSpecifier &CS, 4179 const char *startSpecifier, unsigned specifierLen, 4180 unsigned DiagID); 4181 4182 void HandleNonStandardLengthModifier( 4183 const analyze_format_string::FormatSpecifier &FS, 4184 const char *startSpecifier, unsigned specifierLen); 4185 4186 void HandleNonStandardConversionSpecifier( 4187 const analyze_format_string::ConversionSpecifier &CS, 4188 const char *startSpecifier, unsigned specifierLen); 4189 4190 void HandlePosition(const char *startPos, unsigned posLen) override; 4191 4192 void HandleInvalidPosition(const char *startSpecifier, 4193 unsigned specifierLen, 4194 analyze_format_string::PositionContext p) override; 4195 4196 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 4197 4198 void HandleNullChar(const char *nullCharacter) override; 4199 4200 template <typename Range> 4201 static void 4202 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 4203 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 4204 bool IsStringLocation, Range StringRange, 4205 ArrayRef<FixItHint> Fixit = None); 4206 4207 protected: 4208 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 4209 const char *startSpec, 4210 unsigned specifierLen, 4211 const char *csStart, unsigned csLen); 4212 4213 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 4214 const char *startSpec, 4215 unsigned specifierLen); 4216 4217 SourceRange getFormatStringRange(); 4218 CharSourceRange getSpecifierRange(const char *startSpecifier, 4219 unsigned specifierLen); 4220 SourceLocation getLocationOfByte(const char *x); 4221 4222 const Expr *getDataArg(unsigned i) const; 4223 4224 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 4225 const analyze_format_string::ConversionSpecifier &CS, 4226 const char *startSpecifier, unsigned specifierLen, 4227 unsigned argIndex); 4228 4229 template <typename Range> 4230 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 4231 bool IsStringLocation, Range StringRange, 4232 ArrayRef<FixItHint> Fixit = None); 4233 }; 4234 } // end anonymous namespace 4235 4236 SourceRange CheckFormatHandler::getFormatStringRange() { 4237 return OrigFormatExpr->getSourceRange(); 4238 } 4239 4240 CharSourceRange CheckFormatHandler:: 4241 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 4242 SourceLocation Start = getLocationOfByte(startSpecifier); 4243 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 4244 4245 // Advance the end SourceLocation by one due to half-open ranges. 4246 End = End.getLocWithOffset(1); 4247 4248 return CharSourceRange::getCharRange(Start, End); 4249 } 4250 4251 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 4252 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 4253 } 4254 4255 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 4256 unsigned specifierLen){ 4257 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 4258 getLocationOfByte(startSpecifier), 4259 /*IsStringLocation*/true, 4260 getSpecifierRange(startSpecifier, specifierLen)); 4261 } 4262 4263 void CheckFormatHandler::HandleInvalidLengthModifier( 4264 const analyze_format_string::FormatSpecifier &FS, 4265 const analyze_format_string::ConversionSpecifier &CS, 4266 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 4267 using namespace analyze_format_string; 4268 4269 const LengthModifier &LM = FS.getLengthModifier(); 4270 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 4271 4272 // See if we know how to fix this length modifier. 4273 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 4274 if (FixedLM) { 4275 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 4276 getLocationOfByte(LM.getStart()), 4277 /*IsStringLocation*/true, 4278 getSpecifierRange(startSpecifier, specifierLen)); 4279 4280 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 4281 << FixedLM->toString() 4282 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 4283 4284 } else { 4285 FixItHint Hint; 4286 if (DiagID == diag::warn_format_nonsensical_length) 4287 Hint = FixItHint::CreateRemoval(LMRange); 4288 4289 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 4290 getLocationOfByte(LM.getStart()), 4291 /*IsStringLocation*/true, 4292 getSpecifierRange(startSpecifier, specifierLen), 4293 Hint); 4294 } 4295 } 4296 4297 void CheckFormatHandler::HandleNonStandardLengthModifier( 4298 const analyze_format_string::FormatSpecifier &FS, 4299 const char *startSpecifier, unsigned specifierLen) { 4300 using namespace analyze_format_string; 4301 4302 const LengthModifier &LM = FS.getLengthModifier(); 4303 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 4304 4305 // See if we know how to fix this length modifier. 4306 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 4307 if (FixedLM) { 4308 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4309 << LM.toString() << 0, 4310 getLocationOfByte(LM.getStart()), 4311 /*IsStringLocation*/true, 4312 getSpecifierRange(startSpecifier, specifierLen)); 4313 4314 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 4315 << FixedLM->toString() 4316 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 4317 4318 } else { 4319 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4320 << LM.toString() << 0, 4321 getLocationOfByte(LM.getStart()), 4322 /*IsStringLocation*/true, 4323 getSpecifierRange(startSpecifier, specifierLen)); 4324 } 4325 } 4326 4327 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 4328 const analyze_format_string::ConversionSpecifier &CS, 4329 const char *startSpecifier, unsigned specifierLen) { 4330 using namespace analyze_format_string; 4331 4332 // See if we know how to fix this conversion specifier. 4333 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 4334 if (FixedCS) { 4335 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4336 << CS.toString() << /*conversion specifier*/1, 4337 getLocationOfByte(CS.getStart()), 4338 /*IsStringLocation*/true, 4339 getSpecifierRange(startSpecifier, specifierLen)); 4340 4341 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 4342 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 4343 << FixedCS->toString() 4344 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 4345 } else { 4346 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4347 << CS.toString() << /*conversion specifier*/1, 4348 getLocationOfByte(CS.getStart()), 4349 /*IsStringLocation*/true, 4350 getSpecifierRange(startSpecifier, specifierLen)); 4351 } 4352 } 4353 4354 void CheckFormatHandler::HandlePosition(const char *startPos, 4355 unsigned posLen) { 4356 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 4357 getLocationOfByte(startPos), 4358 /*IsStringLocation*/true, 4359 getSpecifierRange(startPos, posLen)); 4360 } 4361 4362 void 4363 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 4364 analyze_format_string::PositionContext p) { 4365 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 4366 << (unsigned) p, 4367 getLocationOfByte(startPos), /*IsStringLocation*/true, 4368 getSpecifierRange(startPos, posLen)); 4369 } 4370 4371 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 4372 unsigned posLen) { 4373 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 4374 getLocationOfByte(startPos), 4375 /*IsStringLocation*/true, 4376 getSpecifierRange(startPos, posLen)); 4377 } 4378 4379 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 4380 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 4381 // The presence of a null character is likely an error. 4382 EmitFormatDiagnostic( 4383 S.PDiag(diag::warn_printf_format_string_contains_null_char), 4384 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 4385 getFormatStringRange()); 4386 } 4387 } 4388 4389 // Note that this may return NULL if there was an error parsing or building 4390 // one of the argument expressions. 4391 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 4392 return Args[FirstDataArg + i]; 4393 } 4394 4395 void CheckFormatHandler::DoneProcessing() { 4396 // Does the number of data arguments exceed the number of 4397 // format conversions in the format string? 4398 if (!HasVAListArg) { 4399 // Find any arguments that weren't covered. 4400 CoveredArgs.flip(); 4401 signed notCoveredArg = CoveredArgs.find_first(); 4402 if (notCoveredArg >= 0) { 4403 assert((unsigned)notCoveredArg < NumDataArgs); 4404 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 4405 } else { 4406 UncoveredArg.setAllCovered(); 4407 } 4408 } 4409 } 4410 4411 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 4412 const Expr *ArgExpr) { 4413 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 4414 "Invalid state"); 4415 4416 if (!ArgExpr) 4417 return; 4418 4419 SourceLocation Loc = ArgExpr->getLocStart(); 4420 4421 if (S.getSourceManager().isInSystemMacro(Loc)) 4422 return; 4423 4424 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 4425 for (auto E : DiagnosticExprs) 4426 PDiag << E->getSourceRange(); 4427 4428 CheckFormatHandler::EmitFormatDiagnostic( 4429 S, IsFunctionCall, DiagnosticExprs[0], 4430 PDiag, Loc, /*IsStringLocation*/false, 4431 DiagnosticExprs[0]->getSourceRange()); 4432 } 4433 4434 bool 4435 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 4436 SourceLocation Loc, 4437 const char *startSpec, 4438 unsigned specifierLen, 4439 const char *csStart, 4440 unsigned csLen) { 4441 bool keepGoing = true; 4442 if (argIndex < NumDataArgs) { 4443 // Consider the argument coverered, even though the specifier doesn't 4444 // make sense. 4445 CoveredArgs.set(argIndex); 4446 } 4447 else { 4448 // If argIndex exceeds the number of data arguments we 4449 // don't issue a warning because that is just a cascade of warnings (and 4450 // they may have intended '%%' anyway). We don't want to continue processing 4451 // the format string after this point, however, as we will like just get 4452 // gibberish when trying to match arguments. 4453 keepGoing = false; 4454 } 4455 4456 StringRef Specifier(csStart, csLen); 4457 4458 // If the specifier in non-printable, it could be the first byte of a UTF-8 4459 // sequence. In that case, print the UTF-8 code point. If not, print the byte 4460 // hex value. 4461 std::string CodePointStr; 4462 if (!llvm::sys::locale::isPrint(*csStart)) { 4463 UTF32 CodePoint; 4464 const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart); 4465 const UTF8 *E = 4466 reinterpret_cast<const UTF8 *>(csStart + csLen); 4467 ConversionResult Result = 4468 llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion); 4469 4470 if (Result != conversionOK) { 4471 unsigned char FirstChar = *csStart; 4472 CodePoint = (UTF32)FirstChar; 4473 } 4474 4475 llvm::raw_string_ostream OS(CodePointStr); 4476 if (CodePoint < 256) 4477 OS << "\\x" << llvm::format("%02x", CodePoint); 4478 else if (CodePoint <= 0xFFFF) 4479 OS << "\\u" << llvm::format("%04x", CodePoint); 4480 else 4481 OS << "\\U" << llvm::format("%08x", CodePoint); 4482 OS.flush(); 4483 Specifier = CodePointStr; 4484 } 4485 4486 EmitFormatDiagnostic( 4487 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 4488 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 4489 4490 return keepGoing; 4491 } 4492 4493 void 4494 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 4495 const char *startSpec, 4496 unsigned specifierLen) { 4497 EmitFormatDiagnostic( 4498 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 4499 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 4500 } 4501 4502 bool 4503 CheckFormatHandler::CheckNumArgs( 4504 const analyze_format_string::FormatSpecifier &FS, 4505 const analyze_format_string::ConversionSpecifier &CS, 4506 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 4507 4508 if (argIndex >= NumDataArgs) { 4509 PartialDiagnostic PDiag = FS.usesPositionalArg() 4510 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 4511 << (argIndex+1) << NumDataArgs) 4512 : S.PDiag(diag::warn_printf_insufficient_data_args); 4513 EmitFormatDiagnostic( 4514 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 4515 getSpecifierRange(startSpecifier, specifierLen)); 4516 4517 // Since more arguments than conversion tokens are given, by extension 4518 // all arguments are covered, so mark this as so. 4519 UncoveredArg.setAllCovered(); 4520 return false; 4521 } 4522 return true; 4523 } 4524 4525 template<typename Range> 4526 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 4527 SourceLocation Loc, 4528 bool IsStringLocation, 4529 Range StringRange, 4530 ArrayRef<FixItHint> FixIt) { 4531 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 4532 Loc, IsStringLocation, StringRange, FixIt); 4533 } 4534 4535 /// \brief If the format string is not within the funcion call, emit a note 4536 /// so that the function call and string are in diagnostic messages. 4537 /// 4538 /// \param InFunctionCall if true, the format string is within the function 4539 /// call and only one diagnostic message will be produced. Otherwise, an 4540 /// extra note will be emitted pointing to location of the format string. 4541 /// 4542 /// \param ArgumentExpr the expression that is passed as the format string 4543 /// argument in the function call. Used for getting locations when two 4544 /// diagnostics are emitted. 4545 /// 4546 /// \param PDiag the callee should already have provided any strings for the 4547 /// diagnostic message. This function only adds locations and fixits 4548 /// to diagnostics. 4549 /// 4550 /// \param Loc primary location for diagnostic. If two diagnostics are 4551 /// required, one will be at Loc and a new SourceLocation will be created for 4552 /// the other one. 4553 /// 4554 /// \param IsStringLocation if true, Loc points to the format string should be 4555 /// used for the note. Otherwise, Loc points to the argument list and will 4556 /// be used with PDiag. 4557 /// 4558 /// \param StringRange some or all of the string to highlight. This is 4559 /// templated so it can accept either a CharSourceRange or a SourceRange. 4560 /// 4561 /// \param FixIt optional fix it hint for the format string. 4562 template <typename Range> 4563 void CheckFormatHandler::EmitFormatDiagnostic( 4564 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 4565 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 4566 Range StringRange, ArrayRef<FixItHint> FixIt) { 4567 if (InFunctionCall) { 4568 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 4569 D << StringRange; 4570 D << FixIt; 4571 } else { 4572 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 4573 << ArgumentExpr->getSourceRange(); 4574 4575 const Sema::SemaDiagnosticBuilder &Note = 4576 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 4577 diag::note_format_string_defined); 4578 4579 Note << StringRange; 4580 Note << FixIt; 4581 } 4582 } 4583 4584 //===--- CHECK: Printf format string checking ------------------------------===// 4585 4586 namespace { 4587 class CheckPrintfHandler : public CheckFormatHandler { 4588 bool ObjCContext; 4589 4590 public: 4591 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 4592 const Expr *origFormatExpr, unsigned firstDataArg, 4593 unsigned numDataArgs, bool isObjC, 4594 const char *beg, bool hasVAListArg, 4595 ArrayRef<const Expr *> Args, 4596 unsigned formatIdx, bool inFunctionCall, 4597 Sema::VariadicCallType CallType, 4598 llvm::SmallBitVector &CheckedVarArgs, 4599 UncoveredArgHandler &UncoveredArg) 4600 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 4601 numDataArgs, beg, hasVAListArg, Args, 4602 formatIdx, inFunctionCall, CallType, CheckedVarArgs, 4603 UncoveredArg), 4604 ObjCContext(isObjC) 4605 {} 4606 4607 bool HandleInvalidPrintfConversionSpecifier( 4608 const analyze_printf::PrintfSpecifier &FS, 4609 const char *startSpecifier, 4610 unsigned specifierLen) override; 4611 4612 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 4613 const char *startSpecifier, 4614 unsigned specifierLen) override; 4615 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 4616 const char *StartSpecifier, 4617 unsigned SpecifierLen, 4618 const Expr *E); 4619 4620 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 4621 const char *startSpecifier, unsigned specifierLen); 4622 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 4623 const analyze_printf::OptionalAmount &Amt, 4624 unsigned type, 4625 const char *startSpecifier, unsigned specifierLen); 4626 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 4627 const analyze_printf::OptionalFlag &flag, 4628 const char *startSpecifier, unsigned specifierLen); 4629 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 4630 const analyze_printf::OptionalFlag &ignoredFlag, 4631 const analyze_printf::OptionalFlag &flag, 4632 const char *startSpecifier, unsigned specifierLen); 4633 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 4634 const Expr *E); 4635 4636 void HandleEmptyObjCModifierFlag(const char *startFlag, 4637 unsigned flagLen) override; 4638 4639 void HandleInvalidObjCModifierFlag(const char *startFlag, 4640 unsigned flagLen) override; 4641 4642 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 4643 const char *flagsEnd, 4644 const char *conversionPosition) 4645 override; 4646 }; 4647 } // end anonymous namespace 4648 4649 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 4650 const analyze_printf::PrintfSpecifier &FS, 4651 const char *startSpecifier, 4652 unsigned specifierLen) { 4653 const analyze_printf::PrintfConversionSpecifier &CS = 4654 FS.getConversionSpecifier(); 4655 4656 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 4657 getLocationOfByte(CS.getStart()), 4658 startSpecifier, specifierLen, 4659 CS.getStart(), CS.getLength()); 4660 } 4661 4662 bool CheckPrintfHandler::HandleAmount( 4663 const analyze_format_string::OptionalAmount &Amt, 4664 unsigned k, const char *startSpecifier, 4665 unsigned specifierLen) { 4666 if (Amt.hasDataArgument()) { 4667 if (!HasVAListArg) { 4668 unsigned argIndex = Amt.getArgIndex(); 4669 if (argIndex >= NumDataArgs) { 4670 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 4671 << k, 4672 getLocationOfByte(Amt.getStart()), 4673 /*IsStringLocation*/true, 4674 getSpecifierRange(startSpecifier, specifierLen)); 4675 // Don't do any more checking. We will just emit 4676 // spurious errors. 4677 return false; 4678 } 4679 4680 // Type check the data argument. It should be an 'int'. 4681 // Although not in conformance with C99, we also allow the argument to be 4682 // an 'unsigned int' as that is a reasonably safe case. GCC also 4683 // doesn't emit a warning for that case. 4684 CoveredArgs.set(argIndex); 4685 const Expr *Arg = getDataArg(argIndex); 4686 if (!Arg) 4687 return false; 4688 4689 QualType T = Arg->getType(); 4690 4691 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 4692 assert(AT.isValid()); 4693 4694 if (!AT.matchesType(S.Context, T)) { 4695 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 4696 << k << AT.getRepresentativeTypeName(S.Context) 4697 << T << Arg->getSourceRange(), 4698 getLocationOfByte(Amt.getStart()), 4699 /*IsStringLocation*/true, 4700 getSpecifierRange(startSpecifier, specifierLen)); 4701 // Don't do any more checking. We will just emit 4702 // spurious errors. 4703 return false; 4704 } 4705 } 4706 } 4707 return true; 4708 } 4709 4710 void CheckPrintfHandler::HandleInvalidAmount( 4711 const analyze_printf::PrintfSpecifier &FS, 4712 const analyze_printf::OptionalAmount &Amt, 4713 unsigned type, 4714 const char *startSpecifier, 4715 unsigned specifierLen) { 4716 const analyze_printf::PrintfConversionSpecifier &CS = 4717 FS.getConversionSpecifier(); 4718 4719 FixItHint fixit = 4720 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 4721 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 4722 Amt.getConstantLength())) 4723 : FixItHint(); 4724 4725 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 4726 << type << CS.toString(), 4727 getLocationOfByte(Amt.getStart()), 4728 /*IsStringLocation*/true, 4729 getSpecifierRange(startSpecifier, specifierLen), 4730 fixit); 4731 } 4732 4733 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 4734 const analyze_printf::OptionalFlag &flag, 4735 const char *startSpecifier, 4736 unsigned specifierLen) { 4737 // Warn about pointless flag with a fixit removal. 4738 const analyze_printf::PrintfConversionSpecifier &CS = 4739 FS.getConversionSpecifier(); 4740 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 4741 << flag.toString() << CS.toString(), 4742 getLocationOfByte(flag.getPosition()), 4743 /*IsStringLocation*/true, 4744 getSpecifierRange(startSpecifier, specifierLen), 4745 FixItHint::CreateRemoval( 4746 getSpecifierRange(flag.getPosition(), 1))); 4747 } 4748 4749 void CheckPrintfHandler::HandleIgnoredFlag( 4750 const analyze_printf::PrintfSpecifier &FS, 4751 const analyze_printf::OptionalFlag &ignoredFlag, 4752 const analyze_printf::OptionalFlag &flag, 4753 const char *startSpecifier, 4754 unsigned specifierLen) { 4755 // Warn about ignored flag with a fixit removal. 4756 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 4757 << ignoredFlag.toString() << flag.toString(), 4758 getLocationOfByte(ignoredFlag.getPosition()), 4759 /*IsStringLocation*/true, 4760 getSpecifierRange(startSpecifier, specifierLen), 4761 FixItHint::CreateRemoval( 4762 getSpecifierRange(ignoredFlag.getPosition(), 1))); 4763 } 4764 4765 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 4766 // bool IsStringLocation, Range StringRange, 4767 // ArrayRef<FixItHint> Fixit = None); 4768 4769 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 4770 unsigned flagLen) { 4771 // Warn about an empty flag. 4772 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 4773 getLocationOfByte(startFlag), 4774 /*IsStringLocation*/true, 4775 getSpecifierRange(startFlag, flagLen)); 4776 } 4777 4778 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 4779 unsigned flagLen) { 4780 // Warn about an invalid flag. 4781 auto Range = getSpecifierRange(startFlag, flagLen); 4782 StringRef flag(startFlag, flagLen); 4783 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 4784 getLocationOfByte(startFlag), 4785 /*IsStringLocation*/true, 4786 Range, FixItHint::CreateRemoval(Range)); 4787 } 4788 4789 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 4790 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 4791 // Warn about using '[...]' without a '@' conversion. 4792 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 4793 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 4794 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 4795 getLocationOfByte(conversionPosition), 4796 /*IsStringLocation*/true, 4797 Range, FixItHint::CreateRemoval(Range)); 4798 } 4799 4800 // Determines if the specified is a C++ class or struct containing 4801 // a member with the specified name and kind (e.g. a CXXMethodDecl named 4802 // "c_str()"). 4803 template<typename MemberKind> 4804 static llvm::SmallPtrSet<MemberKind*, 1> 4805 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 4806 const RecordType *RT = Ty->getAs<RecordType>(); 4807 llvm::SmallPtrSet<MemberKind*, 1> Results; 4808 4809 if (!RT) 4810 return Results; 4811 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 4812 if (!RD || !RD->getDefinition()) 4813 return Results; 4814 4815 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 4816 Sema::LookupMemberName); 4817 R.suppressDiagnostics(); 4818 4819 // We just need to include all members of the right kind turned up by the 4820 // filter, at this point. 4821 if (S.LookupQualifiedName(R, RT->getDecl())) 4822 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 4823 NamedDecl *decl = (*I)->getUnderlyingDecl(); 4824 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 4825 Results.insert(FK); 4826 } 4827 return Results; 4828 } 4829 4830 /// Check if we could call '.c_str()' on an object. 4831 /// 4832 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 4833 /// allow the call, or if it would be ambiguous). 4834 bool Sema::hasCStrMethod(const Expr *E) { 4835 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 4836 MethodSet Results = 4837 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 4838 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 4839 MI != ME; ++MI) 4840 if ((*MI)->getMinRequiredArguments() == 0) 4841 return true; 4842 return false; 4843 } 4844 4845 // Check if a (w)string was passed when a (w)char* was needed, and offer a 4846 // better diagnostic if so. AT is assumed to be valid. 4847 // Returns true when a c_str() conversion method is found. 4848 bool CheckPrintfHandler::checkForCStrMembers( 4849 const analyze_printf::ArgType &AT, const Expr *E) { 4850 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 4851 4852 MethodSet Results = 4853 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 4854 4855 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 4856 MI != ME; ++MI) { 4857 const CXXMethodDecl *Method = *MI; 4858 if (Method->getMinRequiredArguments() == 0 && 4859 AT.matchesType(S.Context, Method->getReturnType())) { 4860 // FIXME: Suggest parens if the expression needs them. 4861 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 4862 S.Diag(E->getLocStart(), diag::note_printf_c_str) 4863 << "c_str()" 4864 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 4865 return true; 4866 } 4867 } 4868 4869 return false; 4870 } 4871 4872 bool 4873 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 4874 &FS, 4875 const char *startSpecifier, 4876 unsigned specifierLen) { 4877 using namespace analyze_format_string; 4878 using namespace analyze_printf; 4879 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 4880 4881 if (FS.consumesDataArgument()) { 4882 if (atFirstArg) { 4883 atFirstArg = false; 4884 usesPositionalArgs = FS.usesPositionalArg(); 4885 } 4886 else if (usesPositionalArgs != FS.usesPositionalArg()) { 4887 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 4888 startSpecifier, specifierLen); 4889 return false; 4890 } 4891 } 4892 4893 // First check if the field width, precision, and conversion specifier 4894 // have matching data arguments. 4895 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 4896 startSpecifier, specifierLen)) { 4897 return false; 4898 } 4899 4900 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 4901 startSpecifier, specifierLen)) { 4902 return false; 4903 } 4904 4905 if (!CS.consumesDataArgument()) { 4906 // FIXME: Technically specifying a precision or field width here 4907 // makes no sense. Worth issuing a warning at some point. 4908 return true; 4909 } 4910 4911 // Consume the argument. 4912 unsigned argIndex = FS.getArgIndex(); 4913 if (argIndex < NumDataArgs) { 4914 // The check to see if the argIndex is valid will come later. 4915 // We set the bit here because we may exit early from this 4916 // function if we encounter some other error. 4917 CoveredArgs.set(argIndex); 4918 } 4919 4920 // FreeBSD kernel extensions. 4921 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 4922 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 4923 // We need at least two arguments. 4924 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 4925 return false; 4926 4927 // Claim the second argument. 4928 CoveredArgs.set(argIndex + 1); 4929 4930 // Type check the first argument (int for %b, pointer for %D) 4931 const Expr *Ex = getDataArg(argIndex); 4932 const analyze_printf::ArgType &AT = 4933 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 4934 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 4935 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 4936 EmitFormatDiagnostic( 4937 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 4938 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 4939 << false << Ex->getSourceRange(), 4940 Ex->getLocStart(), /*IsStringLocation*/false, 4941 getSpecifierRange(startSpecifier, specifierLen)); 4942 4943 // Type check the second argument (char * for both %b and %D) 4944 Ex = getDataArg(argIndex + 1); 4945 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 4946 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 4947 EmitFormatDiagnostic( 4948 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 4949 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 4950 << false << Ex->getSourceRange(), 4951 Ex->getLocStart(), /*IsStringLocation*/false, 4952 getSpecifierRange(startSpecifier, specifierLen)); 4953 4954 return true; 4955 } 4956 4957 // Check for using an Objective-C specific conversion specifier 4958 // in a non-ObjC literal. 4959 if (!ObjCContext && CS.isObjCArg()) { 4960 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 4961 specifierLen); 4962 } 4963 4964 // Check for invalid use of field width 4965 if (!FS.hasValidFieldWidth()) { 4966 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 4967 startSpecifier, specifierLen); 4968 } 4969 4970 // Check for invalid use of precision 4971 if (!FS.hasValidPrecision()) { 4972 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 4973 startSpecifier, specifierLen); 4974 } 4975 4976 // Check each flag does not conflict with any other component. 4977 if (!FS.hasValidThousandsGroupingPrefix()) 4978 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 4979 if (!FS.hasValidLeadingZeros()) 4980 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 4981 if (!FS.hasValidPlusPrefix()) 4982 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 4983 if (!FS.hasValidSpacePrefix()) 4984 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 4985 if (!FS.hasValidAlternativeForm()) 4986 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 4987 if (!FS.hasValidLeftJustified()) 4988 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 4989 4990 // Check that flags are not ignored by another flag 4991 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 4992 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 4993 startSpecifier, specifierLen); 4994 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 4995 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 4996 startSpecifier, specifierLen); 4997 4998 // Check the length modifier is valid with the given conversion specifier. 4999 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 5000 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5001 diag::warn_format_nonsensical_length); 5002 else if (!FS.hasStandardLengthModifier()) 5003 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 5004 else if (!FS.hasStandardLengthConversionCombination()) 5005 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5006 diag::warn_format_non_standard_conversion_spec); 5007 5008 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 5009 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 5010 5011 // The remaining checks depend on the data arguments. 5012 if (HasVAListArg) 5013 return true; 5014 5015 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 5016 return false; 5017 5018 const Expr *Arg = getDataArg(argIndex); 5019 if (!Arg) 5020 return true; 5021 5022 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 5023 } 5024 5025 static bool requiresParensToAddCast(const Expr *E) { 5026 // FIXME: We should have a general way to reason about operator 5027 // precedence and whether parens are actually needed here. 5028 // Take care of a few common cases where they aren't. 5029 const Expr *Inside = E->IgnoreImpCasts(); 5030 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 5031 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 5032 5033 switch (Inside->getStmtClass()) { 5034 case Stmt::ArraySubscriptExprClass: 5035 case Stmt::CallExprClass: 5036 case Stmt::CharacterLiteralClass: 5037 case Stmt::CXXBoolLiteralExprClass: 5038 case Stmt::DeclRefExprClass: 5039 case Stmt::FloatingLiteralClass: 5040 case Stmt::IntegerLiteralClass: 5041 case Stmt::MemberExprClass: 5042 case Stmt::ObjCArrayLiteralClass: 5043 case Stmt::ObjCBoolLiteralExprClass: 5044 case Stmt::ObjCBoxedExprClass: 5045 case Stmt::ObjCDictionaryLiteralClass: 5046 case Stmt::ObjCEncodeExprClass: 5047 case Stmt::ObjCIvarRefExprClass: 5048 case Stmt::ObjCMessageExprClass: 5049 case Stmt::ObjCPropertyRefExprClass: 5050 case Stmt::ObjCStringLiteralClass: 5051 case Stmt::ObjCSubscriptRefExprClass: 5052 case Stmt::ParenExprClass: 5053 case Stmt::StringLiteralClass: 5054 case Stmt::UnaryOperatorClass: 5055 return false; 5056 default: 5057 return true; 5058 } 5059 } 5060 5061 static std::pair<QualType, StringRef> 5062 shouldNotPrintDirectly(const ASTContext &Context, 5063 QualType IntendedTy, 5064 const Expr *E) { 5065 // Use a 'while' to peel off layers of typedefs. 5066 QualType TyTy = IntendedTy; 5067 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 5068 StringRef Name = UserTy->getDecl()->getName(); 5069 QualType CastTy = llvm::StringSwitch<QualType>(Name) 5070 .Case("NSInteger", Context.LongTy) 5071 .Case("NSUInteger", Context.UnsignedLongTy) 5072 .Case("SInt32", Context.IntTy) 5073 .Case("UInt32", Context.UnsignedIntTy) 5074 .Default(QualType()); 5075 5076 if (!CastTy.isNull()) 5077 return std::make_pair(CastTy, Name); 5078 5079 TyTy = UserTy->desugar(); 5080 } 5081 5082 // Strip parens if necessary. 5083 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 5084 return shouldNotPrintDirectly(Context, 5085 PE->getSubExpr()->getType(), 5086 PE->getSubExpr()); 5087 5088 // If this is a conditional expression, then its result type is constructed 5089 // via usual arithmetic conversions and thus there might be no necessary 5090 // typedef sugar there. Recurse to operands to check for NSInteger & 5091 // Co. usage condition. 5092 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 5093 QualType TrueTy, FalseTy; 5094 StringRef TrueName, FalseName; 5095 5096 std::tie(TrueTy, TrueName) = 5097 shouldNotPrintDirectly(Context, 5098 CO->getTrueExpr()->getType(), 5099 CO->getTrueExpr()); 5100 std::tie(FalseTy, FalseName) = 5101 shouldNotPrintDirectly(Context, 5102 CO->getFalseExpr()->getType(), 5103 CO->getFalseExpr()); 5104 5105 if (TrueTy == FalseTy) 5106 return std::make_pair(TrueTy, TrueName); 5107 else if (TrueTy.isNull()) 5108 return std::make_pair(FalseTy, FalseName); 5109 else if (FalseTy.isNull()) 5110 return std::make_pair(TrueTy, TrueName); 5111 } 5112 5113 return std::make_pair(QualType(), StringRef()); 5114 } 5115 5116 bool 5117 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5118 const char *StartSpecifier, 5119 unsigned SpecifierLen, 5120 const Expr *E) { 5121 using namespace analyze_format_string; 5122 using namespace analyze_printf; 5123 // Now type check the data expression that matches the 5124 // format specifier. 5125 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, 5126 ObjCContext); 5127 if (!AT.isValid()) 5128 return true; 5129 5130 QualType ExprTy = E->getType(); 5131 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 5132 ExprTy = TET->getUnderlyingExpr()->getType(); 5133 } 5134 5135 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 5136 5137 if (match == analyze_printf::ArgType::Match) { 5138 return true; 5139 } 5140 5141 // Look through argument promotions for our error message's reported type. 5142 // This includes the integral and floating promotions, but excludes array 5143 // and function pointer decay; seeing that an argument intended to be a 5144 // string has type 'char [6]' is probably more confusing than 'char *'. 5145 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5146 if (ICE->getCastKind() == CK_IntegralCast || 5147 ICE->getCastKind() == CK_FloatingCast) { 5148 E = ICE->getSubExpr(); 5149 ExprTy = E->getType(); 5150 5151 // Check if we didn't match because of an implicit cast from a 'char' 5152 // or 'short' to an 'int'. This is done because printf is a varargs 5153 // function. 5154 if (ICE->getType() == S.Context.IntTy || 5155 ICE->getType() == S.Context.UnsignedIntTy) { 5156 // All further checking is done on the subexpression. 5157 if (AT.matchesType(S.Context, ExprTy)) 5158 return true; 5159 } 5160 } 5161 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 5162 // Special case for 'a', which has type 'int' in C. 5163 // Note, however, that we do /not/ want to treat multibyte constants like 5164 // 'MooV' as characters! This form is deprecated but still exists. 5165 if (ExprTy == S.Context.IntTy) 5166 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 5167 ExprTy = S.Context.CharTy; 5168 } 5169 5170 // Look through enums to their underlying type. 5171 bool IsEnum = false; 5172 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 5173 ExprTy = EnumTy->getDecl()->getIntegerType(); 5174 IsEnum = true; 5175 } 5176 5177 // %C in an Objective-C context prints a unichar, not a wchar_t. 5178 // If the argument is an integer of some kind, believe the %C and suggest 5179 // a cast instead of changing the conversion specifier. 5180 QualType IntendedTy = ExprTy; 5181 if (ObjCContext && 5182 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 5183 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 5184 !ExprTy->isCharType()) { 5185 // 'unichar' is defined as a typedef of unsigned short, but we should 5186 // prefer using the typedef if it is visible. 5187 IntendedTy = S.Context.UnsignedShortTy; 5188 5189 // While we are here, check if the value is an IntegerLiteral that happens 5190 // to be within the valid range. 5191 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 5192 const llvm::APInt &V = IL->getValue(); 5193 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 5194 return true; 5195 } 5196 5197 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 5198 Sema::LookupOrdinaryName); 5199 if (S.LookupName(Result, S.getCurScope())) { 5200 NamedDecl *ND = Result.getFoundDecl(); 5201 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 5202 if (TD->getUnderlyingType() == IntendedTy) 5203 IntendedTy = S.Context.getTypedefType(TD); 5204 } 5205 } 5206 } 5207 5208 // Special-case some of Darwin's platform-independence types by suggesting 5209 // casts to primitive types that are known to be large enough. 5210 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 5211 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 5212 QualType CastTy; 5213 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 5214 if (!CastTy.isNull()) { 5215 IntendedTy = CastTy; 5216 ShouldNotPrintDirectly = true; 5217 } 5218 } 5219 5220 // We may be able to offer a FixItHint if it is a supported type. 5221 PrintfSpecifier fixedFS = FS; 5222 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(), 5223 S.Context, ObjCContext); 5224 5225 if (success) { 5226 // Get the fix string from the fixed format specifier 5227 SmallString<16> buf; 5228 llvm::raw_svector_ostream os(buf); 5229 fixedFS.toString(os); 5230 5231 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 5232 5233 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 5234 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 5235 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 5236 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 5237 } 5238 // In this case, the specifier is wrong and should be changed to match 5239 // the argument. 5240 EmitFormatDiagnostic(S.PDiag(diag) 5241 << AT.getRepresentativeTypeName(S.Context) 5242 << IntendedTy << IsEnum << E->getSourceRange(), 5243 E->getLocStart(), 5244 /*IsStringLocation*/ false, SpecRange, 5245 FixItHint::CreateReplacement(SpecRange, os.str())); 5246 } else { 5247 // The canonical type for formatting this value is different from the 5248 // actual type of the expression. (This occurs, for example, with Darwin's 5249 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 5250 // should be printed as 'long' for 64-bit compatibility.) 5251 // Rather than emitting a normal format/argument mismatch, we want to 5252 // add a cast to the recommended type (and correct the format string 5253 // if necessary). 5254 SmallString<16> CastBuf; 5255 llvm::raw_svector_ostream CastFix(CastBuf); 5256 CastFix << "("; 5257 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 5258 CastFix << ")"; 5259 5260 SmallVector<FixItHint,4> Hints; 5261 if (!AT.matchesType(S.Context, IntendedTy)) 5262 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 5263 5264 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 5265 // If there's already a cast present, just replace it. 5266 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 5267 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 5268 5269 } else if (!requiresParensToAddCast(E)) { 5270 // If the expression has high enough precedence, 5271 // just write the C-style cast. 5272 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 5273 CastFix.str())); 5274 } else { 5275 // Otherwise, add parens around the expression as well as the cast. 5276 CastFix << "("; 5277 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 5278 CastFix.str())); 5279 5280 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 5281 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 5282 } 5283 5284 if (ShouldNotPrintDirectly) { 5285 // The expression has a type that should not be printed directly. 5286 // We extract the name from the typedef because we don't want to show 5287 // the underlying type in the diagnostic. 5288 StringRef Name; 5289 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 5290 Name = TypedefTy->getDecl()->getName(); 5291 else 5292 Name = CastTyName; 5293 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 5294 << Name << IntendedTy << IsEnum 5295 << E->getSourceRange(), 5296 E->getLocStart(), /*IsStringLocation=*/false, 5297 SpecRange, Hints); 5298 } else { 5299 // In this case, the expression could be printed using a different 5300 // specifier, but we've decided that the specifier is probably correct 5301 // and we should cast instead. Just use the normal warning message. 5302 EmitFormatDiagnostic( 5303 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5304 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 5305 << E->getSourceRange(), 5306 E->getLocStart(), /*IsStringLocation*/false, 5307 SpecRange, Hints); 5308 } 5309 } 5310 } else { 5311 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 5312 SpecifierLen); 5313 // Since the warning for passing non-POD types to variadic functions 5314 // was deferred until now, we emit a warning for non-POD 5315 // arguments here. 5316 switch (S.isValidVarArgType(ExprTy)) { 5317 case Sema::VAK_Valid: 5318 case Sema::VAK_ValidInCXX11: { 5319 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 5320 if (match == analyze_printf::ArgType::NoMatchPedantic) { 5321 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 5322 } 5323 5324 EmitFormatDiagnostic( 5325 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 5326 << IsEnum << CSR << E->getSourceRange(), 5327 E->getLocStart(), /*IsStringLocation*/ false, CSR); 5328 break; 5329 } 5330 case Sema::VAK_Undefined: 5331 case Sema::VAK_MSVCUndefined: 5332 EmitFormatDiagnostic( 5333 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 5334 << S.getLangOpts().CPlusPlus11 5335 << ExprTy 5336 << CallType 5337 << AT.getRepresentativeTypeName(S.Context) 5338 << CSR 5339 << E->getSourceRange(), 5340 E->getLocStart(), /*IsStringLocation*/false, CSR); 5341 checkForCStrMembers(AT, E); 5342 break; 5343 5344 case Sema::VAK_Invalid: 5345 if (ExprTy->isObjCObjectType()) 5346 EmitFormatDiagnostic( 5347 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 5348 << S.getLangOpts().CPlusPlus11 5349 << ExprTy 5350 << CallType 5351 << AT.getRepresentativeTypeName(S.Context) 5352 << CSR 5353 << E->getSourceRange(), 5354 E->getLocStart(), /*IsStringLocation*/false, CSR); 5355 else 5356 // FIXME: If this is an initializer list, suggest removing the braces 5357 // or inserting a cast to the target type. 5358 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 5359 << isa<InitListExpr>(E) << ExprTy << CallType 5360 << AT.getRepresentativeTypeName(S.Context) 5361 << E->getSourceRange(); 5362 break; 5363 } 5364 5365 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 5366 "format string specifier index out of range"); 5367 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 5368 } 5369 5370 return true; 5371 } 5372 5373 //===--- CHECK: Scanf format string checking ------------------------------===// 5374 5375 namespace { 5376 class CheckScanfHandler : public CheckFormatHandler { 5377 public: 5378 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 5379 const Expr *origFormatExpr, unsigned firstDataArg, 5380 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5381 ArrayRef<const Expr *> Args, 5382 unsigned formatIdx, bool inFunctionCall, 5383 Sema::VariadicCallType CallType, 5384 llvm::SmallBitVector &CheckedVarArgs, 5385 UncoveredArgHandler &UncoveredArg) 5386 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 5387 numDataArgs, beg, hasVAListArg, 5388 Args, formatIdx, inFunctionCall, CallType, 5389 CheckedVarArgs, UncoveredArg) 5390 {} 5391 5392 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 5393 const char *startSpecifier, 5394 unsigned specifierLen) override; 5395 5396 bool HandleInvalidScanfConversionSpecifier( 5397 const analyze_scanf::ScanfSpecifier &FS, 5398 const char *startSpecifier, 5399 unsigned specifierLen) override; 5400 5401 void HandleIncompleteScanList(const char *start, const char *end) override; 5402 }; 5403 } // end anonymous namespace 5404 5405 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 5406 const char *end) { 5407 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 5408 getLocationOfByte(end), /*IsStringLocation*/true, 5409 getSpecifierRange(start, end - start)); 5410 } 5411 5412 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 5413 const analyze_scanf::ScanfSpecifier &FS, 5414 const char *startSpecifier, 5415 unsigned specifierLen) { 5416 5417 const analyze_scanf::ScanfConversionSpecifier &CS = 5418 FS.getConversionSpecifier(); 5419 5420 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5421 getLocationOfByte(CS.getStart()), 5422 startSpecifier, specifierLen, 5423 CS.getStart(), CS.getLength()); 5424 } 5425 5426 bool CheckScanfHandler::HandleScanfSpecifier( 5427 const analyze_scanf::ScanfSpecifier &FS, 5428 const char *startSpecifier, 5429 unsigned specifierLen) { 5430 using namespace analyze_scanf; 5431 using namespace analyze_format_string; 5432 5433 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 5434 5435 // Handle case where '%' and '*' don't consume an argument. These shouldn't 5436 // be used to decide if we are using positional arguments consistently. 5437 if (FS.consumesDataArgument()) { 5438 if (atFirstArg) { 5439 atFirstArg = false; 5440 usesPositionalArgs = FS.usesPositionalArg(); 5441 } 5442 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5443 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5444 startSpecifier, specifierLen); 5445 return false; 5446 } 5447 } 5448 5449 // Check if the field with is non-zero. 5450 const OptionalAmount &Amt = FS.getFieldWidth(); 5451 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 5452 if (Amt.getConstantAmount() == 0) { 5453 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 5454 Amt.getConstantLength()); 5455 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 5456 getLocationOfByte(Amt.getStart()), 5457 /*IsStringLocation*/true, R, 5458 FixItHint::CreateRemoval(R)); 5459 } 5460 } 5461 5462 if (!FS.consumesDataArgument()) { 5463 // FIXME: Technically specifying a precision or field width here 5464 // makes no sense. Worth issuing a warning at some point. 5465 return true; 5466 } 5467 5468 // Consume the argument. 5469 unsigned argIndex = FS.getArgIndex(); 5470 if (argIndex < NumDataArgs) { 5471 // The check to see if the argIndex is valid will come later. 5472 // We set the bit here because we may exit early from this 5473 // function if we encounter some other error. 5474 CoveredArgs.set(argIndex); 5475 } 5476 5477 // Check the length modifier is valid with the given conversion specifier. 5478 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 5479 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5480 diag::warn_format_nonsensical_length); 5481 else if (!FS.hasStandardLengthModifier()) 5482 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 5483 else if (!FS.hasStandardLengthConversionCombination()) 5484 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5485 diag::warn_format_non_standard_conversion_spec); 5486 5487 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 5488 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 5489 5490 // The remaining checks depend on the data arguments. 5491 if (HasVAListArg) 5492 return true; 5493 5494 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 5495 return false; 5496 5497 // Check that the argument type matches the format specifier. 5498 const Expr *Ex = getDataArg(argIndex); 5499 if (!Ex) 5500 return true; 5501 5502 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 5503 5504 if (!AT.isValid()) { 5505 return true; 5506 } 5507 5508 analyze_format_string::ArgType::MatchKind match = 5509 AT.matchesType(S.Context, Ex->getType()); 5510 if (match == analyze_format_string::ArgType::Match) { 5511 return true; 5512 } 5513 5514 ScanfSpecifier fixedFS = FS; 5515 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 5516 S.getLangOpts(), S.Context); 5517 5518 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 5519 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 5520 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 5521 } 5522 5523 if (success) { 5524 // Get the fix string from the fixed format specifier. 5525 SmallString<128> buf; 5526 llvm::raw_svector_ostream os(buf); 5527 fixedFS.toString(os); 5528 5529 EmitFormatDiagnostic( 5530 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 5531 << Ex->getType() << false << Ex->getSourceRange(), 5532 Ex->getLocStart(), 5533 /*IsStringLocation*/ false, 5534 getSpecifierRange(startSpecifier, specifierLen), 5535 FixItHint::CreateReplacement( 5536 getSpecifierRange(startSpecifier, specifierLen), os.str())); 5537 } else { 5538 EmitFormatDiagnostic(S.PDiag(diag) 5539 << AT.getRepresentativeTypeName(S.Context) 5540 << Ex->getType() << false << Ex->getSourceRange(), 5541 Ex->getLocStart(), 5542 /*IsStringLocation*/ false, 5543 getSpecifierRange(startSpecifier, specifierLen)); 5544 } 5545 5546 return true; 5547 } 5548 5549 static void CheckFormatString(Sema &S, const StringLiteral *FExpr, 5550 const Expr *OrigFormatExpr, 5551 ArrayRef<const Expr *> Args, 5552 bool HasVAListArg, unsigned format_idx, 5553 unsigned firstDataArg, 5554 Sema::FormatStringType Type, 5555 bool inFunctionCall, 5556 Sema::VariadicCallType CallType, 5557 llvm::SmallBitVector &CheckedVarArgs, 5558 UncoveredArgHandler &UncoveredArg) { 5559 // CHECK: is the format string a wide literal? 5560 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 5561 CheckFormatHandler::EmitFormatDiagnostic( 5562 S, inFunctionCall, Args[format_idx], 5563 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 5564 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 5565 return; 5566 } 5567 5568 // Str - The format string. NOTE: this is NOT null-terminated! 5569 StringRef StrRef = FExpr->getString(); 5570 const char *Str = StrRef.data(); 5571 // Account for cases where the string literal is truncated in a declaration. 5572 const ConstantArrayType *T = 5573 S.Context.getAsConstantArrayType(FExpr->getType()); 5574 assert(T && "String literal not of constant array type!"); 5575 size_t TypeSize = T->getSize().getZExtValue(); 5576 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 5577 const unsigned numDataArgs = Args.size() - firstDataArg; 5578 5579 // Emit a warning if the string literal is truncated and does not contain an 5580 // embedded null character. 5581 if (TypeSize <= StrRef.size() && 5582 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 5583 CheckFormatHandler::EmitFormatDiagnostic( 5584 S, inFunctionCall, Args[format_idx], 5585 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 5586 FExpr->getLocStart(), 5587 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 5588 return; 5589 } 5590 5591 // CHECK: empty format string? 5592 if (StrLen == 0 && numDataArgs > 0) { 5593 CheckFormatHandler::EmitFormatDiagnostic( 5594 S, inFunctionCall, Args[format_idx], 5595 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 5596 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 5597 return; 5598 } 5599 5600 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 5601 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) { 5602 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, 5603 numDataArgs, (Type == Sema::FST_NSString || 5604 Type == Sema::FST_OSTrace), 5605 Str, HasVAListArg, Args, format_idx, 5606 inFunctionCall, CallType, CheckedVarArgs, 5607 UncoveredArg); 5608 5609 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 5610 S.getLangOpts(), 5611 S.Context.getTargetInfo(), 5612 Type == Sema::FST_FreeBSDKPrintf)) 5613 H.DoneProcessing(); 5614 } else if (Type == Sema::FST_Scanf) { 5615 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs, 5616 Str, HasVAListArg, Args, format_idx, 5617 inFunctionCall, CallType, CheckedVarArgs, 5618 UncoveredArg); 5619 5620 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 5621 S.getLangOpts(), 5622 S.Context.getTargetInfo())) 5623 H.DoneProcessing(); 5624 } // TODO: handle other formats 5625 } 5626 5627 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 5628 // Str - The format string. NOTE: this is NOT null-terminated! 5629 StringRef StrRef = FExpr->getString(); 5630 const char *Str = StrRef.data(); 5631 // Account for cases where the string literal is truncated in a declaration. 5632 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 5633 assert(T && "String literal not of constant array type!"); 5634 size_t TypeSize = T->getSize().getZExtValue(); 5635 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 5636 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 5637 getLangOpts(), 5638 Context.getTargetInfo()); 5639 } 5640 5641 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 5642 5643 // Returns the related absolute value function that is larger, of 0 if one 5644 // does not exist. 5645 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 5646 switch (AbsFunction) { 5647 default: 5648 return 0; 5649 5650 case Builtin::BI__builtin_abs: 5651 return Builtin::BI__builtin_labs; 5652 case Builtin::BI__builtin_labs: 5653 return Builtin::BI__builtin_llabs; 5654 case Builtin::BI__builtin_llabs: 5655 return 0; 5656 5657 case Builtin::BI__builtin_fabsf: 5658 return Builtin::BI__builtin_fabs; 5659 case Builtin::BI__builtin_fabs: 5660 return Builtin::BI__builtin_fabsl; 5661 case Builtin::BI__builtin_fabsl: 5662 return 0; 5663 5664 case Builtin::BI__builtin_cabsf: 5665 return Builtin::BI__builtin_cabs; 5666 case Builtin::BI__builtin_cabs: 5667 return Builtin::BI__builtin_cabsl; 5668 case Builtin::BI__builtin_cabsl: 5669 return 0; 5670 5671 case Builtin::BIabs: 5672 return Builtin::BIlabs; 5673 case Builtin::BIlabs: 5674 return Builtin::BIllabs; 5675 case Builtin::BIllabs: 5676 return 0; 5677 5678 case Builtin::BIfabsf: 5679 return Builtin::BIfabs; 5680 case Builtin::BIfabs: 5681 return Builtin::BIfabsl; 5682 case Builtin::BIfabsl: 5683 return 0; 5684 5685 case Builtin::BIcabsf: 5686 return Builtin::BIcabs; 5687 case Builtin::BIcabs: 5688 return Builtin::BIcabsl; 5689 case Builtin::BIcabsl: 5690 return 0; 5691 } 5692 } 5693 5694 // Returns the argument type of the absolute value function. 5695 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 5696 unsigned AbsType) { 5697 if (AbsType == 0) 5698 return QualType(); 5699 5700 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 5701 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 5702 if (Error != ASTContext::GE_None) 5703 return QualType(); 5704 5705 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 5706 if (!FT) 5707 return QualType(); 5708 5709 if (FT->getNumParams() != 1) 5710 return QualType(); 5711 5712 return FT->getParamType(0); 5713 } 5714 5715 // Returns the best absolute value function, or zero, based on type and 5716 // current absolute value function. 5717 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 5718 unsigned AbsFunctionKind) { 5719 unsigned BestKind = 0; 5720 uint64_t ArgSize = Context.getTypeSize(ArgType); 5721 for (unsigned Kind = AbsFunctionKind; Kind != 0; 5722 Kind = getLargerAbsoluteValueFunction(Kind)) { 5723 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 5724 if (Context.getTypeSize(ParamType) >= ArgSize) { 5725 if (BestKind == 0) 5726 BestKind = Kind; 5727 else if (Context.hasSameType(ParamType, ArgType)) { 5728 BestKind = Kind; 5729 break; 5730 } 5731 } 5732 } 5733 return BestKind; 5734 } 5735 5736 enum AbsoluteValueKind { 5737 AVK_Integer, 5738 AVK_Floating, 5739 AVK_Complex 5740 }; 5741 5742 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 5743 if (T->isIntegralOrEnumerationType()) 5744 return AVK_Integer; 5745 if (T->isRealFloatingType()) 5746 return AVK_Floating; 5747 if (T->isAnyComplexType()) 5748 return AVK_Complex; 5749 5750 llvm_unreachable("Type not integer, floating, or complex"); 5751 } 5752 5753 // Changes the absolute value function to a different type. Preserves whether 5754 // the function is a builtin. 5755 static unsigned changeAbsFunction(unsigned AbsKind, 5756 AbsoluteValueKind ValueKind) { 5757 switch (ValueKind) { 5758 case AVK_Integer: 5759 switch (AbsKind) { 5760 default: 5761 return 0; 5762 case Builtin::BI__builtin_fabsf: 5763 case Builtin::BI__builtin_fabs: 5764 case Builtin::BI__builtin_fabsl: 5765 case Builtin::BI__builtin_cabsf: 5766 case Builtin::BI__builtin_cabs: 5767 case Builtin::BI__builtin_cabsl: 5768 return Builtin::BI__builtin_abs; 5769 case Builtin::BIfabsf: 5770 case Builtin::BIfabs: 5771 case Builtin::BIfabsl: 5772 case Builtin::BIcabsf: 5773 case Builtin::BIcabs: 5774 case Builtin::BIcabsl: 5775 return Builtin::BIabs; 5776 } 5777 case AVK_Floating: 5778 switch (AbsKind) { 5779 default: 5780 return 0; 5781 case Builtin::BI__builtin_abs: 5782 case Builtin::BI__builtin_labs: 5783 case Builtin::BI__builtin_llabs: 5784 case Builtin::BI__builtin_cabsf: 5785 case Builtin::BI__builtin_cabs: 5786 case Builtin::BI__builtin_cabsl: 5787 return Builtin::BI__builtin_fabsf; 5788 case Builtin::BIabs: 5789 case Builtin::BIlabs: 5790 case Builtin::BIllabs: 5791 case Builtin::BIcabsf: 5792 case Builtin::BIcabs: 5793 case Builtin::BIcabsl: 5794 return Builtin::BIfabsf; 5795 } 5796 case AVK_Complex: 5797 switch (AbsKind) { 5798 default: 5799 return 0; 5800 case Builtin::BI__builtin_abs: 5801 case Builtin::BI__builtin_labs: 5802 case Builtin::BI__builtin_llabs: 5803 case Builtin::BI__builtin_fabsf: 5804 case Builtin::BI__builtin_fabs: 5805 case Builtin::BI__builtin_fabsl: 5806 return Builtin::BI__builtin_cabsf; 5807 case Builtin::BIabs: 5808 case Builtin::BIlabs: 5809 case Builtin::BIllabs: 5810 case Builtin::BIfabsf: 5811 case Builtin::BIfabs: 5812 case Builtin::BIfabsl: 5813 return Builtin::BIcabsf; 5814 } 5815 } 5816 llvm_unreachable("Unable to convert function"); 5817 } 5818 5819 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 5820 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 5821 if (!FnInfo) 5822 return 0; 5823 5824 switch (FDecl->getBuiltinID()) { 5825 default: 5826 return 0; 5827 case Builtin::BI__builtin_abs: 5828 case Builtin::BI__builtin_fabs: 5829 case Builtin::BI__builtin_fabsf: 5830 case Builtin::BI__builtin_fabsl: 5831 case Builtin::BI__builtin_labs: 5832 case Builtin::BI__builtin_llabs: 5833 case Builtin::BI__builtin_cabs: 5834 case Builtin::BI__builtin_cabsf: 5835 case Builtin::BI__builtin_cabsl: 5836 case Builtin::BIabs: 5837 case Builtin::BIlabs: 5838 case Builtin::BIllabs: 5839 case Builtin::BIfabs: 5840 case Builtin::BIfabsf: 5841 case Builtin::BIfabsl: 5842 case Builtin::BIcabs: 5843 case Builtin::BIcabsf: 5844 case Builtin::BIcabsl: 5845 return FDecl->getBuiltinID(); 5846 } 5847 llvm_unreachable("Unknown Builtin type"); 5848 } 5849 5850 // If the replacement is valid, emit a note with replacement function. 5851 // Additionally, suggest including the proper header if not already included. 5852 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 5853 unsigned AbsKind, QualType ArgType) { 5854 bool EmitHeaderHint = true; 5855 const char *HeaderName = nullptr; 5856 const char *FunctionName = nullptr; 5857 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 5858 FunctionName = "std::abs"; 5859 if (ArgType->isIntegralOrEnumerationType()) { 5860 HeaderName = "cstdlib"; 5861 } else if (ArgType->isRealFloatingType()) { 5862 HeaderName = "cmath"; 5863 } else { 5864 llvm_unreachable("Invalid Type"); 5865 } 5866 5867 // Lookup all std::abs 5868 if (NamespaceDecl *Std = S.getStdNamespace()) { 5869 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 5870 R.suppressDiagnostics(); 5871 S.LookupQualifiedName(R, Std); 5872 5873 for (const auto *I : R) { 5874 const FunctionDecl *FDecl = nullptr; 5875 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 5876 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 5877 } else { 5878 FDecl = dyn_cast<FunctionDecl>(I); 5879 } 5880 if (!FDecl) 5881 continue; 5882 5883 // Found std::abs(), check that they are the right ones. 5884 if (FDecl->getNumParams() != 1) 5885 continue; 5886 5887 // Check that the parameter type can handle the argument. 5888 QualType ParamType = FDecl->getParamDecl(0)->getType(); 5889 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 5890 S.Context.getTypeSize(ArgType) <= 5891 S.Context.getTypeSize(ParamType)) { 5892 // Found a function, don't need the header hint. 5893 EmitHeaderHint = false; 5894 break; 5895 } 5896 } 5897 } 5898 } else { 5899 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 5900 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 5901 5902 if (HeaderName) { 5903 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 5904 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 5905 R.suppressDiagnostics(); 5906 S.LookupName(R, S.getCurScope()); 5907 5908 if (R.isSingleResult()) { 5909 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 5910 if (FD && FD->getBuiltinID() == AbsKind) { 5911 EmitHeaderHint = false; 5912 } else { 5913 return; 5914 } 5915 } else if (!R.empty()) { 5916 return; 5917 } 5918 } 5919 } 5920 5921 S.Diag(Loc, diag::note_replace_abs_function) 5922 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 5923 5924 if (!HeaderName) 5925 return; 5926 5927 if (!EmitHeaderHint) 5928 return; 5929 5930 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 5931 << FunctionName; 5932 } 5933 5934 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) { 5935 if (!FDecl) 5936 return false; 5937 5938 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs")) 5939 return false; 5940 5941 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext()); 5942 5943 while (ND && ND->isInlineNamespace()) { 5944 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext()); 5945 } 5946 5947 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std")) 5948 return false; 5949 5950 if (!isa<TranslationUnitDecl>(ND->getDeclContext())) 5951 return false; 5952 5953 return true; 5954 } 5955 5956 // Warn when using the wrong abs() function. 5957 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 5958 const FunctionDecl *FDecl, 5959 IdentifierInfo *FnInfo) { 5960 if (Call->getNumArgs() != 1) 5961 return; 5962 5963 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 5964 bool IsStdAbs = IsFunctionStdAbs(FDecl); 5965 if (AbsKind == 0 && !IsStdAbs) 5966 return; 5967 5968 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 5969 QualType ParamType = Call->getArg(0)->getType(); 5970 5971 // Unsigned types cannot be negative. Suggest removing the absolute value 5972 // function call. 5973 if (ArgType->isUnsignedIntegerType()) { 5974 const char *FunctionName = 5975 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 5976 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 5977 Diag(Call->getExprLoc(), diag::note_remove_abs) 5978 << FunctionName 5979 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 5980 return; 5981 } 5982 5983 // Taking the absolute value of a pointer is very suspicious, they probably 5984 // wanted to index into an array, dereference a pointer, call a function, etc. 5985 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 5986 unsigned DiagType = 0; 5987 if (ArgType->isFunctionType()) 5988 DiagType = 1; 5989 else if (ArgType->isArrayType()) 5990 DiagType = 2; 5991 5992 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 5993 return; 5994 } 5995 5996 // std::abs has overloads which prevent most of the absolute value problems 5997 // from occurring. 5998 if (IsStdAbs) 5999 return; 6000 6001 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 6002 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 6003 6004 // The argument and parameter are the same kind. Check if they are the right 6005 // size. 6006 if (ArgValueKind == ParamValueKind) { 6007 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 6008 return; 6009 6010 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 6011 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 6012 << FDecl << ArgType << ParamType; 6013 6014 if (NewAbsKind == 0) 6015 return; 6016 6017 emitReplacement(*this, Call->getExprLoc(), 6018 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6019 return; 6020 } 6021 6022 // ArgValueKind != ParamValueKind 6023 // The wrong type of absolute value function was used. Attempt to find the 6024 // proper one. 6025 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 6026 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 6027 if (NewAbsKind == 0) 6028 return; 6029 6030 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 6031 << FDecl << ParamValueKind << ArgValueKind; 6032 6033 emitReplacement(*this, Call->getExprLoc(), 6034 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6035 } 6036 6037 //===--- CHECK: Standard memory functions ---------------------------------===// 6038 6039 /// \brief Takes the expression passed to the size_t parameter of functions 6040 /// such as memcmp, strncat, etc and warns if it's a comparison. 6041 /// 6042 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 6043 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 6044 IdentifierInfo *FnName, 6045 SourceLocation FnLoc, 6046 SourceLocation RParenLoc) { 6047 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 6048 if (!Size) 6049 return false; 6050 6051 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 6052 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 6053 return false; 6054 6055 SourceRange SizeRange = Size->getSourceRange(); 6056 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 6057 << SizeRange << FnName; 6058 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 6059 << FnName << FixItHint::CreateInsertion( 6060 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 6061 << FixItHint::CreateRemoval(RParenLoc); 6062 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 6063 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 6064 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 6065 ")"); 6066 6067 return true; 6068 } 6069 6070 /// \brief Determine whether the given type is or contains a dynamic class type 6071 /// (e.g., whether it has a vtable). 6072 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 6073 bool &IsContained) { 6074 // Look through array types while ignoring qualifiers. 6075 const Type *Ty = T->getBaseElementTypeUnsafe(); 6076 IsContained = false; 6077 6078 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 6079 RD = RD ? RD->getDefinition() : nullptr; 6080 if (!RD || RD->isInvalidDecl()) 6081 return nullptr; 6082 6083 if (RD->isDynamicClass()) 6084 return RD; 6085 6086 // Check all the fields. If any bases were dynamic, the class is dynamic. 6087 // It's impossible for a class to transitively contain itself by value, so 6088 // infinite recursion is impossible. 6089 for (auto *FD : RD->fields()) { 6090 bool SubContained; 6091 if (const CXXRecordDecl *ContainedRD = 6092 getContainedDynamicClass(FD->getType(), SubContained)) { 6093 IsContained = true; 6094 return ContainedRD; 6095 } 6096 } 6097 6098 return nullptr; 6099 } 6100 6101 /// \brief If E is a sizeof expression, returns its argument expression, 6102 /// otherwise returns NULL. 6103 static const Expr *getSizeOfExprArg(const Expr *E) { 6104 if (const UnaryExprOrTypeTraitExpr *SizeOf = 6105 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 6106 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 6107 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 6108 6109 return nullptr; 6110 } 6111 6112 /// \brief If E is a sizeof expression, returns its argument type. 6113 static QualType getSizeOfArgType(const Expr *E) { 6114 if (const UnaryExprOrTypeTraitExpr *SizeOf = 6115 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 6116 if (SizeOf->getKind() == clang::UETT_SizeOf) 6117 return SizeOf->getTypeOfArgument(); 6118 6119 return QualType(); 6120 } 6121 6122 /// \brief Check for dangerous or invalid arguments to memset(). 6123 /// 6124 /// This issues warnings on known problematic, dangerous or unspecified 6125 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 6126 /// function calls. 6127 /// 6128 /// \param Call The call expression to diagnose. 6129 void Sema::CheckMemaccessArguments(const CallExpr *Call, 6130 unsigned BId, 6131 IdentifierInfo *FnName) { 6132 assert(BId != 0); 6133 6134 // It is possible to have a non-standard definition of memset. Validate 6135 // we have enough arguments, and if not, abort further checking. 6136 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3); 6137 if (Call->getNumArgs() < ExpectedNumArgs) 6138 return; 6139 6140 unsigned LastArg = (BId == Builtin::BImemset || 6141 BId == Builtin::BIstrndup ? 1 : 2); 6142 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2); 6143 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 6144 6145 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 6146 Call->getLocStart(), Call->getRParenLoc())) 6147 return; 6148 6149 // We have special checking when the length is a sizeof expression. 6150 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 6151 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 6152 llvm::FoldingSetNodeID SizeOfArgID; 6153 6154 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 6155 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 6156 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 6157 6158 QualType DestTy = Dest->getType(); 6159 QualType PointeeTy; 6160 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 6161 PointeeTy = DestPtrTy->getPointeeType(); 6162 6163 // Never warn about void type pointers. This can be used to suppress 6164 // false positives. 6165 if (PointeeTy->isVoidType()) 6166 continue; 6167 6168 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 6169 // actually comparing the expressions for equality. Because computing the 6170 // expression IDs can be expensive, we only do this if the diagnostic is 6171 // enabled. 6172 if (SizeOfArg && 6173 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 6174 SizeOfArg->getExprLoc())) { 6175 // We only compute IDs for expressions if the warning is enabled, and 6176 // cache the sizeof arg's ID. 6177 if (SizeOfArgID == llvm::FoldingSetNodeID()) 6178 SizeOfArg->Profile(SizeOfArgID, Context, true); 6179 llvm::FoldingSetNodeID DestID; 6180 Dest->Profile(DestID, Context, true); 6181 if (DestID == SizeOfArgID) { 6182 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 6183 // over sizeof(src) as well. 6184 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 6185 StringRef ReadableName = FnName->getName(); 6186 6187 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 6188 if (UnaryOp->getOpcode() == UO_AddrOf) 6189 ActionIdx = 1; // If its an address-of operator, just remove it. 6190 if (!PointeeTy->isIncompleteType() && 6191 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 6192 ActionIdx = 2; // If the pointee's size is sizeof(char), 6193 // suggest an explicit length. 6194 6195 // If the function is defined as a builtin macro, do not show macro 6196 // expansion. 6197 SourceLocation SL = SizeOfArg->getExprLoc(); 6198 SourceRange DSR = Dest->getSourceRange(); 6199 SourceRange SSR = SizeOfArg->getSourceRange(); 6200 SourceManager &SM = getSourceManager(); 6201 6202 if (SM.isMacroArgExpansion(SL)) { 6203 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 6204 SL = SM.getSpellingLoc(SL); 6205 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 6206 SM.getSpellingLoc(DSR.getEnd())); 6207 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 6208 SM.getSpellingLoc(SSR.getEnd())); 6209 } 6210 6211 DiagRuntimeBehavior(SL, SizeOfArg, 6212 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 6213 << ReadableName 6214 << PointeeTy 6215 << DestTy 6216 << DSR 6217 << SSR); 6218 DiagRuntimeBehavior(SL, SizeOfArg, 6219 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 6220 << ActionIdx 6221 << SSR); 6222 6223 break; 6224 } 6225 } 6226 6227 // Also check for cases where the sizeof argument is the exact same 6228 // type as the memory argument, and where it points to a user-defined 6229 // record type. 6230 if (SizeOfArgTy != QualType()) { 6231 if (PointeeTy->isRecordType() && 6232 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 6233 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 6234 PDiag(diag::warn_sizeof_pointer_type_memaccess) 6235 << FnName << SizeOfArgTy << ArgIdx 6236 << PointeeTy << Dest->getSourceRange() 6237 << LenExpr->getSourceRange()); 6238 break; 6239 } 6240 } 6241 } else if (DestTy->isArrayType()) { 6242 PointeeTy = DestTy; 6243 } 6244 6245 if (PointeeTy == QualType()) 6246 continue; 6247 6248 // Always complain about dynamic classes. 6249 bool IsContained; 6250 if (const CXXRecordDecl *ContainedRD = 6251 getContainedDynamicClass(PointeeTy, IsContained)) { 6252 6253 unsigned OperationType = 0; 6254 // "overwritten" if we're warning about the destination for any call 6255 // but memcmp; otherwise a verb appropriate to the call. 6256 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 6257 if (BId == Builtin::BImemcpy) 6258 OperationType = 1; 6259 else if(BId == Builtin::BImemmove) 6260 OperationType = 2; 6261 else if (BId == Builtin::BImemcmp) 6262 OperationType = 3; 6263 } 6264 6265 DiagRuntimeBehavior( 6266 Dest->getExprLoc(), Dest, 6267 PDiag(diag::warn_dyn_class_memaccess) 6268 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 6269 << FnName << IsContained << ContainedRD << OperationType 6270 << Call->getCallee()->getSourceRange()); 6271 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 6272 BId != Builtin::BImemset) 6273 DiagRuntimeBehavior( 6274 Dest->getExprLoc(), Dest, 6275 PDiag(diag::warn_arc_object_memaccess) 6276 << ArgIdx << FnName << PointeeTy 6277 << Call->getCallee()->getSourceRange()); 6278 else 6279 continue; 6280 6281 DiagRuntimeBehavior( 6282 Dest->getExprLoc(), Dest, 6283 PDiag(diag::note_bad_memaccess_silence) 6284 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 6285 break; 6286 } 6287 } 6288 6289 // A little helper routine: ignore addition and subtraction of integer literals. 6290 // This intentionally does not ignore all integer constant expressions because 6291 // we don't want to remove sizeof(). 6292 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 6293 Ex = Ex->IgnoreParenCasts(); 6294 6295 for (;;) { 6296 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 6297 if (!BO || !BO->isAdditiveOp()) 6298 break; 6299 6300 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 6301 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 6302 6303 if (isa<IntegerLiteral>(RHS)) 6304 Ex = LHS; 6305 else if (isa<IntegerLiteral>(LHS)) 6306 Ex = RHS; 6307 else 6308 break; 6309 } 6310 6311 return Ex; 6312 } 6313 6314 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 6315 ASTContext &Context) { 6316 // Only handle constant-sized or VLAs, but not flexible members. 6317 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 6318 // Only issue the FIXIT for arrays of size > 1. 6319 if (CAT->getSize().getSExtValue() <= 1) 6320 return false; 6321 } else if (!Ty->isVariableArrayType()) { 6322 return false; 6323 } 6324 return true; 6325 } 6326 6327 // Warn if the user has made the 'size' argument to strlcpy or strlcat 6328 // be the size of the source, instead of the destination. 6329 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 6330 IdentifierInfo *FnName) { 6331 6332 // Don't crash if the user has the wrong number of arguments 6333 unsigned NumArgs = Call->getNumArgs(); 6334 if ((NumArgs != 3) && (NumArgs != 4)) 6335 return; 6336 6337 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 6338 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 6339 const Expr *CompareWithSrc = nullptr; 6340 6341 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 6342 Call->getLocStart(), Call->getRParenLoc())) 6343 return; 6344 6345 // Look for 'strlcpy(dst, x, sizeof(x))' 6346 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 6347 CompareWithSrc = Ex; 6348 else { 6349 // Look for 'strlcpy(dst, x, strlen(x))' 6350 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 6351 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 6352 SizeCall->getNumArgs() == 1) 6353 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 6354 } 6355 } 6356 6357 if (!CompareWithSrc) 6358 return; 6359 6360 // Determine if the argument to sizeof/strlen is equal to the source 6361 // argument. In principle there's all kinds of things you could do 6362 // here, for instance creating an == expression and evaluating it with 6363 // EvaluateAsBooleanCondition, but this uses a more direct technique: 6364 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 6365 if (!SrcArgDRE) 6366 return; 6367 6368 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 6369 if (!CompareWithSrcDRE || 6370 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 6371 return; 6372 6373 const Expr *OriginalSizeArg = Call->getArg(2); 6374 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 6375 << OriginalSizeArg->getSourceRange() << FnName; 6376 6377 // Output a FIXIT hint if the destination is an array (rather than a 6378 // pointer to an array). This could be enhanced to handle some 6379 // pointers if we know the actual size, like if DstArg is 'array+2' 6380 // we could say 'sizeof(array)-2'. 6381 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 6382 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 6383 return; 6384 6385 SmallString<128> sizeString; 6386 llvm::raw_svector_ostream OS(sizeString); 6387 OS << "sizeof("; 6388 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 6389 OS << ")"; 6390 6391 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 6392 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 6393 OS.str()); 6394 } 6395 6396 /// Check if two expressions refer to the same declaration. 6397 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 6398 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 6399 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 6400 return D1->getDecl() == D2->getDecl(); 6401 return false; 6402 } 6403 6404 static const Expr *getStrlenExprArg(const Expr *E) { 6405 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6406 const FunctionDecl *FD = CE->getDirectCallee(); 6407 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 6408 return nullptr; 6409 return CE->getArg(0)->IgnoreParenCasts(); 6410 } 6411 return nullptr; 6412 } 6413 6414 // Warn on anti-patterns as the 'size' argument to strncat. 6415 // The correct size argument should look like following: 6416 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 6417 void Sema::CheckStrncatArguments(const CallExpr *CE, 6418 IdentifierInfo *FnName) { 6419 // Don't crash if the user has the wrong number of arguments. 6420 if (CE->getNumArgs() < 3) 6421 return; 6422 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 6423 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 6424 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 6425 6426 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 6427 CE->getRParenLoc())) 6428 return; 6429 6430 // Identify common expressions, which are wrongly used as the size argument 6431 // to strncat and may lead to buffer overflows. 6432 unsigned PatternType = 0; 6433 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 6434 // - sizeof(dst) 6435 if (referToTheSameDecl(SizeOfArg, DstArg)) 6436 PatternType = 1; 6437 // - sizeof(src) 6438 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 6439 PatternType = 2; 6440 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 6441 if (BE->getOpcode() == BO_Sub) { 6442 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 6443 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 6444 // - sizeof(dst) - strlen(dst) 6445 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 6446 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 6447 PatternType = 1; 6448 // - sizeof(src) - (anything) 6449 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 6450 PatternType = 2; 6451 } 6452 } 6453 6454 if (PatternType == 0) 6455 return; 6456 6457 // Generate the diagnostic. 6458 SourceLocation SL = LenArg->getLocStart(); 6459 SourceRange SR = LenArg->getSourceRange(); 6460 SourceManager &SM = getSourceManager(); 6461 6462 // If the function is defined as a builtin macro, do not show macro expansion. 6463 if (SM.isMacroArgExpansion(SL)) { 6464 SL = SM.getSpellingLoc(SL); 6465 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 6466 SM.getSpellingLoc(SR.getEnd())); 6467 } 6468 6469 // Check if the destination is an array (rather than a pointer to an array). 6470 QualType DstTy = DstArg->getType(); 6471 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 6472 Context); 6473 if (!isKnownSizeArray) { 6474 if (PatternType == 1) 6475 Diag(SL, diag::warn_strncat_wrong_size) << SR; 6476 else 6477 Diag(SL, diag::warn_strncat_src_size) << SR; 6478 return; 6479 } 6480 6481 if (PatternType == 1) 6482 Diag(SL, diag::warn_strncat_large_size) << SR; 6483 else 6484 Diag(SL, diag::warn_strncat_src_size) << SR; 6485 6486 SmallString<128> sizeString; 6487 llvm::raw_svector_ostream OS(sizeString); 6488 OS << "sizeof("; 6489 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 6490 OS << ") - "; 6491 OS << "strlen("; 6492 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 6493 OS << ") - 1"; 6494 6495 Diag(SL, diag::note_strncat_wrong_size) 6496 << FixItHint::CreateReplacement(SR, OS.str()); 6497 } 6498 6499 //===--- CHECK: Return Address of Stack Variable --------------------------===// 6500 6501 static const Expr *EvalVal(const Expr *E, 6502 SmallVectorImpl<const DeclRefExpr *> &refVars, 6503 const Decl *ParentDecl); 6504 static const Expr *EvalAddr(const Expr *E, 6505 SmallVectorImpl<const DeclRefExpr *> &refVars, 6506 const Decl *ParentDecl); 6507 6508 /// CheckReturnStackAddr - Check if a return statement returns the address 6509 /// of a stack variable. 6510 static void 6511 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 6512 SourceLocation ReturnLoc) { 6513 6514 const Expr *stackE = nullptr; 6515 SmallVector<const DeclRefExpr *, 8> refVars; 6516 6517 // Perform checking for returned stack addresses, local blocks, 6518 // label addresses or references to temporaries. 6519 if (lhsType->isPointerType() || 6520 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 6521 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 6522 } else if (lhsType->isReferenceType()) { 6523 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 6524 } 6525 6526 if (!stackE) 6527 return; // Nothing suspicious was found. 6528 6529 SourceLocation diagLoc; 6530 SourceRange diagRange; 6531 if (refVars.empty()) { 6532 diagLoc = stackE->getLocStart(); 6533 diagRange = stackE->getSourceRange(); 6534 } else { 6535 // We followed through a reference variable. 'stackE' contains the 6536 // problematic expression but we will warn at the return statement pointing 6537 // at the reference variable. We will later display the "trail" of 6538 // reference variables using notes. 6539 diagLoc = refVars[0]->getLocStart(); 6540 diagRange = refVars[0]->getSourceRange(); 6541 } 6542 6543 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 6544 // address of local var 6545 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 6546 << DR->getDecl()->getDeclName() << diagRange; 6547 } else if (isa<BlockExpr>(stackE)) { // local block. 6548 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 6549 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 6550 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 6551 } else { // local temporary. 6552 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 6553 << lhsType->isReferenceType() << diagRange; 6554 } 6555 6556 // Display the "trail" of reference variables that we followed until we 6557 // found the problematic expression using notes. 6558 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 6559 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 6560 // If this var binds to another reference var, show the range of the next 6561 // var, otherwise the var binds to the problematic expression, in which case 6562 // show the range of the expression. 6563 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 6564 : stackE->getSourceRange(); 6565 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 6566 << VD->getDeclName() << range; 6567 } 6568 } 6569 6570 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 6571 /// check if the expression in a return statement evaluates to an address 6572 /// to a location on the stack, a local block, an address of a label, or a 6573 /// reference to local temporary. The recursion is used to traverse the 6574 /// AST of the return expression, with recursion backtracking when we 6575 /// encounter a subexpression that (1) clearly does not lead to one of the 6576 /// above problematic expressions (2) is something we cannot determine leads to 6577 /// a problematic expression based on such local checking. 6578 /// 6579 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 6580 /// the expression that they point to. Such variables are added to the 6581 /// 'refVars' vector so that we know what the reference variable "trail" was. 6582 /// 6583 /// EvalAddr processes expressions that are pointers that are used as 6584 /// references (and not L-values). EvalVal handles all other values. 6585 /// At the base case of the recursion is a check for the above problematic 6586 /// expressions. 6587 /// 6588 /// This implementation handles: 6589 /// 6590 /// * pointer-to-pointer casts 6591 /// * implicit conversions from array references to pointers 6592 /// * taking the address of fields 6593 /// * arbitrary interplay between "&" and "*" operators 6594 /// * pointer arithmetic from an address of a stack variable 6595 /// * taking the address of an array element where the array is on the stack 6596 static const Expr *EvalAddr(const Expr *E, 6597 SmallVectorImpl<const DeclRefExpr *> &refVars, 6598 const Decl *ParentDecl) { 6599 if (E->isTypeDependent()) 6600 return nullptr; 6601 6602 // We should only be called for evaluating pointer expressions. 6603 assert((E->getType()->isAnyPointerType() || 6604 E->getType()->isBlockPointerType() || 6605 E->getType()->isObjCQualifiedIdType()) && 6606 "EvalAddr only works on pointers"); 6607 6608 E = E->IgnoreParens(); 6609 6610 // Our "symbolic interpreter" is just a dispatch off the currently 6611 // viewed AST node. We then recursively traverse the AST by calling 6612 // EvalAddr and EvalVal appropriately. 6613 switch (E->getStmtClass()) { 6614 case Stmt::DeclRefExprClass: { 6615 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6616 6617 // If we leave the immediate function, the lifetime isn't about to end. 6618 if (DR->refersToEnclosingVariableOrCapture()) 6619 return nullptr; 6620 6621 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 6622 // If this is a reference variable, follow through to the expression that 6623 // it points to. 6624 if (V->hasLocalStorage() && 6625 V->getType()->isReferenceType() && V->hasInit()) { 6626 // Add the reference variable to the "trail". 6627 refVars.push_back(DR); 6628 return EvalAddr(V->getInit(), refVars, ParentDecl); 6629 } 6630 6631 return nullptr; 6632 } 6633 6634 case Stmt::UnaryOperatorClass: { 6635 // The only unary operator that make sense to handle here 6636 // is AddrOf. All others don't make sense as pointers. 6637 const UnaryOperator *U = cast<UnaryOperator>(E); 6638 6639 if (U->getOpcode() == UO_AddrOf) 6640 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 6641 return nullptr; 6642 } 6643 6644 case Stmt::BinaryOperatorClass: { 6645 // Handle pointer arithmetic. All other binary operators are not valid 6646 // in this context. 6647 const BinaryOperator *B = cast<BinaryOperator>(E); 6648 BinaryOperatorKind op = B->getOpcode(); 6649 6650 if (op != BO_Add && op != BO_Sub) 6651 return nullptr; 6652 6653 const Expr *Base = B->getLHS(); 6654 6655 // Determine which argument is the real pointer base. It could be 6656 // the RHS argument instead of the LHS. 6657 if (!Base->getType()->isPointerType()) 6658 Base = B->getRHS(); 6659 6660 assert(Base->getType()->isPointerType()); 6661 return EvalAddr(Base, refVars, ParentDecl); 6662 } 6663 6664 // For conditional operators we need to see if either the LHS or RHS are 6665 // valid DeclRefExpr*s. If one of them is valid, we return it. 6666 case Stmt::ConditionalOperatorClass: { 6667 const ConditionalOperator *C = cast<ConditionalOperator>(E); 6668 6669 // Handle the GNU extension for missing LHS. 6670 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 6671 if (const Expr *LHSExpr = C->getLHS()) { 6672 // In C++, we can have a throw-expression, which has 'void' type. 6673 if (!LHSExpr->getType()->isVoidType()) 6674 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 6675 return LHS; 6676 } 6677 6678 // In C++, we can have a throw-expression, which has 'void' type. 6679 if (C->getRHS()->getType()->isVoidType()) 6680 return nullptr; 6681 6682 return EvalAddr(C->getRHS(), refVars, ParentDecl); 6683 } 6684 6685 case Stmt::BlockExprClass: 6686 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 6687 return E; // local block. 6688 return nullptr; 6689 6690 case Stmt::AddrLabelExprClass: 6691 return E; // address of label. 6692 6693 case Stmt::ExprWithCleanupsClass: 6694 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 6695 ParentDecl); 6696 6697 // For casts, we need to handle conversions from arrays to 6698 // pointer values, and pointer-to-pointer conversions. 6699 case Stmt::ImplicitCastExprClass: 6700 case Stmt::CStyleCastExprClass: 6701 case Stmt::CXXFunctionalCastExprClass: 6702 case Stmt::ObjCBridgedCastExprClass: 6703 case Stmt::CXXStaticCastExprClass: 6704 case Stmt::CXXDynamicCastExprClass: 6705 case Stmt::CXXConstCastExprClass: 6706 case Stmt::CXXReinterpretCastExprClass: { 6707 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 6708 switch (cast<CastExpr>(E)->getCastKind()) { 6709 case CK_LValueToRValue: 6710 case CK_NoOp: 6711 case CK_BaseToDerived: 6712 case CK_DerivedToBase: 6713 case CK_UncheckedDerivedToBase: 6714 case CK_Dynamic: 6715 case CK_CPointerToObjCPointerCast: 6716 case CK_BlockPointerToObjCPointerCast: 6717 case CK_AnyPointerToBlockPointerCast: 6718 return EvalAddr(SubExpr, refVars, ParentDecl); 6719 6720 case CK_ArrayToPointerDecay: 6721 return EvalVal(SubExpr, refVars, ParentDecl); 6722 6723 case CK_BitCast: 6724 if (SubExpr->getType()->isAnyPointerType() || 6725 SubExpr->getType()->isBlockPointerType() || 6726 SubExpr->getType()->isObjCQualifiedIdType()) 6727 return EvalAddr(SubExpr, refVars, ParentDecl); 6728 else 6729 return nullptr; 6730 6731 default: 6732 return nullptr; 6733 } 6734 } 6735 6736 case Stmt::MaterializeTemporaryExprClass: 6737 if (const Expr *Result = 6738 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 6739 refVars, ParentDecl)) 6740 return Result; 6741 return E; 6742 6743 // Everything else: we simply don't reason about them. 6744 default: 6745 return nullptr; 6746 } 6747 } 6748 6749 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 6750 /// See the comments for EvalAddr for more details. 6751 static const Expr *EvalVal(const Expr *E, 6752 SmallVectorImpl<const DeclRefExpr *> &refVars, 6753 const Decl *ParentDecl) { 6754 do { 6755 // We should only be called for evaluating non-pointer expressions, or 6756 // expressions with a pointer type that are not used as references but 6757 // instead 6758 // are l-values (e.g., DeclRefExpr with a pointer type). 6759 6760 // Our "symbolic interpreter" is just a dispatch off the currently 6761 // viewed AST node. We then recursively traverse the AST by calling 6762 // EvalAddr and EvalVal appropriately. 6763 6764 E = E->IgnoreParens(); 6765 switch (E->getStmtClass()) { 6766 case Stmt::ImplicitCastExprClass: { 6767 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 6768 if (IE->getValueKind() == VK_LValue) { 6769 E = IE->getSubExpr(); 6770 continue; 6771 } 6772 return nullptr; 6773 } 6774 6775 case Stmt::ExprWithCleanupsClass: 6776 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 6777 ParentDecl); 6778 6779 case Stmt::DeclRefExprClass: { 6780 // When we hit a DeclRefExpr we are looking at code that refers to a 6781 // variable's name. If it's not a reference variable we check if it has 6782 // local storage within the function, and if so, return the expression. 6783 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6784 6785 // If we leave the immediate function, the lifetime isn't about to end. 6786 if (DR->refersToEnclosingVariableOrCapture()) 6787 return nullptr; 6788 6789 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 6790 // Check if it refers to itself, e.g. "int& i = i;". 6791 if (V == ParentDecl) 6792 return DR; 6793 6794 if (V->hasLocalStorage()) { 6795 if (!V->getType()->isReferenceType()) 6796 return DR; 6797 6798 // Reference variable, follow through to the expression that 6799 // it points to. 6800 if (V->hasInit()) { 6801 // Add the reference variable to the "trail". 6802 refVars.push_back(DR); 6803 return EvalVal(V->getInit(), refVars, V); 6804 } 6805 } 6806 } 6807 6808 return nullptr; 6809 } 6810 6811 case Stmt::UnaryOperatorClass: { 6812 // The only unary operator that make sense to handle here 6813 // is Deref. All others don't resolve to a "name." This includes 6814 // handling all sorts of rvalues passed to a unary operator. 6815 const UnaryOperator *U = cast<UnaryOperator>(E); 6816 6817 if (U->getOpcode() == UO_Deref) 6818 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 6819 6820 return nullptr; 6821 } 6822 6823 case Stmt::ArraySubscriptExprClass: { 6824 // Array subscripts are potential references to data on the stack. We 6825 // retrieve the DeclRefExpr* for the array variable if it indeed 6826 // has local storage. 6827 const auto *ASE = cast<ArraySubscriptExpr>(E); 6828 if (ASE->isTypeDependent()) 6829 return nullptr; 6830 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 6831 } 6832 6833 case Stmt::OMPArraySectionExprClass: { 6834 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 6835 ParentDecl); 6836 } 6837 6838 case Stmt::ConditionalOperatorClass: { 6839 // For conditional operators we need to see if either the LHS or RHS are 6840 // non-NULL Expr's. If one is non-NULL, we return it. 6841 const ConditionalOperator *C = cast<ConditionalOperator>(E); 6842 6843 // Handle the GNU extension for missing LHS. 6844 if (const Expr *LHSExpr = C->getLHS()) { 6845 // In C++, we can have a throw-expression, which has 'void' type. 6846 if (!LHSExpr->getType()->isVoidType()) 6847 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 6848 return LHS; 6849 } 6850 6851 // In C++, we can have a throw-expression, which has 'void' type. 6852 if (C->getRHS()->getType()->isVoidType()) 6853 return nullptr; 6854 6855 return EvalVal(C->getRHS(), refVars, ParentDecl); 6856 } 6857 6858 // Accesses to members are potential references to data on the stack. 6859 case Stmt::MemberExprClass: { 6860 const MemberExpr *M = cast<MemberExpr>(E); 6861 6862 // Check for indirect access. We only want direct field accesses. 6863 if (M->isArrow()) 6864 return nullptr; 6865 6866 // Check whether the member type is itself a reference, in which case 6867 // we're not going to refer to the member, but to what the member refers 6868 // to. 6869 if (M->getMemberDecl()->getType()->isReferenceType()) 6870 return nullptr; 6871 6872 return EvalVal(M->getBase(), refVars, ParentDecl); 6873 } 6874 6875 case Stmt::MaterializeTemporaryExprClass: 6876 if (const Expr *Result = 6877 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 6878 refVars, ParentDecl)) 6879 return Result; 6880 return E; 6881 6882 default: 6883 // Check that we don't return or take the address of a reference to a 6884 // temporary. This is only useful in C++. 6885 if (!E->isTypeDependent() && E->isRValue()) 6886 return E; 6887 6888 // Everything else: we simply don't reason about them. 6889 return nullptr; 6890 } 6891 } while (true); 6892 } 6893 6894 void 6895 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 6896 SourceLocation ReturnLoc, 6897 bool isObjCMethod, 6898 const AttrVec *Attrs, 6899 const FunctionDecl *FD) { 6900 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 6901 6902 // Check if the return value is null but should not be. 6903 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 6904 (!isObjCMethod && isNonNullType(Context, lhsType))) && 6905 CheckNonNullExpr(*this, RetValExp)) 6906 Diag(ReturnLoc, diag::warn_null_ret) 6907 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 6908 6909 // C++11 [basic.stc.dynamic.allocation]p4: 6910 // If an allocation function declared with a non-throwing 6911 // exception-specification fails to allocate storage, it shall return 6912 // a null pointer. Any other allocation function that fails to allocate 6913 // storage shall indicate failure only by throwing an exception [...] 6914 if (FD) { 6915 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 6916 if (Op == OO_New || Op == OO_Array_New) { 6917 const FunctionProtoType *Proto 6918 = FD->getType()->castAs<FunctionProtoType>(); 6919 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 6920 CheckNonNullExpr(*this, RetValExp)) 6921 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 6922 << FD << getLangOpts().CPlusPlus11; 6923 } 6924 } 6925 } 6926 6927 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 6928 6929 /// Check for comparisons of floating point operands using != and ==. 6930 /// Issue a warning if these are no self-comparisons, as they are not likely 6931 /// to do what the programmer intended. 6932 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 6933 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 6934 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 6935 6936 // Special case: check for x == x (which is OK). 6937 // Do not emit warnings for such cases. 6938 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 6939 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 6940 if (DRL->getDecl() == DRR->getDecl()) 6941 return; 6942 6943 // Special case: check for comparisons against literals that can be exactly 6944 // represented by APFloat. In such cases, do not emit a warning. This 6945 // is a heuristic: often comparison against such literals are used to 6946 // detect if a value in a variable has not changed. This clearly can 6947 // lead to false negatives. 6948 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 6949 if (FLL->isExact()) 6950 return; 6951 } else 6952 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 6953 if (FLR->isExact()) 6954 return; 6955 6956 // Check for comparisons with builtin types. 6957 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 6958 if (CL->getBuiltinCallee()) 6959 return; 6960 6961 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 6962 if (CR->getBuiltinCallee()) 6963 return; 6964 6965 // Emit the diagnostic. 6966 Diag(Loc, diag::warn_floatingpoint_eq) 6967 << LHS->getSourceRange() << RHS->getSourceRange(); 6968 } 6969 6970 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 6971 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 6972 6973 namespace { 6974 6975 /// Structure recording the 'active' range of an integer-valued 6976 /// expression. 6977 struct IntRange { 6978 /// The number of bits active in the int. 6979 unsigned Width; 6980 6981 /// True if the int is known not to have negative values. 6982 bool NonNegative; 6983 6984 IntRange(unsigned Width, bool NonNegative) 6985 : Width(Width), NonNegative(NonNegative) 6986 {} 6987 6988 /// Returns the range of the bool type. 6989 static IntRange forBoolType() { 6990 return IntRange(1, true); 6991 } 6992 6993 /// Returns the range of an opaque value of the given integral type. 6994 static IntRange forValueOfType(ASTContext &C, QualType T) { 6995 return forValueOfCanonicalType(C, 6996 T->getCanonicalTypeInternal().getTypePtr()); 6997 } 6998 6999 /// Returns the range of an opaque value of a canonical integral type. 7000 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 7001 assert(T->isCanonicalUnqualified()); 7002 7003 if (const VectorType *VT = dyn_cast<VectorType>(T)) 7004 T = VT->getElementType().getTypePtr(); 7005 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 7006 T = CT->getElementType().getTypePtr(); 7007 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 7008 T = AT->getValueType().getTypePtr(); 7009 7010 // For enum types, use the known bit width of the enumerators. 7011 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 7012 EnumDecl *Enum = ET->getDecl(); 7013 if (!Enum->isCompleteDefinition()) 7014 return IntRange(C.getIntWidth(QualType(T, 0)), false); 7015 7016 unsigned NumPositive = Enum->getNumPositiveBits(); 7017 unsigned NumNegative = Enum->getNumNegativeBits(); 7018 7019 if (NumNegative == 0) 7020 return IntRange(NumPositive, true/*NonNegative*/); 7021 else 7022 return IntRange(std::max(NumPositive + 1, NumNegative), 7023 false/*NonNegative*/); 7024 } 7025 7026 const BuiltinType *BT = cast<BuiltinType>(T); 7027 assert(BT->isInteger()); 7028 7029 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 7030 } 7031 7032 /// Returns the "target" range of a canonical integral type, i.e. 7033 /// the range of values expressible in the type. 7034 /// 7035 /// This matches forValueOfCanonicalType except that enums have the 7036 /// full range of their type, not the range of their enumerators. 7037 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 7038 assert(T->isCanonicalUnqualified()); 7039 7040 if (const VectorType *VT = dyn_cast<VectorType>(T)) 7041 T = VT->getElementType().getTypePtr(); 7042 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 7043 T = CT->getElementType().getTypePtr(); 7044 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 7045 T = AT->getValueType().getTypePtr(); 7046 if (const EnumType *ET = dyn_cast<EnumType>(T)) 7047 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 7048 7049 const BuiltinType *BT = cast<BuiltinType>(T); 7050 assert(BT->isInteger()); 7051 7052 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 7053 } 7054 7055 /// Returns the supremum of two ranges: i.e. their conservative merge. 7056 static IntRange join(IntRange L, IntRange R) { 7057 return IntRange(std::max(L.Width, R.Width), 7058 L.NonNegative && R.NonNegative); 7059 } 7060 7061 /// Returns the infinum of two ranges: i.e. their aggressive merge. 7062 static IntRange meet(IntRange L, IntRange R) { 7063 return IntRange(std::min(L.Width, R.Width), 7064 L.NonNegative || R.NonNegative); 7065 } 7066 }; 7067 7068 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 7069 if (value.isSigned() && value.isNegative()) 7070 return IntRange(value.getMinSignedBits(), false); 7071 7072 if (value.getBitWidth() > MaxWidth) 7073 value = value.trunc(MaxWidth); 7074 7075 // isNonNegative() just checks the sign bit without considering 7076 // signedness. 7077 return IntRange(value.getActiveBits(), true); 7078 } 7079 7080 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 7081 unsigned MaxWidth) { 7082 if (result.isInt()) 7083 return GetValueRange(C, result.getInt(), MaxWidth); 7084 7085 if (result.isVector()) { 7086 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 7087 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 7088 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 7089 R = IntRange::join(R, El); 7090 } 7091 return R; 7092 } 7093 7094 if (result.isComplexInt()) { 7095 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 7096 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 7097 return IntRange::join(R, I); 7098 } 7099 7100 // This can happen with lossless casts to intptr_t of "based" lvalues. 7101 // Assume it might use arbitrary bits. 7102 // FIXME: The only reason we need to pass the type in here is to get 7103 // the sign right on this one case. It would be nice if APValue 7104 // preserved this. 7105 assert(result.isLValue() || result.isAddrLabelDiff()); 7106 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 7107 } 7108 7109 QualType GetExprType(const Expr *E) { 7110 QualType Ty = E->getType(); 7111 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 7112 Ty = AtomicRHS->getValueType(); 7113 return Ty; 7114 } 7115 7116 /// Pseudo-evaluate the given integer expression, estimating the 7117 /// range of values it might take. 7118 /// 7119 /// \param MaxWidth - the width to which the value will be truncated 7120 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 7121 E = E->IgnoreParens(); 7122 7123 // Try a full evaluation first. 7124 Expr::EvalResult result; 7125 if (E->EvaluateAsRValue(result, C)) 7126 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 7127 7128 // I think we only want to look through implicit casts here; if the 7129 // user has an explicit widening cast, we should treat the value as 7130 // being of the new, wider type. 7131 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 7132 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 7133 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 7134 7135 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 7136 7137 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 7138 CE->getCastKind() == CK_BooleanToSignedIntegral; 7139 7140 // Assume that non-integer casts can span the full range of the type. 7141 if (!isIntegerCast) 7142 return OutputTypeRange; 7143 7144 IntRange SubRange 7145 = GetExprRange(C, CE->getSubExpr(), 7146 std::min(MaxWidth, OutputTypeRange.Width)); 7147 7148 // Bail out if the subexpr's range is as wide as the cast type. 7149 if (SubRange.Width >= OutputTypeRange.Width) 7150 return OutputTypeRange; 7151 7152 // Otherwise, we take the smaller width, and we're non-negative if 7153 // either the output type or the subexpr is. 7154 return IntRange(SubRange.Width, 7155 SubRange.NonNegative || OutputTypeRange.NonNegative); 7156 } 7157 7158 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 7159 // If we can fold the condition, just take that operand. 7160 bool CondResult; 7161 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 7162 return GetExprRange(C, CondResult ? CO->getTrueExpr() 7163 : CO->getFalseExpr(), 7164 MaxWidth); 7165 7166 // Otherwise, conservatively merge. 7167 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 7168 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 7169 return IntRange::join(L, R); 7170 } 7171 7172 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 7173 switch (BO->getOpcode()) { 7174 7175 // Boolean-valued operations are single-bit and positive. 7176 case BO_LAnd: 7177 case BO_LOr: 7178 case BO_LT: 7179 case BO_GT: 7180 case BO_LE: 7181 case BO_GE: 7182 case BO_EQ: 7183 case BO_NE: 7184 return IntRange::forBoolType(); 7185 7186 // The type of the assignments is the type of the LHS, so the RHS 7187 // is not necessarily the same type. 7188 case BO_MulAssign: 7189 case BO_DivAssign: 7190 case BO_RemAssign: 7191 case BO_AddAssign: 7192 case BO_SubAssign: 7193 case BO_XorAssign: 7194 case BO_OrAssign: 7195 // TODO: bitfields? 7196 return IntRange::forValueOfType(C, GetExprType(E)); 7197 7198 // Simple assignments just pass through the RHS, which will have 7199 // been coerced to the LHS type. 7200 case BO_Assign: 7201 // TODO: bitfields? 7202 return GetExprRange(C, BO->getRHS(), MaxWidth); 7203 7204 // Operations with opaque sources are black-listed. 7205 case BO_PtrMemD: 7206 case BO_PtrMemI: 7207 return IntRange::forValueOfType(C, GetExprType(E)); 7208 7209 // Bitwise-and uses the *infinum* of the two source ranges. 7210 case BO_And: 7211 case BO_AndAssign: 7212 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 7213 GetExprRange(C, BO->getRHS(), MaxWidth)); 7214 7215 // Left shift gets black-listed based on a judgement call. 7216 case BO_Shl: 7217 // ...except that we want to treat '1 << (blah)' as logically 7218 // positive. It's an important idiom. 7219 if (IntegerLiteral *I 7220 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 7221 if (I->getValue() == 1) { 7222 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 7223 return IntRange(R.Width, /*NonNegative*/ true); 7224 } 7225 } 7226 // fallthrough 7227 7228 case BO_ShlAssign: 7229 return IntRange::forValueOfType(C, GetExprType(E)); 7230 7231 // Right shift by a constant can narrow its left argument. 7232 case BO_Shr: 7233 case BO_ShrAssign: { 7234 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 7235 7236 // If the shift amount is a positive constant, drop the width by 7237 // that much. 7238 llvm::APSInt shift; 7239 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 7240 shift.isNonNegative()) { 7241 unsigned zext = shift.getZExtValue(); 7242 if (zext >= L.Width) 7243 L.Width = (L.NonNegative ? 0 : 1); 7244 else 7245 L.Width -= zext; 7246 } 7247 7248 return L; 7249 } 7250 7251 // Comma acts as its right operand. 7252 case BO_Comma: 7253 return GetExprRange(C, BO->getRHS(), MaxWidth); 7254 7255 // Black-list pointer subtractions. 7256 case BO_Sub: 7257 if (BO->getLHS()->getType()->isPointerType()) 7258 return IntRange::forValueOfType(C, GetExprType(E)); 7259 break; 7260 7261 // The width of a division result is mostly determined by the size 7262 // of the LHS. 7263 case BO_Div: { 7264 // Don't 'pre-truncate' the operands. 7265 unsigned opWidth = C.getIntWidth(GetExprType(E)); 7266 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 7267 7268 // If the divisor is constant, use that. 7269 llvm::APSInt divisor; 7270 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 7271 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 7272 if (log2 >= L.Width) 7273 L.Width = (L.NonNegative ? 0 : 1); 7274 else 7275 L.Width = std::min(L.Width - log2, MaxWidth); 7276 return L; 7277 } 7278 7279 // Otherwise, just use the LHS's width. 7280 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 7281 return IntRange(L.Width, L.NonNegative && R.NonNegative); 7282 } 7283 7284 // The result of a remainder can't be larger than the result of 7285 // either side. 7286 case BO_Rem: { 7287 // Don't 'pre-truncate' the operands. 7288 unsigned opWidth = C.getIntWidth(GetExprType(E)); 7289 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 7290 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 7291 7292 IntRange meet = IntRange::meet(L, R); 7293 meet.Width = std::min(meet.Width, MaxWidth); 7294 return meet; 7295 } 7296 7297 // The default behavior is okay for these. 7298 case BO_Mul: 7299 case BO_Add: 7300 case BO_Xor: 7301 case BO_Or: 7302 break; 7303 } 7304 7305 // The default case is to treat the operation as if it were closed 7306 // on the narrowest type that encompasses both operands. 7307 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 7308 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 7309 return IntRange::join(L, R); 7310 } 7311 7312 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 7313 switch (UO->getOpcode()) { 7314 // Boolean-valued operations are white-listed. 7315 case UO_LNot: 7316 return IntRange::forBoolType(); 7317 7318 // Operations with opaque sources are black-listed. 7319 case UO_Deref: 7320 case UO_AddrOf: // should be impossible 7321 return IntRange::forValueOfType(C, GetExprType(E)); 7322 7323 default: 7324 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 7325 } 7326 } 7327 7328 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 7329 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 7330 7331 if (const auto *BitField = E->getSourceBitField()) 7332 return IntRange(BitField->getBitWidthValue(C), 7333 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 7334 7335 return IntRange::forValueOfType(C, GetExprType(E)); 7336 } 7337 7338 IntRange GetExprRange(ASTContext &C, const Expr *E) { 7339 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 7340 } 7341 7342 /// Checks whether the given value, which currently has the given 7343 /// source semantics, has the same value when coerced through the 7344 /// target semantics. 7345 bool IsSameFloatAfterCast(const llvm::APFloat &value, 7346 const llvm::fltSemantics &Src, 7347 const llvm::fltSemantics &Tgt) { 7348 llvm::APFloat truncated = value; 7349 7350 bool ignored; 7351 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 7352 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 7353 7354 return truncated.bitwiseIsEqual(value); 7355 } 7356 7357 /// Checks whether the given value, which currently has the given 7358 /// source semantics, has the same value when coerced through the 7359 /// target semantics. 7360 /// 7361 /// The value might be a vector of floats (or a complex number). 7362 bool IsSameFloatAfterCast(const APValue &value, 7363 const llvm::fltSemantics &Src, 7364 const llvm::fltSemantics &Tgt) { 7365 if (value.isFloat()) 7366 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 7367 7368 if (value.isVector()) { 7369 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 7370 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 7371 return false; 7372 return true; 7373 } 7374 7375 assert(value.isComplexFloat()); 7376 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 7377 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 7378 } 7379 7380 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 7381 7382 bool IsZero(Sema &S, Expr *E) { 7383 // Suppress cases where we are comparing against an enum constant. 7384 if (const DeclRefExpr *DR = 7385 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 7386 if (isa<EnumConstantDecl>(DR->getDecl())) 7387 return false; 7388 7389 // Suppress cases where the '0' value is expanded from a macro. 7390 if (E->getLocStart().isMacroID()) 7391 return false; 7392 7393 llvm::APSInt Value; 7394 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 7395 } 7396 7397 bool HasEnumType(Expr *E) { 7398 // Strip off implicit integral promotions. 7399 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7400 if (ICE->getCastKind() != CK_IntegralCast && 7401 ICE->getCastKind() != CK_NoOp) 7402 break; 7403 E = ICE->getSubExpr(); 7404 } 7405 7406 return E->getType()->isEnumeralType(); 7407 } 7408 7409 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 7410 // Disable warning in template instantiations. 7411 if (!S.ActiveTemplateInstantiations.empty()) 7412 return; 7413 7414 BinaryOperatorKind op = E->getOpcode(); 7415 if (E->isValueDependent()) 7416 return; 7417 7418 if (op == BO_LT && IsZero(S, E->getRHS())) { 7419 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 7420 << "< 0" << "false" << HasEnumType(E->getLHS()) 7421 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 7422 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 7423 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 7424 << ">= 0" << "true" << HasEnumType(E->getLHS()) 7425 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 7426 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 7427 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 7428 << "0 >" << "false" << HasEnumType(E->getRHS()) 7429 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 7430 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 7431 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 7432 << "0 <=" << "true" << HasEnumType(E->getRHS()) 7433 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 7434 } 7435 } 7436 7437 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant, 7438 Expr *Other, const llvm::APSInt &Value, 7439 bool RhsConstant) { 7440 // Disable warning in template instantiations. 7441 if (!S.ActiveTemplateInstantiations.empty()) 7442 return; 7443 7444 // TODO: Investigate using GetExprRange() to get tighter bounds 7445 // on the bit ranges. 7446 QualType OtherT = Other->getType(); 7447 if (const auto *AT = OtherT->getAs<AtomicType>()) 7448 OtherT = AT->getValueType(); 7449 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 7450 unsigned OtherWidth = OtherRange.Width; 7451 7452 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 7453 7454 // 0 values are handled later by CheckTrivialUnsignedComparison(). 7455 if ((Value == 0) && (!OtherIsBooleanType)) 7456 return; 7457 7458 BinaryOperatorKind op = E->getOpcode(); 7459 bool IsTrue = true; 7460 7461 // Used for diagnostic printout. 7462 enum { 7463 LiteralConstant = 0, 7464 CXXBoolLiteralTrue, 7465 CXXBoolLiteralFalse 7466 } LiteralOrBoolConstant = LiteralConstant; 7467 7468 if (!OtherIsBooleanType) { 7469 QualType ConstantT = Constant->getType(); 7470 QualType CommonT = E->getLHS()->getType(); 7471 7472 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 7473 return; 7474 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 7475 "comparison with non-integer type"); 7476 7477 bool ConstantSigned = ConstantT->isSignedIntegerType(); 7478 bool CommonSigned = CommonT->isSignedIntegerType(); 7479 7480 bool EqualityOnly = false; 7481 7482 if (CommonSigned) { 7483 // The common type is signed, therefore no signed to unsigned conversion. 7484 if (!OtherRange.NonNegative) { 7485 // Check that the constant is representable in type OtherT. 7486 if (ConstantSigned) { 7487 if (OtherWidth >= Value.getMinSignedBits()) 7488 return; 7489 } else { // !ConstantSigned 7490 if (OtherWidth >= Value.getActiveBits() + 1) 7491 return; 7492 } 7493 } else { // !OtherSigned 7494 // Check that the constant is representable in type OtherT. 7495 // Negative values are out of range. 7496 if (ConstantSigned) { 7497 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 7498 return; 7499 } else { // !ConstantSigned 7500 if (OtherWidth >= Value.getActiveBits()) 7501 return; 7502 } 7503 } 7504 } else { // !CommonSigned 7505 if (OtherRange.NonNegative) { 7506 if (OtherWidth >= Value.getActiveBits()) 7507 return; 7508 } else { // OtherSigned 7509 assert(!ConstantSigned && 7510 "Two signed types converted to unsigned types."); 7511 // Check to see if the constant is representable in OtherT. 7512 if (OtherWidth > Value.getActiveBits()) 7513 return; 7514 // Check to see if the constant is equivalent to a negative value 7515 // cast to CommonT. 7516 if (S.Context.getIntWidth(ConstantT) == 7517 S.Context.getIntWidth(CommonT) && 7518 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 7519 return; 7520 // The constant value rests between values that OtherT can represent 7521 // after conversion. Relational comparison still works, but equality 7522 // comparisons will be tautological. 7523 EqualityOnly = true; 7524 } 7525 } 7526 7527 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 7528 7529 if (op == BO_EQ || op == BO_NE) { 7530 IsTrue = op == BO_NE; 7531 } else if (EqualityOnly) { 7532 return; 7533 } else if (RhsConstant) { 7534 if (op == BO_GT || op == BO_GE) 7535 IsTrue = !PositiveConstant; 7536 else // op == BO_LT || op == BO_LE 7537 IsTrue = PositiveConstant; 7538 } else { 7539 if (op == BO_LT || op == BO_LE) 7540 IsTrue = !PositiveConstant; 7541 else // op == BO_GT || op == BO_GE 7542 IsTrue = PositiveConstant; 7543 } 7544 } else { 7545 // Other isKnownToHaveBooleanValue 7546 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 7547 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 7548 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 7549 7550 static const struct LinkedConditions { 7551 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 7552 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 7553 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 7554 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 7555 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 7556 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 7557 7558 } TruthTable = { 7559 // Constant on LHS. | Constant on RHS. | 7560 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 7561 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 7562 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 7563 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 7564 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 7565 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 7566 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 7567 }; 7568 7569 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 7570 7571 enum ConstantValue ConstVal = Zero; 7572 if (Value.isUnsigned() || Value.isNonNegative()) { 7573 if (Value == 0) { 7574 LiteralOrBoolConstant = 7575 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 7576 ConstVal = Zero; 7577 } else if (Value == 1) { 7578 LiteralOrBoolConstant = 7579 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 7580 ConstVal = One; 7581 } else { 7582 LiteralOrBoolConstant = LiteralConstant; 7583 ConstVal = GT_One; 7584 } 7585 } else { 7586 ConstVal = LT_Zero; 7587 } 7588 7589 CompareBoolWithConstantResult CmpRes; 7590 7591 switch (op) { 7592 case BO_LT: 7593 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 7594 break; 7595 case BO_GT: 7596 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 7597 break; 7598 case BO_LE: 7599 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 7600 break; 7601 case BO_GE: 7602 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 7603 break; 7604 case BO_EQ: 7605 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 7606 break; 7607 case BO_NE: 7608 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 7609 break; 7610 default: 7611 CmpRes = Unkwn; 7612 break; 7613 } 7614 7615 if (CmpRes == AFals) { 7616 IsTrue = false; 7617 } else if (CmpRes == ATrue) { 7618 IsTrue = true; 7619 } else { 7620 return; 7621 } 7622 } 7623 7624 // If this is a comparison to an enum constant, include that 7625 // constant in the diagnostic. 7626 const EnumConstantDecl *ED = nullptr; 7627 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 7628 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 7629 7630 SmallString<64> PrettySourceValue; 7631 llvm::raw_svector_ostream OS(PrettySourceValue); 7632 if (ED) 7633 OS << '\'' << *ED << "' (" << Value << ")"; 7634 else 7635 OS << Value; 7636 7637 S.DiagRuntimeBehavior( 7638 E->getOperatorLoc(), E, 7639 S.PDiag(diag::warn_out_of_range_compare) 7640 << OS.str() << LiteralOrBoolConstant 7641 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 7642 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 7643 } 7644 7645 /// Analyze the operands of the given comparison. Implements the 7646 /// fallback case from AnalyzeComparison. 7647 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 7648 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 7649 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 7650 } 7651 7652 /// \brief Implements -Wsign-compare. 7653 /// 7654 /// \param E the binary operator to check for warnings 7655 void AnalyzeComparison(Sema &S, BinaryOperator *E) { 7656 // The type the comparison is being performed in. 7657 QualType T = E->getLHS()->getType(); 7658 7659 // Only analyze comparison operators where both sides have been converted to 7660 // the same type. 7661 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 7662 return AnalyzeImpConvsInComparison(S, E); 7663 7664 // Don't analyze value-dependent comparisons directly. 7665 if (E->isValueDependent()) 7666 return AnalyzeImpConvsInComparison(S, E); 7667 7668 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 7669 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 7670 7671 bool IsComparisonConstant = false; 7672 7673 // Check whether an integer constant comparison results in a value 7674 // of 'true' or 'false'. 7675 if (T->isIntegralType(S.Context)) { 7676 llvm::APSInt RHSValue; 7677 bool IsRHSIntegralLiteral = 7678 RHS->isIntegerConstantExpr(RHSValue, S.Context); 7679 llvm::APSInt LHSValue; 7680 bool IsLHSIntegralLiteral = 7681 LHS->isIntegerConstantExpr(LHSValue, S.Context); 7682 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 7683 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 7684 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 7685 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 7686 else 7687 IsComparisonConstant = 7688 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 7689 } else if (!T->hasUnsignedIntegerRepresentation()) 7690 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 7691 7692 // We don't do anything special if this isn't an unsigned integral 7693 // comparison: we're only interested in integral comparisons, and 7694 // signed comparisons only happen in cases we don't care to warn about. 7695 // 7696 // We also don't care about value-dependent expressions or expressions 7697 // whose result is a constant. 7698 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 7699 return AnalyzeImpConvsInComparison(S, E); 7700 7701 // Check to see if one of the (unmodified) operands is of different 7702 // signedness. 7703 Expr *signedOperand, *unsignedOperand; 7704 if (LHS->getType()->hasSignedIntegerRepresentation()) { 7705 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 7706 "unsigned comparison between two signed integer expressions?"); 7707 signedOperand = LHS; 7708 unsignedOperand = RHS; 7709 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 7710 signedOperand = RHS; 7711 unsignedOperand = LHS; 7712 } else { 7713 CheckTrivialUnsignedComparison(S, E); 7714 return AnalyzeImpConvsInComparison(S, E); 7715 } 7716 7717 // Otherwise, calculate the effective range of the signed operand. 7718 IntRange signedRange = GetExprRange(S.Context, signedOperand); 7719 7720 // Go ahead and analyze implicit conversions in the operands. Note 7721 // that we skip the implicit conversions on both sides. 7722 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 7723 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 7724 7725 // If the signed range is non-negative, -Wsign-compare won't fire, 7726 // but we should still check for comparisons which are always true 7727 // or false. 7728 if (signedRange.NonNegative) 7729 return CheckTrivialUnsignedComparison(S, E); 7730 7731 // For (in)equality comparisons, if the unsigned operand is a 7732 // constant which cannot collide with a overflowed signed operand, 7733 // then reinterpreting the signed operand as unsigned will not 7734 // change the result of the comparison. 7735 if (E->isEqualityOp()) { 7736 unsigned comparisonWidth = S.Context.getIntWidth(T); 7737 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 7738 7739 // We should never be unable to prove that the unsigned operand is 7740 // non-negative. 7741 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 7742 7743 if (unsignedRange.Width < comparisonWidth) 7744 return; 7745 } 7746 7747 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 7748 S.PDiag(diag::warn_mixed_sign_comparison) 7749 << LHS->getType() << RHS->getType() 7750 << LHS->getSourceRange() << RHS->getSourceRange()); 7751 } 7752 7753 /// Analyzes an attempt to assign the given value to a bitfield. 7754 /// 7755 /// Returns true if there was something fishy about the attempt. 7756 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 7757 SourceLocation InitLoc) { 7758 assert(Bitfield->isBitField()); 7759 if (Bitfield->isInvalidDecl()) 7760 return false; 7761 7762 // White-list bool bitfields. 7763 if (Bitfield->getType()->isBooleanType()) 7764 return false; 7765 7766 // Ignore value- or type-dependent expressions. 7767 if (Bitfield->getBitWidth()->isValueDependent() || 7768 Bitfield->getBitWidth()->isTypeDependent() || 7769 Init->isValueDependent() || 7770 Init->isTypeDependent()) 7771 return false; 7772 7773 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 7774 7775 llvm::APSInt Value; 7776 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 7777 return false; 7778 7779 unsigned OriginalWidth = Value.getBitWidth(); 7780 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 7781 7782 if (OriginalWidth <= FieldWidth) 7783 return false; 7784 7785 // Compute the value which the bitfield will contain. 7786 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 7787 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType()); 7788 7789 // Check whether the stored value is equal to the original value. 7790 TruncatedValue = TruncatedValue.extend(OriginalWidth); 7791 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 7792 return false; 7793 7794 // Special-case bitfields of width 1: booleans are naturally 0/1, and 7795 // therefore don't strictly fit into a signed bitfield of width 1. 7796 if (FieldWidth == 1 && Value == 1) 7797 return false; 7798 7799 std::string PrettyValue = Value.toString(10); 7800 std::string PrettyTrunc = TruncatedValue.toString(10); 7801 7802 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 7803 << PrettyValue << PrettyTrunc << OriginalInit->getType() 7804 << Init->getSourceRange(); 7805 7806 return true; 7807 } 7808 7809 /// Analyze the given simple or compound assignment for warning-worthy 7810 /// operations. 7811 void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 7812 // Just recurse on the LHS. 7813 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 7814 7815 // We want to recurse on the RHS as normal unless we're assigning to 7816 // a bitfield. 7817 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 7818 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 7819 E->getOperatorLoc())) { 7820 // Recurse, ignoring any implicit conversions on the RHS. 7821 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 7822 E->getOperatorLoc()); 7823 } 7824 } 7825 7826 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 7827 } 7828 7829 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 7830 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 7831 SourceLocation CContext, unsigned diag, 7832 bool pruneControlFlow = false) { 7833 if (pruneControlFlow) { 7834 S.DiagRuntimeBehavior(E->getExprLoc(), E, 7835 S.PDiag(diag) 7836 << SourceType << T << E->getSourceRange() 7837 << SourceRange(CContext)); 7838 return; 7839 } 7840 S.Diag(E->getExprLoc(), diag) 7841 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 7842 } 7843 7844 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 7845 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 7846 unsigned diag, bool pruneControlFlow = false) { 7847 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 7848 } 7849 7850 7851 /// Diagnose an implicit cast from a floating point value to an integer value. 7852 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 7853 7854 SourceLocation CContext) { 7855 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 7856 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty(); 7857 7858 Expr *InnerE = E->IgnoreParenImpCasts(); 7859 // We also want to warn on, e.g., "int i = -1.234" 7860 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 7861 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 7862 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 7863 7864 const bool IsLiteral = 7865 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 7866 7867 llvm::APFloat Value(0.0); 7868 bool IsConstant = 7869 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 7870 if (!IsConstant) { 7871 return DiagnoseImpCast(S, E, T, CContext, 7872 diag::warn_impcast_float_integer, PruneWarnings); 7873 } 7874 7875 bool isExact = false; 7876 7877 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 7878 T->hasUnsignedIntegerRepresentation()); 7879 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 7880 &isExact) == llvm::APFloat::opOK && 7881 isExact) { 7882 if (IsLiteral) return; 7883 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 7884 PruneWarnings); 7885 } 7886 7887 unsigned DiagID = 0; 7888 if (IsLiteral) { 7889 // Warn on floating point literal to integer. 7890 DiagID = diag::warn_impcast_literal_float_to_integer; 7891 } else if (IntegerValue == 0) { 7892 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 7893 return DiagnoseImpCast(S, E, T, CContext, 7894 diag::warn_impcast_float_integer, PruneWarnings); 7895 } 7896 // Warn on non-zero to zero conversion. 7897 DiagID = diag::warn_impcast_float_to_integer_zero; 7898 } else { 7899 if (IntegerValue.isUnsigned()) { 7900 if (!IntegerValue.isMaxValue()) { 7901 return DiagnoseImpCast(S, E, T, CContext, 7902 diag::warn_impcast_float_integer, PruneWarnings); 7903 } 7904 } else { // IntegerValue.isSigned() 7905 if (!IntegerValue.isMaxSignedValue() && 7906 !IntegerValue.isMinSignedValue()) { 7907 return DiagnoseImpCast(S, E, T, CContext, 7908 diag::warn_impcast_float_integer, PruneWarnings); 7909 } 7910 } 7911 // Warn on evaluatable floating point expression to integer conversion. 7912 DiagID = diag::warn_impcast_float_to_integer; 7913 } 7914 7915 // FIXME: Force the precision of the source value down so we don't print 7916 // digits which are usually useless (we don't really care here if we 7917 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 7918 // would automatically print the shortest representation, but it's a bit 7919 // tricky to implement. 7920 SmallString<16> PrettySourceValue; 7921 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 7922 precision = (precision * 59 + 195) / 196; 7923 Value.toString(PrettySourceValue, precision); 7924 7925 SmallString<16> PrettyTargetValue; 7926 if (IsBool) 7927 PrettyTargetValue = Value.isZero() ? "false" : "true"; 7928 else 7929 IntegerValue.toString(PrettyTargetValue); 7930 7931 if (PruneWarnings) { 7932 S.DiagRuntimeBehavior(E->getExprLoc(), E, 7933 S.PDiag(DiagID) 7934 << E->getType() << T.getUnqualifiedType() 7935 << PrettySourceValue << PrettyTargetValue 7936 << E->getSourceRange() << SourceRange(CContext)); 7937 } else { 7938 S.Diag(E->getExprLoc(), DiagID) 7939 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 7940 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 7941 } 7942 } 7943 7944 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 7945 if (!Range.Width) return "0"; 7946 7947 llvm::APSInt ValueInRange = Value; 7948 ValueInRange.setIsSigned(!Range.NonNegative); 7949 ValueInRange = ValueInRange.trunc(Range.Width); 7950 return ValueInRange.toString(10); 7951 } 7952 7953 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 7954 if (!isa<ImplicitCastExpr>(Ex)) 7955 return false; 7956 7957 Expr *InnerE = Ex->IgnoreParenImpCasts(); 7958 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 7959 const Type *Source = 7960 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 7961 if (Target->isDependentType()) 7962 return false; 7963 7964 const BuiltinType *FloatCandidateBT = 7965 dyn_cast<BuiltinType>(ToBool ? Source : Target); 7966 const Type *BoolCandidateType = ToBool ? Target : Source; 7967 7968 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 7969 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 7970 } 7971 7972 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 7973 SourceLocation CC) { 7974 unsigned NumArgs = TheCall->getNumArgs(); 7975 for (unsigned i = 0; i < NumArgs; ++i) { 7976 Expr *CurrA = TheCall->getArg(i); 7977 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 7978 continue; 7979 7980 bool IsSwapped = ((i > 0) && 7981 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 7982 IsSwapped |= ((i < (NumArgs - 1)) && 7983 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 7984 if (IsSwapped) { 7985 // Warn on this floating-point to bool conversion. 7986 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 7987 CurrA->getType(), CC, 7988 diag::warn_impcast_floating_point_to_bool); 7989 } 7990 } 7991 } 7992 7993 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) { 7994 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 7995 E->getExprLoc())) 7996 return; 7997 7998 // Don't warn on functions which have return type nullptr_t. 7999 if (isa<CallExpr>(E)) 8000 return; 8001 8002 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 8003 const Expr::NullPointerConstantKind NullKind = 8004 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 8005 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 8006 return; 8007 8008 // Return if target type is a safe conversion. 8009 if (T->isAnyPointerType() || T->isBlockPointerType() || 8010 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 8011 return; 8012 8013 SourceLocation Loc = E->getSourceRange().getBegin(); 8014 8015 // Venture through the macro stacks to get to the source of macro arguments. 8016 // The new location is a better location than the complete location that was 8017 // passed in. 8018 while (S.SourceMgr.isMacroArgExpansion(Loc)) 8019 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); 8020 8021 while (S.SourceMgr.isMacroArgExpansion(CC)) 8022 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); 8023 8024 // __null is usually wrapped in a macro. Go up a macro if that is the case. 8025 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 8026 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 8027 Loc, S.SourceMgr, S.getLangOpts()); 8028 if (MacroName == "NULL") 8029 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 8030 } 8031 8032 // Only warn if the null and context location are in the same macro expansion. 8033 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 8034 return; 8035 8036 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 8037 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) 8038 << FixItHint::CreateReplacement(Loc, 8039 S.getFixItZeroLiteralForType(T, Loc)); 8040 } 8041 8042 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 8043 ObjCArrayLiteral *ArrayLiteral); 8044 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 8045 ObjCDictionaryLiteral *DictionaryLiteral); 8046 8047 /// Check a single element within a collection literal against the 8048 /// target element type. 8049 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, 8050 Expr *Element, unsigned ElementKind) { 8051 // Skip a bitcast to 'id' or qualified 'id'. 8052 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 8053 if (ICE->getCastKind() == CK_BitCast && 8054 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 8055 Element = ICE->getSubExpr(); 8056 } 8057 8058 QualType ElementType = Element->getType(); 8059 ExprResult ElementResult(Element); 8060 if (ElementType->getAs<ObjCObjectPointerType>() && 8061 S.CheckSingleAssignmentConstraints(TargetElementType, 8062 ElementResult, 8063 false, false) 8064 != Sema::Compatible) { 8065 S.Diag(Element->getLocStart(), 8066 diag::warn_objc_collection_literal_element) 8067 << ElementType << ElementKind << TargetElementType 8068 << Element->getSourceRange(); 8069 } 8070 8071 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 8072 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 8073 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 8074 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 8075 } 8076 8077 /// Check an Objective-C array literal being converted to the given 8078 /// target type. 8079 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 8080 ObjCArrayLiteral *ArrayLiteral) { 8081 if (!S.NSArrayDecl) 8082 return; 8083 8084 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 8085 if (!TargetObjCPtr) 8086 return; 8087 8088 if (TargetObjCPtr->isUnspecialized() || 8089 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 8090 != S.NSArrayDecl->getCanonicalDecl()) 8091 return; 8092 8093 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 8094 if (TypeArgs.size() != 1) 8095 return; 8096 8097 QualType TargetElementType = TypeArgs[0]; 8098 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 8099 checkObjCCollectionLiteralElement(S, TargetElementType, 8100 ArrayLiteral->getElement(I), 8101 0); 8102 } 8103 } 8104 8105 /// Check an Objective-C dictionary literal being converted to the given 8106 /// target type. 8107 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 8108 ObjCDictionaryLiteral *DictionaryLiteral) { 8109 if (!S.NSDictionaryDecl) 8110 return; 8111 8112 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 8113 if (!TargetObjCPtr) 8114 return; 8115 8116 if (TargetObjCPtr->isUnspecialized() || 8117 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 8118 != S.NSDictionaryDecl->getCanonicalDecl()) 8119 return; 8120 8121 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 8122 if (TypeArgs.size() != 2) 8123 return; 8124 8125 QualType TargetKeyType = TypeArgs[0]; 8126 QualType TargetObjectType = TypeArgs[1]; 8127 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 8128 auto Element = DictionaryLiteral->getKeyValueElement(I); 8129 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 8130 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 8131 } 8132 } 8133 8134 // Helper function to filter out cases for constant width constant conversion. 8135 // Don't warn on char array initialization or for non-decimal values. 8136 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 8137 SourceLocation CC) { 8138 // If initializing from a constant, and the constant starts with '0', 8139 // then it is a binary, octal, or hexadecimal. Allow these constants 8140 // to fill all the bits, even if there is a sign change. 8141 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 8142 const char FirstLiteralCharacter = 8143 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 8144 if (FirstLiteralCharacter == '0') 8145 return false; 8146 } 8147 8148 // If the CC location points to a '{', and the type is char, then assume 8149 // assume it is an array initialization. 8150 if (CC.isValid() && T->isCharType()) { 8151 const char FirstContextCharacter = 8152 S.getSourceManager().getCharacterData(CC)[0]; 8153 if (FirstContextCharacter == '{') 8154 return false; 8155 } 8156 8157 return true; 8158 } 8159 8160 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 8161 SourceLocation CC, bool *ICContext = nullptr) { 8162 if (E->isTypeDependent() || E->isValueDependent()) return; 8163 8164 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 8165 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 8166 if (Source == Target) return; 8167 if (Target->isDependentType()) return; 8168 8169 // If the conversion context location is invalid don't complain. We also 8170 // don't want to emit a warning if the issue occurs from the expansion of 8171 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 8172 // delay this check as long as possible. Once we detect we are in that 8173 // scenario, we just return. 8174 if (CC.isInvalid()) 8175 return; 8176 8177 // Diagnose implicit casts to bool. 8178 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 8179 if (isa<StringLiteral>(E)) 8180 // Warn on string literal to bool. Checks for string literals in logical 8181 // and expressions, for instance, assert(0 && "error here"), are 8182 // prevented by a check in AnalyzeImplicitConversions(). 8183 return DiagnoseImpCast(S, E, T, CC, 8184 diag::warn_impcast_string_literal_to_bool); 8185 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 8186 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 8187 // This covers the literal expressions that evaluate to Objective-C 8188 // objects. 8189 return DiagnoseImpCast(S, E, T, CC, 8190 diag::warn_impcast_objective_c_literal_to_bool); 8191 } 8192 if (Source->isPointerType() || Source->canDecayToPointerType()) { 8193 // Warn on pointer to bool conversion that is always true. 8194 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 8195 SourceRange(CC)); 8196 } 8197 } 8198 8199 // Check implicit casts from Objective-C collection literals to specialized 8200 // collection types, e.g., NSArray<NSString *> *. 8201 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 8202 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 8203 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 8204 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 8205 8206 // Strip vector types. 8207 if (isa<VectorType>(Source)) { 8208 if (!isa<VectorType>(Target)) { 8209 if (S.SourceMgr.isInSystemMacro(CC)) 8210 return; 8211 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 8212 } 8213 8214 // If the vector cast is cast between two vectors of the same size, it is 8215 // a bitcast, not a conversion. 8216 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 8217 return; 8218 8219 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 8220 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 8221 } 8222 if (auto VecTy = dyn_cast<VectorType>(Target)) 8223 Target = VecTy->getElementType().getTypePtr(); 8224 8225 // Strip complex types. 8226 if (isa<ComplexType>(Source)) { 8227 if (!isa<ComplexType>(Target)) { 8228 if (S.SourceMgr.isInSystemMacro(CC)) 8229 return; 8230 8231 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 8232 } 8233 8234 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 8235 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 8236 } 8237 8238 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 8239 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 8240 8241 // If the source is floating point... 8242 if (SourceBT && SourceBT->isFloatingPoint()) { 8243 // ...and the target is floating point... 8244 if (TargetBT && TargetBT->isFloatingPoint()) { 8245 // ...then warn if we're dropping FP rank. 8246 8247 // Builtin FP kinds are ordered by increasing FP rank. 8248 if (SourceBT->getKind() > TargetBT->getKind()) { 8249 // Don't warn about float constants that are precisely 8250 // representable in the target type. 8251 Expr::EvalResult result; 8252 if (E->EvaluateAsRValue(result, S.Context)) { 8253 // Value might be a float, a float vector, or a float complex. 8254 if (IsSameFloatAfterCast(result.Val, 8255 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 8256 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 8257 return; 8258 } 8259 8260 if (S.SourceMgr.isInSystemMacro(CC)) 8261 return; 8262 8263 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 8264 } 8265 // ... or possibly if we're increasing rank, too 8266 else if (TargetBT->getKind() > SourceBT->getKind()) { 8267 if (S.SourceMgr.isInSystemMacro(CC)) 8268 return; 8269 8270 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 8271 } 8272 return; 8273 } 8274 8275 // If the target is integral, always warn. 8276 if (TargetBT && TargetBT->isInteger()) { 8277 if (S.SourceMgr.isInSystemMacro(CC)) 8278 return; 8279 8280 DiagnoseFloatingImpCast(S, E, T, CC); 8281 } 8282 8283 // Detect the case where a call result is converted from floating-point to 8284 // to bool, and the final argument to the call is converted from bool, to 8285 // discover this typo: 8286 // 8287 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 8288 // 8289 // FIXME: This is an incredibly special case; is there some more general 8290 // way to detect this class of misplaced-parentheses bug? 8291 if (Target->isBooleanType() && isa<CallExpr>(E)) { 8292 // Check last argument of function call to see if it is an 8293 // implicit cast from a type matching the type the result 8294 // is being cast to. 8295 CallExpr *CEx = cast<CallExpr>(E); 8296 if (unsigned NumArgs = CEx->getNumArgs()) { 8297 Expr *LastA = CEx->getArg(NumArgs - 1); 8298 Expr *InnerE = LastA->IgnoreParenImpCasts(); 8299 if (isa<ImplicitCastExpr>(LastA) && 8300 InnerE->getType()->isBooleanType()) { 8301 // Warn on this floating-point to bool conversion 8302 DiagnoseImpCast(S, E, T, CC, 8303 diag::warn_impcast_floating_point_to_bool); 8304 } 8305 } 8306 } 8307 return; 8308 } 8309 8310 DiagnoseNullConversion(S, E, T, CC); 8311 8312 if (!Source->isIntegerType() || !Target->isIntegerType()) 8313 return; 8314 8315 // TODO: remove this early return once the false positives for constant->bool 8316 // in templates, macros, etc, are reduced or removed. 8317 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 8318 return; 8319 8320 IntRange SourceRange = GetExprRange(S.Context, E); 8321 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 8322 8323 if (SourceRange.Width > TargetRange.Width) { 8324 // If the source is a constant, use a default-on diagnostic. 8325 // TODO: this should happen for bitfield stores, too. 8326 llvm::APSInt Value(32); 8327 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 8328 if (S.SourceMgr.isInSystemMacro(CC)) 8329 return; 8330 8331 std::string PrettySourceValue = Value.toString(10); 8332 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 8333 8334 S.DiagRuntimeBehavior(E->getExprLoc(), E, 8335 S.PDiag(diag::warn_impcast_integer_precision_constant) 8336 << PrettySourceValue << PrettyTargetValue 8337 << E->getType() << T << E->getSourceRange() 8338 << clang::SourceRange(CC)); 8339 return; 8340 } 8341 8342 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 8343 if (S.SourceMgr.isInSystemMacro(CC)) 8344 return; 8345 8346 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 8347 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 8348 /* pruneControlFlow */ true); 8349 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 8350 } 8351 8352 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 8353 SourceRange.NonNegative && Source->isSignedIntegerType()) { 8354 // Warn when doing a signed to signed conversion, warn if the positive 8355 // source value is exactly the width of the target type, which will 8356 // cause a negative value to be stored. 8357 8358 llvm::APSInt Value; 8359 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 8360 !S.SourceMgr.isInSystemMacro(CC)) { 8361 if (isSameWidthConstantConversion(S, E, T, CC)) { 8362 std::string PrettySourceValue = Value.toString(10); 8363 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 8364 8365 S.DiagRuntimeBehavior( 8366 E->getExprLoc(), E, 8367 S.PDiag(diag::warn_impcast_integer_precision_constant) 8368 << PrettySourceValue << PrettyTargetValue << E->getType() << T 8369 << E->getSourceRange() << clang::SourceRange(CC)); 8370 return; 8371 } 8372 } 8373 8374 // Fall through for non-constants to give a sign conversion warning. 8375 } 8376 8377 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 8378 (!TargetRange.NonNegative && SourceRange.NonNegative && 8379 SourceRange.Width == TargetRange.Width)) { 8380 if (S.SourceMgr.isInSystemMacro(CC)) 8381 return; 8382 8383 unsigned DiagID = diag::warn_impcast_integer_sign; 8384 8385 // Traditionally, gcc has warned about this under -Wsign-compare. 8386 // We also want to warn about it in -Wconversion. 8387 // So if -Wconversion is off, use a completely identical diagnostic 8388 // in the sign-compare group. 8389 // The conditional-checking code will 8390 if (ICContext) { 8391 DiagID = diag::warn_impcast_integer_sign_conditional; 8392 *ICContext = true; 8393 } 8394 8395 return DiagnoseImpCast(S, E, T, CC, DiagID); 8396 } 8397 8398 // Diagnose conversions between different enumeration types. 8399 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 8400 // type, to give us better diagnostics. 8401 QualType SourceType = E->getType(); 8402 if (!S.getLangOpts().CPlusPlus) { 8403 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8404 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 8405 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 8406 SourceType = S.Context.getTypeDeclType(Enum); 8407 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 8408 } 8409 } 8410 8411 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 8412 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 8413 if (SourceEnum->getDecl()->hasNameForLinkage() && 8414 TargetEnum->getDecl()->hasNameForLinkage() && 8415 SourceEnum != TargetEnum) { 8416 if (S.SourceMgr.isInSystemMacro(CC)) 8417 return; 8418 8419 return DiagnoseImpCast(S, E, SourceType, T, CC, 8420 diag::warn_impcast_different_enum_types); 8421 } 8422 } 8423 8424 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 8425 SourceLocation CC, QualType T); 8426 8427 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 8428 SourceLocation CC, bool &ICContext) { 8429 E = E->IgnoreParenImpCasts(); 8430 8431 if (isa<ConditionalOperator>(E)) 8432 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 8433 8434 AnalyzeImplicitConversions(S, E, CC); 8435 if (E->getType() != T) 8436 return CheckImplicitConversion(S, E, T, CC, &ICContext); 8437 } 8438 8439 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 8440 SourceLocation CC, QualType T) { 8441 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 8442 8443 bool Suspicious = false; 8444 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 8445 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 8446 8447 // If -Wconversion would have warned about either of the candidates 8448 // for a signedness conversion to the context type... 8449 if (!Suspicious) return; 8450 8451 // ...but it's currently ignored... 8452 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 8453 return; 8454 8455 // ...then check whether it would have warned about either of the 8456 // candidates for a signedness conversion to the condition type. 8457 if (E->getType() == T) return; 8458 8459 Suspicious = false; 8460 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 8461 E->getType(), CC, &Suspicious); 8462 if (!Suspicious) 8463 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 8464 E->getType(), CC, &Suspicious); 8465 } 8466 8467 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 8468 /// Input argument E is a logical expression. 8469 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 8470 if (S.getLangOpts().Bool) 8471 return; 8472 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 8473 } 8474 8475 /// AnalyzeImplicitConversions - Find and report any interesting 8476 /// implicit conversions in the given expression. There are a couple 8477 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 8478 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 8479 QualType T = OrigE->getType(); 8480 Expr *E = OrigE->IgnoreParenImpCasts(); 8481 8482 if (E->isTypeDependent() || E->isValueDependent()) 8483 return; 8484 8485 // For conditional operators, we analyze the arguments as if they 8486 // were being fed directly into the output. 8487 if (isa<ConditionalOperator>(E)) { 8488 ConditionalOperator *CO = cast<ConditionalOperator>(E); 8489 CheckConditionalOperator(S, CO, CC, T); 8490 return; 8491 } 8492 8493 // Check implicit argument conversions for function calls. 8494 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 8495 CheckImplicitArgumentConversions(S, Call, CC); 8496 8497 // Go ahead and check any implicit conversions we might have skipped. 8498 // The non-canonical typecheck is just an optimization; 8499 // CheckImplicitConversion will filter out dead implicit conversions. 8500 if (E->getType() != T) 8501 CheckImplicitConversion(S, E, T, CC); 8502 8503 // Now continue drilling into this expression. 8504 8505 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 8506 // The bound subexpressions in a PseudoObjectExpr are not reachable 8507 // as transitive children. 8508 // FIXME: Use a more uniform representation for this. 8509 for (auto *SE : POE->semantics()) 8510 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 8511 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 8512 } 8513 8514 // Skip past explicit casts. 8515 if (isa<ExplicitCastExpr>(E)) { 8516 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 8517 return AnalyzeImplicitConversions(S, E, CC); 8518 } 8519 8520 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 8521 // Do a somewhat different check with comparison operators. 8522 if (BO->isComparisonOp()) 8523 return AnalyzeComparison(S, BO); 8524 8525 // And with simple assignments. 8526 if (BO->getOpcode() == BO_Assign) 8527 return AnalyzeAssignment(S, BO); 8528 } 8529 8530 // These break the otherwise-useful invariant below. Fortunately, 8531 // we don't really need to recurse into them, because any internal 8532 // expressions should have been analyzed already when they were 8533 // built into statements. 8534 if (isa<StmtExpr>(E)) return; 8535 8536 // Don't descend into unevaluated contexts. 8537 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 8538 8539 // Now just recurse over the expression's children. 8540 CC = E->getExprLoc(); 8541 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 8542 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 8543 for (Stmt *SubStmt : E->children()) { 8544 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 8545 if (!ChildExpr) 8546 continue; 8547 8548 if (IsLogicalAndOperator && 8549 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 8550 // Ignore checking string literals that are in logical and operators. 8551 // This is a common pattern for asserts. 8552 continue; 8553 AnalyzeImplicitConversions(S, ChildExpr, CC); 8554 } 8555 8556 if (BO && BO->isLogicalOp()) { 8557 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 8558 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 8559 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 8560 8561 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 8562 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 8563 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 8564 } 8565 8566 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 8567 if (U->getOpcode() == UO_LNot) 8568 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 8569 } 8570 8571 } // end anonymous namespace 8572 8573 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 8574 unsigned Start, unsigned End) { 8575 bool IllegalParams = false; 8576 for (unsigned I = Start; I <= End; ++I) { 8577 QualType Ty = TheCall->getArg(I)->getType(); 8578 // Taking into account implicit conversions, 8579 // allow any integer within 32 bits range 8580 if (!Ty->isIntegerType() || 8581 S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) { 8582 S.Diag(TheCall->getArg(I)->getLocStart(), 8583 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 8584 IllegalParams = true; 8585 } 8586 // Potentially emit standard warnings for implicit conversions if enabled 8587 // using -Wconversion. 8588 CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy, 8589 TheCall->getArg(I)->getLocStart()); 8590 } 8591 return IllegalParams; 8592 } 8593 8594 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 8595 // Returns true when emitting a warning about taking the address of a reference. 8596 static bool CheckForReference(Sema &SemaRef, const Expr *E, 8597 const PartialDiagnostic &PD) { 8598 E = E->IgnoreParenImpCasts(); 8599 8600 const FunctionDecl *FD = nullptr; 8601 8602 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 8603 if (!DRE->getDecl()->getType()->isReferenceType()) 8604 return false; 8605 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 8606 if (!M->getMemberDecl()->getType()->isReferenceType()) 8607 return false; 8608 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 8609 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 8610 return false; 8611 FD = Call->getDirectCallee(); 8612 } else { 8613 return false; 8614 } 8615 8616 SemaRef.Diag(E->getExprLoc(), PD); 8617 8618 // If possible, point to location of function. 8619 if (FD) { 8620 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 8621 } 8622 8623 return true; 8624 } 8625 8626 // Returns true if the SourceLocation is expanded from any macro body. 8627 // Returns false if the SourceLocation is invalid, is from not in a macro 8628 // expansion, or is from expanded from a top-level macro argument. 8629 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 8630 if (Loc.isInvalid()) 8631 return false; 8632 8633 while (Loc.isMacroID()) { 8634 if (SM.isMacroBodyExpansion(Loc)) 8635 return true; 8636 Loc = SM.getImmediateMacroCallerLoc(Loc); 8637 } 8638 8639 return false; 8640 } 8641 8642 /// \brief Diagnose pointers that are always non-null. 8643 /// \param E the expression containing the pointer 8644 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 8645 /// compared to a null pointer 8646 /// \param IsEqual True when the comparison is equal to a null pointer 8647 /// \param Range Extra SourceRange to highlight in the diagnostic 8648 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 8649 Expr::NullPointerConstantKind NullKind, 8650 bool IsEqual, SourceRange Range) { 8651 if (!E) 8652 return; 8653 8654 // Don't warn inside macros. 8655 if (E->getExprLoc().isMacroID()) { 8656 const SourceManager &SM = getSourceManager(); 8657 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 8658 IsInAnyMacroBody(SM, Range.getBegin())) 8659 return; 8660 } 8661 E = E->IgnoreImpCasts(); 8662 8663 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 8664 8665 if (isa<CXXThisExpr>(E)) { 8666 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 8667 : diag::warn_this_bool_conversion; 8668 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 8669 return; 8670 } 8671 8672 bool IsAddressOf = false; 8673 8674 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 8675 if (UO->getOpcode() != UO_AddrOf) 8676 return; 8677 IsAddressOf = true; 8678 E = UO->getSubExpr(); 8679 } 8680 8681 if (IsAddressOf) { 8682 unsigned DiagID = IsCompare 8683 ? diag::warn_address_of_reference_null_compare 8684 : diag::warn_address_of_reference_bool_conversion; 8685 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 8686 << IsEqual; 8687 if (CheckForReference(*this, E, PD)) { 8688 return; 8689 } 8690 } 8691 8692 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 8693 bool IsParam = isa<NonNullAttr>(NonnullAttr); 8694 std::string Str; 8695 llvm::raw_string_ostream S(Str); 8696 E->printPretty(S, nullptr, getPrintingPolicy()); 8697 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 8698 : diag::warn_cast_nonnull_to_bool; 8699 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 8700 << E->getSourceRange() << Range << IsEqual; 8701 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 8702 }; 8703 8704 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 8705 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 8706 if (auto *Callee = Call->getDirectCallee()) { 8707 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 8708 ComplainAboutNonnullParamOrCall(A); 8709 return; 8710 } 8711 } 8712 } 8713 8714 // Expect to find a single Decl. Skip anything more complicated. 8715 ValueDecl *D = nullptr; 8716 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 8717 D = R->getDecl(); 8718 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 8719 D = M->getMemberDecl(); 8720 } 8721 8722 // Weak Decls can be null. 8723 if (!D || D->isWeak()) 8724 return; 8725 8726 // Check for parameter decl with nonnull attribute 8727 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 8728 if (getCurFunction() && 8729 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 8730 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 8731 ComplainAboutNonnullParamOrCall(A); 8732 return; 8733 } 8734 8735 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 8736 auto ParamIter = llvm::find(FD->parameters(), PV); 8737 assert(ParamIter != FD->param_end()); 8738 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 8739 8740 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 8741 if (!NonNull->args_size()) { 8742 ComplainAboutNonnullParamOrCall(NonNull); 8743 return; 8744 } 8745 8746 for (unsigned ArgNo : NonNull->args()) { 8747 if (ArgNo == ParamNo) { 8748 ComplainAboutNonnullParamOrCall(NonNull); 8749 return; 8750 } 8751 } 8752 } 8753 } 8754 } 8755 } 8756 8757 QualType T = D->getType(); 8758 const bool IsArray = T->isArrayType(); 8759 const bool IsFunction = T->isFunctionType(); 8760 8761 // Address of function is used to silence the function warning. 8762 if (IsAddressOf && IsFunction) { 8763 return; 8764 } 8765 8766 // Found nothing. 8767 if (!IsAddressOf && !IsFunction && !IsArray) 8768 return; 8769 8770 // Pretty print the expression for the diagnostic. 8771 std::string Str; 8772 llvm::raw_string_ostream S(Str); 8773 E->printPretty(S, nullptr, getPrintingPolicy()); 8774 8775 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 8776 : diag::warn_impcast_pointer_to_bool; 8777 enum { 8778 AddressOf, 8779 FunctionPointer, 8780 ArrayPointer 8781 } DiagType; 8782 if (IsAddressOf) 8783 DiagType = AddressOf; 8784 else if (IsFunction) 8785 DiagType = FunctionPointer; 8786 else if (IsArray) 8787 DiagType = ArrayPointer; 8788 else 8789 llvm_unreachable("Could not determine diagnostic."); 8790 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 8791 << Range << IsEqual; 8792 8793 if (!IsFunction) 8794 return; 8795 8796 // Suggest '&' to silence the function warning. 8797 Diag(E->getExprLoc(), diag::note_function_warning_silence) 8798 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 8799 8800 // Check to see if '()' fixit should be emitted. 8801 QualType ReturnType; 8802 UnresolvedSet<4> NonTemplateOverloads; 8803 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 8804 if (ReturnType.isNull()) 8805 return; 8806 8807 if (IsCompare) { 8808 // There are two cases here. If there is null constant, the only suggest 8809 // for a pointer return type. If the null is 0, then suggest if the return 8810 // type is a pointer or an integer type. 8811 if (!ReturnType->isPointerType()) { 8812 if (NullKind == Expr::NPCK_ZeroExpression || 8813 NullKind == Expr::NPCK_ZeroLiteral) { 8814 if (!ReturnType->isIntegerType()) 8815 return; 8816 } else { 8817 return; 8818 } 8819 } 8820 } else { // !IsCompare 8821 // For function to bool, only suggest if the function pointer has bool 8822 // return type. 8823 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 8824 return; 8825 } 8826 Diag(E->getExprLoc(), diag::note_function_to_function_call) 8827 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 8828 } 8829 8830 /// Diagnoses "dangerous" implicit conversions within the given 8831 /// expression (which is a full expression). Implements -Wconversion 8832 /// and -Wsign-compare. 8833 /// 8834 /// \param CC the "context" location of the implicit conversion, i.e. 8835 /// the most location of the syntactic entity requiring the implicit 8836 /// conversion 8837 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 8838 // Don't diagnose in unevaluated contexts. 8839 if (isUnevaluatedContext()) 8840 return; 8841 8842 // Don't diagnose for value- or type-dependent expressions. 8843 if (E->isTypeDependent() || E->isValueDependent()) 8844 return; 8845 8846 // Check for array bounds violations in cases where the check isn't triggered 8847 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 8848 // ArraySubscriptExpr is on the RHS of a variable initialization. 8849 CheckArrayAccess(E); 8850 8851 // This is not the right CC for (e.g.) a variable initialization. 8852 AnalyzeImplicitConversions(*this, E, CC); 8853 } 8854 8855 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 8856 /// Input argument E is a logical expression. 8857 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 8858 ::CheckBoolLikeConversion(*this, E, CC); 8859 } 8860 8861 /// Diagnose when expression is an integer constant expression and its evaluation 8862 /// results in integer overflow 8863 void Sema::CheckForIntOverflow (Expr *E) { 8864 // Use a work list to deal with nested struct initializers. 8865 SmallVector<Expr *, 2> Exprs(1, E); 8866 8867 do { 8868 Expr *E = Exprs.pop_back_val(); 8869 8870 if (isa<BinaryOperator>(E->IgnoreParenCasts())) { 8871 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 8872 continue; 8873 } 8874 8875 if (auto InitList = dyn_cast<InitListExpr>(E)) 8876 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 8877 } while (!Exprs.empty()); 8878 } 8879 8880 namespace { 8881 /// \brief Visitor for expressions which looks for unsequenced operations on the 8882 /// same object. 8883 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 8884 typedef EvaluatedExprVisitor<SequenceChecker> Base; 8885 8886 /// \brief A tree of sequenced regions within an expression. Two regions are 8887 /// unsequenced if one is an ancestor or a descendent of the other. When we 8888 /// finish processing an expression with sequencing, such as a comma 8889 /// expression, we fold its tree nodes into its parent, since they are 8890 /// unsequenced with respect to nodes we will visit later. 8891 class SequenceTree { 8892 struct Value { 8893 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 8894 unsigned Parent : 31; 8895 bool Merged : 1; 8896 }; 8897 SmallVector<Value, 8> Values; 8898 8899 public: 8900 /// \brief A region within an expression which may be sequenced with respect 8901 /// to some other region. 8902 class Seq { 8903 explicit Seq(unsigned N) : Index(N) {} 8904 unsigned Index; 8905 friend class SequenceTree; 8906 public: 8907 Seq() : Index(0) {} 8908 }; 8909 8910 SequenceTree() { Values.push_back(Value(0)); } 8911 Seq root() const { return Seq(0); } 8912 8913 /// \brief Create a new sequence of operations, which is an unsequenced 8914 /// subset of \p Parent. This sequence of operations is sequenced with 8915 /// respect to other children of \p Parent. 8916 Seq allocate(Seq Parent) { 8917 Values.push_back(Value(Parent.Index)); 8918 return Seq(Values.size() - 1); 8919 } 8920 8921 /// \brief Merge a sequence of operations into its parent. 8922 void merge(Seq S) { 8923 Values[S.Index].Merged = true; 8924 } 8925 8926 /// \brief Determine whether two operations are unsequenced. This operation 8927 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 8928 /// should have been merged into its parent as appropriate. 8929 bool isUnsequenced(Seq Cur, Seq Old) { 8930 unsigned C = representative(Cur.Index); 8931 unsigned Target = representative(Old.Index); 8932 while (C >= Target) { 8933 if (C == Target) 8934 return true; 8935 C = Values[C].Parent; 8936 } 8937 return false; 8938 } 8939 8940 private: 8941 /// \brief Pick a representative for a sequence. 8942 unsigned representative(unsigned K) { 8943 if (Values[K].Merged) 8944 // Perform path compression as we go. 8945 return Values[K].Parent = representative(Values[K].Parent); 8946 return K; 8947 } 8948 }; 8949 8950 /// An object for which we can track unsequenced uses. 8951 typedef NamedDecl *Object; 8952 8953 /// Different flavors of object usage which we track. We only track the 8954 /// least-sequenced usage of each kind. 8955 enum UsageKind { 8956 /// A read of an object. Multiple unsequenced reads are OK. 8957 UK_Use, 8958 /// A modification of an object which is sequenced before the value 8959 /// computation of the expression, such as ++n in C++. 8960 UK_ModAsValue, 8961 /// A modification of an object which is not sequenced before the value 8962 /// computation of the expression, such as n++. 8963 UK_ModAsSideEffect, 8964 8965 UK_Count = UK_ModAsSideEffect + 1 8966 }; 8967 8968 struct Usage { 8969 Usage() : Use(nullptr), Seq() {} 8970 Expr *Use; 8971 SequenceTree::Seq Seq; 8972 }; 8973 8974 struct UsageInfo { 8975 UsageInfo() : Diagnosed(false) {} 8976 Usage Uses[UK_Count]; 8977 /// Have we issued a diagnostic for this variable already? 8978 bool Diagnosed; 8979 }; 8980 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 8981 8982 Sema &SemaRef; 8983 /// Sequenced regions within the expression. 8984 SequenceTree Tree; 8985 /// Declaration modifications and references which we have seen. 8986 UsageInfoMap UsageMap; 8987 /// The region we are currently within. 8988 SequenceTree::Seq Region; 8989 /// Filled in with declarations which were modified as a side-effect 8990 /// (that is, post-increment operations). 8991 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 8992 /// Expressions to check later. We defer checking these to reduce 8993 /// stack usage. 8994 SmallVectorImpl<Expr *> &WorkList; 8995 8996 /// RAII object wrapping the visitation of a sequenced subexpression of an 8997 /// expression. At the end of this process, the side-effects of the evaluation 8998 /// become sequenced with respect to the value computation of the result, so 8999 /// we downgrade any UK_ModAsSideEffect within the evaluation to 9000 /// UK_ModAsValue. 9001 struct SequencedSubexpression { 9002 SequencedSubexpression(SequenceChecker &Self) 9003 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 9004 Self.ModAsSideEffect = &ModAsSideEffect; 9005 } 9006 ~SequencedSubexpression() { 9007 for (auto &M : llvm::reverse(ModAsSideEffect)) { 9008 UsageInfo &U = Self.UsageMap[M.first]; 9009 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 9010 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 9011 SideEffectUsage = M.second; 9012 } 9013 Self.ModAsSideEffect = OldModAsSideEffect; 9014 } 9015 9016 SequenceChecker &Self; 9017 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 9018 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 9019 }; 9020 9021 /// RAII object wrapping the visitation of a subexpression which we might 9022 /// choose to evaluate as a constant. If any subexpression is evaluated and 9023 /// found to be non-constant, this allows us to suppress the evaluation of 9024 /// the outer expression. 9025 class EvaluationTracker { 9026 public: 9027 EvaluationTracker(SequenceChecker &Self) 9028 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 9029 Self.EvalTracker = this; 9030 } 9031 ~EvaluationTracker() { 9032 Self.EvalTracker = Prev; 9033 if (Prev) 9034 Prev->EvalOK &= EvalOK; 9035 } 9036 9037 bool evaluate(const Expr *E, bool &Result) { 9038 if (!EvalOK || E->isValueDependent()) 9039 return false; 9040 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 9041 return EvalOK; 9042 } 9043 9044 private: 9045 SequenceChecker &Self; 9046 EvaluationTracker *Prev; 9047 bool EvalOK; 9048 } *EvalTracker; 9049 9050 /// \brief Find the object which is produced by the specified expression, 9051 /// if any. 9052 Object getObject(Expr *E, bool Mod) const { 9053 E = E->IgnoreParenCasts(); 9054 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9055 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 9056 return getObject(UO->getSubExpr(), Mod); 9057 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9058 if (BO->getOpcode() == BO_Comma) 9059 return getObject(BO->getRHS(), Mod); 9060 if (Mod && BO->isAssignmentOp()) 9061 return getObject(BO->getLHS(), Mod); 9062 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9063 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 9064 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 9065 return ME->getMemberDecl(); 9066 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9067 // FIXME: If this is a reference, map through to its value. 9068 return DRE->getDecl(); 9069 return nullptr; 9070 } 9071 9072 /// \brief Note that an object was modified or used by an expression. 9073 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 9074 Usage &U = UI.Uses[UK]; 9075 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 9076 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 9077 ModAsSideEffect->push_back(std::make_pair(O, U)); 9078 U.Use = Ref; 9079 U.Seq = Region; 9080 } 9081 } 9082 /// \brief Check whether a modification or use conflicts with a prior usage. 9083 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 9084 bool IsModMod) { 9085 if (UI.Diagnosed) 9086 return; 9087 9088 const Usage &U = UI.Uses[OtherKind]; 9089 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 9090 return; 9091 9092 Expr *Mod = U.Use; 9093 Expr *ModOrUse = Ref; 9094 if (OtherKind == UK_Use) 9095 std::swap(Mod, ModOrUse); 9096 9097 SemaRef.Diag(Mod->getExprLoc(), 9098 IsModMod ? diag::warn_unsequenced_mod_mod 9099 : diag::warn_unsequenced_mod_use) 9100 << O << SourceRange(ModOrUse->getExprLoc()); 9101 UI.Diagnosed = true; 9102 } 9103 9104 void notePreUse(Object O, Expr *Use) { 9105 UsageInfo &U = UsageMap[O]; 9106 // Uses conflict with other modifications. 9107 checkUsage(O, U, Use, UK_ModAsValue, false); 9108 } 9109 void notePostUse(Object O, Expr *Use) { 9110 UsageInfo &U = UsageMap[O]; 9111 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 9112 addUsage(U, O, Use, UK_Use); 9113 } 9114 9115 void notePreMod(Object O, Expr *Mod) { 9116 UsageInfo &U = UsageMap[O]; 9117 // Modifications conflict with other modifications and with uses. 9118 checkUsage(O, U, Mod, UK_ModAsValue, true); 9119 checkUsage(O, U, Mod, UK_Use, false); 9120 } 9121 void notePostMod(Object O, Expr *Use, UsageKind UK) { 9122 UsageInfo &U = UsageMap[O]; 9123 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 9124 addUsage(U, O, Use, UK); 9125 } 9126 9127 public: 9128 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 9129 : Base(S.Context), SemaRef(S), Region(Tree.root()), 9130 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 9131 Visit(E); 9132 } 9133 9134 void VisitStmt(Stmt *S) { 9135 // Skip all statements which aren't expressions for now. 9136 } 9137 9138 void VisitExpr(Expr *E) { 9139 // By default, just recurse to evaluated subexpressions. 9140 Base::VisitStmt(E); 9141 } 9142 9143 void VisitCastExpr(CastExpr *E) { 9144 Object O = Object(); 9145 if (E->getCastKind() == CK_LValueToRValue) 9146 O = getObject(E->getSubExpr(), false); 9147 9148 if (O) 9149 notePreUse(O, E); 9150 VisitExpr(E); 9151 if (O) 9152 notePostUse(O, E); 9153 } 9154 9155 void VisitBinComma(BinaryOperator *BO) { 9156 // C++11 [expr.comma]p1: 9157 // Every value computation and side effect associated with the left 9158 // expression is sequenced before every value computation and side 9159 // effect associated with the right expression. 9160 SequenceTree::Seq LHS = Tree.allocate(Region); 9161 SequenceTree::Seq RHS = Tree.allocate(Region); 9162 SequenceTree::Seq OldRegion = Region; 9163 9164 { 9165 SequencedSubexpression SeqLHS(*this); 9166 Region = LHS; 9167 Visit(BO->getLHS()); 9168 } 9169 9170 Region = RHS; 9171 Visit(BO->getRHS()); 9172 9173 Region = OldRegion; 9174 9175 // Forget that LHS and RHS are sequenced. They are both unsequenced 9176 // with respect to other stuff. 9177 Tree.merge(LHS); 9178 Tree.merge(RHS); 9179 } 9180 9181 void VisitBinAssign(BinaryOperator *BO) { 9182 // The modification is sequenced after the value computation of the LHS 9183 // and RHS, so check it before inspecting the operands and update the 9184 // map afterwards. 9185 Object O = getObject(BO->getLHS(), true); 9186 if (!O) 9187 return VisitExpr(BO); 9188 9189 notePreMod(O, BO); 9190 9191 // C++11 [expr.ass]p7: 9192 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 9193 // only once. 9194 // 9195 // Therefore, for a compound assignment operator, O is considered used 9196 // everywhere except within the evaluation of E1 itself. 9197 if (isa<CompoundAssignOperator>(BO)) 9198 notePreUse(O, BO); 9199 9200 Visit(BO->getLHS()); 9201 9202 if (isa<CompoundAssignOperator>(BO)) 9203 notePostUse(O, BO); 9204 9205 Visit(BO->getRHS()); 9206 9207 // C++11 [expr.ass]p1: 9208 // the assignment is sequenced [...] before the value computation of the 9209 // assignment expression. 9210 // C11 6.5.16/3 has no such rule. 9211 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 9212 : UK_ModAsSideEffect); 9213 } 9214 9215 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 9216 VisitBinAssign(CAO); 9217 } 9218 9219 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 9220 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 9221 void VisitUnaryPreIncDec(UnaryOperator *UO) { 9222 Object O = getObject(UO->getSubExpr(), true); 9223 if (!O) 9224 return VisitExpr(UO); 9225 9226 notePreMod(O, UO); 9227 Visit(UO->getSubExpr()); 9228 // C++11 [expr.pre.incr]p1: 9229 // the expression ++x is equivalent to x+=1 9230 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 9231 : UK_ModAsSideEffect); 9232 } 9233 9234 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 9235 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 9236 void VisitUnaryPostIncDec(UnaryOperator *UO) { 9237 Object O = getObject(UO->getSubExpr(), true); 9238 if (!O) 9239 return VisitExpr(UO); 9240 9241 notePreMod(O, UO); 9242 Visit(UO->getSubExpr()); 9243 notePostMod(O, UO, UK_ModAsSideEffect); 9244 } 9245 9246 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 9247 void VisitBinLOr(BinaryOperator *BO) { 9248 // The side-effects of the LHS of an '&&' are sequenced before the 9249 // value computation of the RHS, and hence before the value computation 9250 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 9251 // as if they were unconditionally sequenced. 9252 EvaluationTracker Eval(*this); 9253 { 9254 SequencedSubexpression Sequenced(*this); 9255 Visit(BO->getLHS()); 9256 } 9257 9258 bool Result; 9259 if (Eval.evaluate(BO->getLHS(), Result)) { 9260 if (!Result) 9261 Visit(BO->getRHS()); 9262 } else { 9263 // Check for unsequenced operations in the RHS, treating it as an 9264 // entirely separate evaluation. 9265 // 9266 // FIXME: If there are operations in the RHS which are unsequenced 9267 // with respect to operations outside the RHS, and those operations 9268 // are unconditionally evaluated, diagnose them. 9269 WorkList.push_back(BO->getRHS()); 9270 } 9271 } 9272 void VisitBinLAnd(BinaryOperator *BO) { 9273 EvaluationTracker Eval(*this); 9274 { 9275 SequencedSubexpression Sequenced(*this); 9276 Visit(BO->getLHS()); 9277 } 9278 9279 bool Result; 9280 if (Eval.evaluate(BO->getLHS(), Result)) { 9281 if (Result) 9282 Visit(BO->getRHS()); 9283 } else { 9284 WorkList.push_back(BO->getRHS()); 9285 } 9286 } 9287 9288 // Only visit the condition, unless we can be sure which subexpression will 9289 // be chosen. 9290 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 9291 EvaluationTracker Eval(*this); 9292 { 9293 SequencedSubexpression Sequenced(*this); 9294 Visit(CO->getCond()); 9295 } 9296 9297 bool Result; 9298 if (Eval.evaluate(CO->getCond(), Result)) 9299 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 9300 else { 9301 WorkList.push_back(CO->getTrueExpr()); 9302 WorkList.push_back(CO->getFalseExpr()); 9303 } 9304 } 9305 9306 void VisitCallExpr(CallExpr *CE) { 9307 // C++11 [intro.execution]p15: 9308 // When calling a function [...], every value computation and side effect 9309 // associated with any argument expression, or with the postfix expression 9310 // designating the called function, is sequenced before execution of every 9311 // expression or statement in the body of the function [and thus before 9312 // the value computation of its result]. 9313 SequencedSubexpression Sequenced(*this); 9314 Base::VisitCallExpr(CE); 9315 9316 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 9317 } 9318 9319 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 9320 // This is a call, so all subexpressions are sequenced before the result. 9321 SequencedSubexpression Sequenced(*this); 9322 9323 if (!CCE->isListInitialization()) 9324 return VisitExpr(CCE); 9325 9326 // In C++11, list initializations are sequenced. 9327 SmallVector<SequenceTree::Seq, 32> Elts; 9328 SequenceTree::Seq Parent = Region; 9329 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 9330 E = CCE->arg_end(); 9331 I != E; ++I) { 9332 Region = Tree.allocate(Parent); 9333 Elts.push_back(Region); 9334 Visit(*I); 9335 } 9336 9337 // Forget that the initializers are sequenced. 9338 Region = Parent; 9339 for (unsigned I = 0; I < Elts.size(); ++I) 9340 Tree.merge(Elts[I]); 9341 } 9342 9343 void VisitInitListExpr(InitListExpr *ILE) { 9344 if (!SemaRef.getLangOpts().CPlusPlus11) 9345 return VisitExpr(ILE); 9346 9347 // In C++11, list initializations are sequenced. 9348 SmallVector<SequenceTree::Seq, 32> Elts; 9349 SequenceTree::Seq Parent = Region; 9350 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 9351 Expr *E = ILE->getInit(I); 9352 if (!E) continue; 9353 Region = Tree.allocate(Parent); 9354 Elts.push_back(Region); 9355 Visit(E); 9356 } 9357 9358 // Forget that the initializers are sequenced. 9359 Region = Parent; 9360 for (unsigned I = 0; I < Elts.size(); ++I) 9361 Tree.merge(Elts[I]); 9362 } 9363 }; 9364 } // end anonymous namespace 9365 9366 void Sema::CheckUnsequencedOperations(Expr *E) { 9367 SmallVector<Expr *, 8> WorkList; 9368 WorkList.push_back(E); 9369 while (!WorkList.empty()) { 9370 Expr *Item = WorkList.pop_back_val(); 9371 SequenceChecker(*this, Item, WorkList); 9372 } 9373 } 9374 9375 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 9376 bool IsConstexpr) { 9377 CheckImplicitConversions(E, CheckLoc); 9378 CheckUnsequencedOperations(E); 9379 if (!IsConstexpr && !E->isValueDependent()) 9380 CheckForIntOverflow(E); 9381 } 9382 9383 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 9384 FieldDecl *BitField, 9385 Expr *Init) { 9386 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 9387 } 9388 9389 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 9390 SourceLocation Loc) { 9391 if (!PType->isVariablyModifiedType()) 9392 return; 9393 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 9394 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 9395 return; 9396 } 9397 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 9398 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 9399 return; 9400 } 9401 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 9402 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 9403 return; 9404 } 9405 9406 const ArrayType *AT = S.Context.getAsArrayType(PType); 9407 if (!AT) 9408 return; 9409 9410 if (AT->getSizeModifier() != ArrayType::Star) { 9411 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 9412 return; 9413 } 9414 9415 S.Diag(Loc, diag::err_array_star_in_function_definition); 9416 } 9417 9418 /// CheckParmsForFunctionDef - Check that the parameters of the given 9419 /// function are appropriate for the definition of a function. This 9420 /// takes care of any checks that cannot be performed on the 9421 /// declaration itself, e.g., that the types of each of the function 9422 /// parameters are complete. 9423 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 9424 bool CheckParameterNames) { 9425 bool HasInvalidParm = false; 9426 for (ParmVarDecl *Param : Parameters) { 9427 // C99 6.7.5.3p4: the parameters in a parameter type list in a 9428 // function declarator that is part of a function definition of 9429 // that function shall not have incomplete type. 9430 // 9431 // This is also C++ [dcl.fct]p6. 9432 if (!Param->isInvalidDecl() && 9433 RequireCompleteType(Param->getLocation(), Param->getType(), 9434 diag::err_typecheck_decl_incomplete_type)) { 9435 Param->setInvalidDecl(); 9436 HasInvalidParm = true; 9437 } 9438 9439 // C99 6.9.1p5: If the declarator includes a parameter type list, the 9440 // declaration of each parameter shall include an identifier. 9441 if (CheckParameterNames && 9442 Param->getIdentifier() == nullptr && 9443 !Param->isImplicit() && 9444 !getLangOpts().CPlusPlus) 9445 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 9446 9447 // C99 6.7.5.3p12: 9448 // If the function declarator is not part of a definition of that 9449 // function, parameters may have incomplete type and may use the [*] 9450 // notation in their sequences of declarator specifiers to specify 9451 // variable length array types. 9452 QualType PType = Param->getOriginalType(); 9453 // FIXME: This diagnostic should point the '[*]' if source-location 9454 // information is added for it. 9455 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 9456 9457 // MSVC destroys objects passed by value in the callee. Therefore a 9458 // function definition which takes such a parameter must be able to call the 9459 // object's destructor. However, we don't perform any direct access check 9460 // on the dtor. 9461 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 9462 .getCXXABI() 9463 .areArgsDestroyedLeftToRightInCallee()) { 9464 if (!Param->isInvalidDecl()) { 9465 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 9466 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 9467 if (!ClassDecl->isInvalidDecl() && 9468 !ClassDecl->hasIrrelevantDestructor() && 9469 !ClassDecl->isDependentContext()) { 9470 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 9471 MarkFunctionReferenced(Param->getLocation(), Destructor); 9472 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 9473 } 9474 } 9475 } 9476 } 9477 9478 // Parameters with the pass_object_size attribute only need to be marked 9479 // constant at function definitions. Because we lack information about 9480 // whether we're on a declaration or definition when we're instantiating the 9481 // attribute, we need to check for constness here. 9482 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 9483 if (!Param->getType().isConstQualified()) 9484 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 9485 << Attr->getSpelling() << 1; 9486 } 9487 9488 return HasInvalidParm; 9489 } 9490 9491 /// CheckCastAlign - Implements -Wcast-align, which warns when a 9492 /// pointer cast increases the alignment requirements. 9493 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 9494 // This is actually a lot of work to potentially be doing on every 9495 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 9496 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 9497 return; 9498 9499 // Ignore dependent types. 9500 if (T->isDependentType() || Op->getType()->isDependentType()) 9501 return; 9502 9503 // Require that the destination be a pointer type. 9504 const PointerType *DestPtr = T->getAs<PointerType>(); 9505 if (!DestPtr) return; 9506 9507 // If the destination has alignment 1, we're done. 9508 QualType DestPointee = DestPtr->getPointeeType(); 9509 if (DestPointee->isIncompleteType()) return; 9510 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 9511 if (DestAlign.isOne()) return; 9512 9513 // Require that the source be a pointer type. 9514 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 9515 if (!SrcPtr) return; 9516 QualType SrcPointee = SrcPtr->getPointeeType(); 9517 9518 // Whitelist casts from cv void*. We already implicitly 9519 // whitelisted casts to cv void*, since they have alignment 1. 9520 // Also whitelist casts involving incomplete types, which implicitly 9521 // includes 'void'. 9522 if (SrcPointee->isIncompleteType()) return; 9523 9524 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 9525 if (SrcAlign >= DestAlign) return; 9526 9527 Diag(TRange.getBegin(), diag::warn_cast_align) 9528 << Op->getType() << T 9529 << static_cast<unsigned>(SrcAlign.getQuantity()) 9530 << static_cast<unsigned>(DestAlign.getQuantity()) 9531 << TRange << Op->getSourceRange(); 9532 } 9533 9534 /// \brief Check whether this array fits the idiom of a size-one tail padded 9535 /// array member of a struct. 9536 /// 9537 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 9538 /// commonly used to emulate flexible arrays in C89 code. 9539 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 9540 const NamedDecl *ND) { 9541 if (Size != 1 || !ND) return false; 9542 9543 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 9544 if (!FD) return false; 9545 9546 // Don't consider sizes resulting from macro expansions or template argument 9547 // substitution to form C89 tail-padded arrays. 9548 9549 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 9550 while (TInfo) { 9551 TypeLoc TL = TInfo->getTypeLoc(); 9552 // Look through typedefs. 9553 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 9554 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 9555 TInfo = TDL->getTypeSourceInfo(); 9556 continue; 9557 } 9558 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 9559 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 9560 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 9561 return false; 9562 } 9563 break; 9564 } 9565 9566 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 9567 if (!RD) return false; 9568 if (RD->isUnion()) return false; 9569 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 9570 if (!CRD->isStandardLayout()) return false; 9571 } 9572 9573 // See if this is the last field decl in the record. 9574 const Decl *D = FD; 9575 while ((D = D->getNextDeclInContext())) 9576 if (isa<FieldDecl>(D)) 9577 return false; 9578 return true; 9579 } 9580 9581 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 9582 const ArraySubscriptExpr *ASE, 9583 bool AllowOnePastEnd, bool IndexNegated) { 9584 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 9585 if (IndexExpr->isValueDependent()) 9586 return; 9587 9588 const Type *EffectiveType = 9589 BaseExpr->getType()->getPointeeOrArrayElementType(); 9590 BaseExpr = BaseExpr->IgnoreParenCasts(); 9591 const ConstantArrayType *ArrayTy = 9592 Context.getAsConstantArrayType(BaseExpr->getType()); 9593 if (!ArrayTy) 9594 return; 9595 9596 llvm::APSInt index; 9597 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 9598 return; 9599 if (IndexNegated) 9600 index = -index; 9601 9602 const NamedDecl *ND = nullptr; 9603 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 9604 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 9605 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 9606 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 9607 9608 if (index.isUnsigned() || !index.isNegative()) { 9609 llvm::APInt size = ArrayTy->getSize(); 9610 if (!size.isStrictlyPositive()) 9611 return; 9612 9613 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 9614 if (BaseType != EffectiveType) { 9615 // Make sure we're comparing apples to apples when comparing index to size 9616 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 9617 uint64_t array_typesize = Context.getTypeSize(BaseType); 9618 // Handle ptrarith_typesize being zero, such as when casting to void* 9619 if (!ptrarith_typesize) ptrarith_typesize = 1; 9620 if (ptrarith_typesize != array_typesize) { 9621 // There's a cast to a different size type involved 9622 uint64_t ratio = array_typesize / ptrarith_typesize; 9623 // TODO: Be smarter about handling cases where array_typesize is not a 9624 // multiple of ptrarith_typesize 9625 if (ptrarith_typesize * ratio == array_typesize) 9626 size *= llvm::APInt(size.getBitWidth(), ratio); 9627 } 9628 } 9629 9630 if (size.getBitWidth() > index.getBitWidth()) 9631 index = index.zext(size.getBitWidth()); 9632 else if (size.getBitWidth() < index.getBitWidth()) 9633 size = size.zext(index.getBitWidth()); 9634 9635 // For array subscripting the index must be less than size, but for pointer 9636 // arithmetic also allow the index (offset) to be equal to size since 9637 // computing the next address after the end of the array is legal and 9638 // commonly done e.g. in C++ iterators and range-based for loops. 9639 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 9640 return; 9641 9642 // Also don't warn for arrays of size 1 which are members of some 9643 // structure. These are often used to approximate flexible arrays in C89 9644 // code. 9645 if (IsTailPaddedMemberArray(*this, size, ND)) 9646 return; 9647 9648 // Suppress the warning if the subscript expression (as identified by the 9649 // ']' location) and the index expression are both from macro expansions 9650 // within a system header. 9651 if (ASE) { 9652 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 9653 ASE->getRBracketLoc()); 9654 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 9655 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 9656 IndexExpr->getLocStart()); 9657 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 9658 return; 9659 } 9660 } 9661 9662 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 9663 if (ASE) 9664 DiagID = diag::warn_array_index_exceeds_bounds; 9665 9666 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 9667 PDiag(DiagID) << index.toString(10, true) 9668 << size.toString(10, true) 9669 << (unsigned)size.getLimitedValue(~0U) 9670 << IndexExpr->getSourceRange()); 9671 } else { 9672 unsigned DiagID = diag::warn_array_index_precedes_bounds; 9673 if (!ASE) { 9674 DiagID = diag::warn_ptr_arith_precedes_bounds; 9675 if (index.isNegative()) index = -index; 9676 } 9677 9678 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 9679 PDiag(DiagID) << index.toString(10, true) 9680 << IndexExpr->getSourceRange()); 9681 } 9682 9683 if (!ND) { 9684 // Try harder to find a NamedDecl to point at in the note. 9685 while (const ArraySubscriptExpr *ASE = 9686 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 9687 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 9688 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 9689 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 9690 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 9691 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 9692 } 9693 9694 if (ND) 9695 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 9696 PDiag(diag::note_array_index_out_of_bounds) 9697 << ND->getDeclName()); 9698 } 9699 9700 void Sema::CheckArrayAccess(const Expr *expr) { 9701 int AllowOnePastEnd = 0; 9702 while (expr) { 9703 expr = expr->IgnoreParenImpCasts(); 9704 switch (expr->getStmtClass()) { 9705 case Stmt::ArraySubscriptExprClass: { 9706 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 9707 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 9708 AllowOnePastEnd > 0); 9709 return; 9710 } 9711 case Stmt::OMPArraySectionExprClass: { 9712 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 9713 if (ASE->getLowerBound()) 9714 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 9715 /*ASE=*/nullptr, AllowOnePastEnd > 0); 9716 return; 9717 } 9718 case Stmt::UnaryOperatorClass: { 9719 // Only unwrap the * and & unary operators 9720 const UnaryOperator *UO = cast<UnaryOperator>(expr); 9721 expr = UO->getSubExpr(); 9722 switch (UO->getOpcode()) { 9723 case UO_AddrOf: 9724 AllowOnePastEnd++; 9725 break; 9726 case UO_Deref: 9727 AllowOnePastEnd--; 9728 break; 9729 default: 9730 return; 9731 } 9732 break; 9733 } 9734 case Stmt::ConditionalOperatorClass: { 9735 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 9736 if (const Expr *lhs = cond->getLHS()) 9737 CheckArrayAccess(lhs); 9738 if (const Expr *rhs = cond->getRHS()) 9739 CheckArrayAccess(rhs); 9740 return; 9741 } 9742 default: 9743 return; 9744 } 9745 } 9746 } 9747 9748 //===--- CHECK: Objective-C retain cycles ----------------------------------// 9749 9750 namespace { 9751 struct RetainCycleOwner { 9752 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 9753 VarDecl *Variable; 9754 SourceRange Range; 9755 SourceLocation Loc; 9756 bool Indirect; 9757 9758 void setLocsFrom(Expr *e) { 9759 Loc = e->getExprLoc(); 9760 Range = e->getSourceRange(); 9761 } 9762 }; 9763 } // end anonymous namespace 9764 9765 /// Consider whether capturing the given variable can possibly lead to 9766 /// a retain cycle. 9767 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 9768 // In ARC, it's captured strongly iff the variable has __strong 9769 // lifetime. In MRR, it's captured strongly if the variable is 9770 // __block and has an appropriate type. 9771 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 9772 return false; 9773 9774 owner.Variable = var; 9775 if (ref) 9776 owner.setLocsFrom(ref); 9777 return true; 9778 } 9779 9780 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 9781 while (true) { 9782 e = e->IgnoreParens(); 9783 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 9784 switch (cast->getCastKind()) { 9785 case CK_BitCast: 9786 case CK_LValueBitCast: 9787 case CK_LValueToRValue: 9788 case CK_ARCReclaimReturnedObject: 9789 e = cast->getSubExpr(); 9790 continue; 9791 9792 default: 9793 return false; 9794 } 9795 } 9796 9797 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 9798 ObjCIvarDecl *ivar = ref->getDecl(); 9799 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 9800 return false; 9801 9802 // Try to find a retain cycle in the base. 9803 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 9804 return false; 9805 9806 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 9807 owner.Indirect = true; 9808 return true; 9809 } 9810 9811 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 9812 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 9813 if (!var) return false; 9814 return considerVariable(var, ref, owner); 9815 } 9816 9817 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 9818 if (member->isArrow()) return false; 9819 9820 // Don't count this as an indirect ownership. 9821 e = member->getBase(); 9822 continue; 9823 } 9824 9825 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 9826 // Only pay attention to pseudo-objects on property references. 9827 ObjCPropertyRefExpr *pre 9828 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 9829 ->IgnoreParens()); 9830 if (!pre) return false; 9831 if (pre->isImplicitProperty()) return false; 9832 ObjCPropertyDecl *property = pre->getExplicitProperty(); 9833 if (!property->isRetaining() && 9834 !(property->getPropertyIvarDecl() && 9835 property->getPropertyIvarDecl()->getType() 9836 .getObjCLifetime() == Qualifiers::OCL_Strong)) 9837 return false; 9838 9839 owner.Indirect = true; 9840 if (pre->isSuperReceiver()) { 9841 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 9842 if (!owner.Variable) 9843 return false; 9844 owner.Loc = pre->getLocation(); 9845 owner.Range = pre->getSourceRange(); 9846 return true; 9847 } 9848 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 9849 ->getSourceExpr()); 9850 continue; 9851 } 9852 9853 // Array ivars? 9854 9855 return false; 9856 } 9857 } 9858 9859 namespace { 9860 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 9861 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 9862 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 9863 Context(Context), Variable(variable), Capturer(nullptr), 9864 VarWillBeReased(false) {} 9865 ASTContext &Context; 9866 VarDecl *Variable; 9867 Expr *Capturer; 9868 bool VarWillBeReased; 9869 9870 void VisitDeclRefExpr(DeclRefExpr *ref) { 9871 if (ref->getDecl() == Variable && !Capturer) 9872 Capturer = ref; 9873 } 9874 9875 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 9876 if (Capturer) return; 9877 Visit(ref->getBase()); 9878 if (Capturer && ref->isFreeIvar()) 9879 Capturer = ref; 9880 } 9881 9882 void VisitBlockExpr(BlockExpr *block) { 9883 // Look inside nested blocks 9884 if (block->getBlockDecl()->capturesVariable(Variable)) 9885 Visit(block->getBlockDecl()->getBody()); 9886 } 9887 9888 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 9889 if (Capturer) return; 9890 if (OVE->getSourceExpr()) 9891 Visit(OVE->getSourceExpr()); 9892 } 9893 void VisitBinaryOperator(BinaryOperator *BinOp) { 9894 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 9895 return; 9896 Expr *LHS = BinOp->getLHS(); 9897 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 9898 if (DRE->getDecl() != Variable) 9899 return; 9900 if (Expr *RHS = BinOp->getRHS()) { 9901 RHS = RHS->IgnoreParenCasts(); 9902 llvm::APSInt Value; 9903 VarWillBeReased = 9904 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 9905 } 9906 } 9907 } 9908 }; 9909 } // end anonymous namespace 9910 9911 /// Check whether the given argument is a block which captures a 9912 /// variable. 9913 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 9914 assert(owner.Variable && owner.Loc.isValid()); 9915 9916 e = e->IgnoreParenCasts(); 9917 9918 // Look through [^{...} copy] and Block_copy(^{...}). 9919 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 9920 Selector Cmd = ME->getSelector(); 9921 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 9922 e = ME->getInstanceReceiver(); 9923 if (!e) 9924 return nullptr; 9925 e = e->IgnoreParenCasts(); 9926 } 9927 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 9928 if (CE->getNumArgs() == 1) { 9929 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 9930 if (Fn) { 9931 const IdentifierInfo *FnI = Fn->getIdentifier(); 9932 if (FnI && FnI->isStr("_Block_copy")) { 9933 e = CE->getArg(0)->IgnoreParenCasts(); 9934 } 9935 } 9936 } 9937 } 9938 9939 BlockExpr *block = dyn_cast<BlockExpr>(e); 9940 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 9941 return nullptr; 9942 9943 FindCaptureVisitor visitor(S.Context, owner.Variable); 9944 visitor.Visit(block->getBlockDecl()->getBody()); 9945 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 9946 } 9947 9948 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 9949 RetainCycleOwner &owner) { 9950 assert(capturer); 9951 assert(owner.Variable && owner.Loc.isValid()); 9952 9953 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 9954 << owner.Variable << capturer->getSourceRange(); 9955 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 9956 << owner.Indirect << owner.Range; 9957 } 9958 9959 /// Check for a keyword selector that starts with the word 'add' or 9960 /// 'set'. 9961 static bool isSetterLikeSelector(Selector sel) { 9962 if (sel.isUnarySelector()) return false; 9963 9964 StringRef str = sel.getNameForSlot(0); 9965 while (!str.empty() && str.front() == '_') str = str.substr(1); 9966 if (str.startswith("set")) 9967 str = str.substr(3); 9968 else if (str.startswith("add")) { 9969 // Specially whitelist 'addOperationWithBlock:'. 9970 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 9971 return false; 9972 str = str.substr(3); 9973 } 9974 else 9975 return false; 9976 9977 if (str.empty()) return true; 9978 return !isLowercase(str.front()); 9979 } 9980 9981 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 9982 ObjCMessageExpr *Message) { 9983 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 9984 Message->getReceiverInterface(), 9985 NSAPI::ClassId_NSMutableArray); 9986 if (!IsMutableArray) { 9987 return None; 9988 } 9989 9990 Selector Sel = Message->getSelector(); 9991 9992 Optional<NSAPI::NSArrayMethodKind> MKOpt = 9993 S.NSAPIObj->getNSArrayMethodKind(Sel); 9994 if (!MKOpt) { 9995 return None; 9996 } 9997 9998 NSAPI::NSArrayMethodKind MK = *MKOpt; 9999 10000 switch (MK) { 10001 case NSAPI::NSMutableArr_addObject: 10002 case NSAPI::NSMutableArr_insertObjectAtIndex: 10003 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 10004 return 0; 10005 case NSAPI::NSMutableArr_replaceObjectAtIndex: 10006 return 1; 10007 10008 default: 10009 return None; 10010 } 10011 10012 return None; 10013 } 10014 10015 static 10016 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 10017 ObjCMessageExpr *Message) { 10018 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 10019 Message->getReceiverInterface(), 10020 NSAPI::ClassId_NSMutableDictionary); 10021 if (!IsMutableDictionary) { 10022 return None; 10023 } 10024 10025 Selector Sel = Message->getSelector(); 10026 10027 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 10028 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 10029 if (!MKOpt) { 10030 return None; 10031 } 10032 10033 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 10034 10035 switch (MK) { 10036 case NSAPI::NSMutableDict_setObjectForKey: 10037 case NSAPI::NSMutableDict_setValueForKey: 10038 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 10039 return 0; 10040 10041 default: 10042 return None; 10043 } 10044 10045 return None; 10046 } 10047 10048 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 10049 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 10050 Message->getReceiverInterface(), 10051 NSAPI::ClassId_NSMutableSet); 10052 10053 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 10054 Message->getReceiverInterface(), 10055 NSAPI::ClassId_NSMutableOrderedSet); 10056 if (!IsMutableSet && !IsMutableOrderedSet) { 10057 return None; 10058 } 10059 10060 Selector Sel = Message->getSelector(); 10061 10062 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 10063 if (!MKOpt) { 10064 return None; 10065 } 10066 10067 NSAPI::NSSetMethodKind MK = *MKOpt; 10068 10069 switch (MK) { 10070 case NSAPI::NSMutableSet_addObject: 10071 case NSAPI::NSOrderedSet_setObjectAtIndex: 10072 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 10073 case NSAPI::NSOrderedSet_insertObjectAtIndex: 10074 return 0; 10075 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 10076 return 1; 10077 } 10078 10079 return None; 10080 } 10081 10082 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 10083 if (!Message->isInstanceMessage()) { 10084 return; 10085 } 10086 10087 Optional<int> ArgOpt; 10088 10089 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 10090 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 10091 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 10092 return; 10093 } 10094 10095 int ArgIndex = *ArgOpt; 10096 10097 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 10098 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 10099 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 10100 } 10101 10102 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 10103 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 10104 if (ArgRE->isObjCSelfExpr()) { 10105 Diag(Message->getSourceRange().getBegin(), 10106 diag::warn_objc_circular_container) 10107 << ArgRE->getDecl()->getName() << StringRef("super"); 10108 } 10109 } 10110 } else { 10111 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 10112 10113 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 10114 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 10115 } 10116 10117 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 10118 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 10119 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 10120 ValueDecl *Decl = ReceiverRE->getDecl(); 10121 Diag(Message->getSourceRange().getBegin(), 10122 diag::warn_objc_circular_container) 10123 << Decl->getName() << Decl->getName(); 10124 if (!ArgRE->isObjCSelfExpr()) { 10125 Diag(Decl->getLocation(), 10126 diag::note_objc_circular_container_declared_here) 10127 << Decl->getName(); 10128 } 10129 } 10130 } 10131 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 10132 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 10133 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 10134 ObjCIvarDecl *Decl = IvarRE->getDecl(); 10135 Diag(Message->getSourceRange().getBegin(), 10136 diag::warn_objc_circular_container) 10137 << Decl->getName() << Decl->getName(); 10138 Diag(Decl->getLocation(), 10139 diag::note_objc_circular_container_declared_here) 10140 << Decl->getName(); 10141 } 10142 } 10143 } 10144 } 10145 } 10146 10147 /// Check a message send to see if it's likely to cause a retain cycle. 10148 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 10149 // Only check instance methods whose selector looks like a setter. 10150 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 10151 return; 10152 10153 // Try to find a variable that the receiver is strongly owned by. 10154 RetainCycleOwner owner; 10155 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 10156 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 10157 return; 10158 } else { 10159 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 10160 owner.Variable = getCurMethodDecl()->getSelfDecl(); 10161 owner.Loc = msg->getSuperLoc(); 10162 owner.Range = msg->getSuperLoc(); 10163 } 10164 10165 // Check whether the receiver is captured by any of the arguments. 10166 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 10167 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 10168 return diagnoseRetainCycle(*this, capturer, owner); 10169 } 10170 10171 /// Check a property assign to see if it's likely to cause a retain cycle. 10172 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 10173 RetainCycleOwner owner; 10174 if (!findRetainCycleOwner(*this, receiver, owner)) 10175 return; 10176 10177 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 10178 diagnoseRetainCycle(*this, capturer, owner); 10179 } 10180 10181 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 10182 RetainCycleOwner Owner; 10183 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 10184 return; 10185 10186 // Because we don't have an expression for the variable, we have to set the 10187 // location explicitly here. 10188 Owner.Loc = Var->getLocation(); 10189 Owner.Range = Var->getSourceRange(); 10190 10191 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 10192 diagnoseRetainCycle(*this, Capturer, Owner); 10193 } 10194 10195 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 10196 Expr *RHS, bool isProperty) { 10197 // Check if RHS is an Objective-C object literal, which also can get 10198 // immediately zapped in a weak reference. Note that we explicitly 10199 // allow ObjCStringLiterals, since those are designed to never really die. 10200 RHS = RHS->IgnoreParenImpCasts(); 10201 10202 // This enum needs to match with the 'select' in 10203 // warn_objc_arc_literal_assign (off-by-1). 10204 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 10205 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 10206 return false; 10207 10208 S.Diag(Loc, diag::warn_arc_literal_assign) 10209 << (unsigned) Kind 10210 << (isProperty ? 0 : 1) 10211 << RHS->getSourceRange(); 10212 10213 return true; 10214 } 10215 10216 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 10217 Qualifiers::ObjCLifetime LT, 10218 Expr *RHS, bool isProperty) { 10219 // Strip off any implicit cast added to get to the one ARC-specific. 10220 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 10221 if (cast->getCastKind() == CK_ARCConsumeObject) { 10222 S.Diag(Loc, diag::warn_arc_retained_assign) 10223 << (LT == Qualifiers::OCL_ExplicitNone) 10224 << (isProperty ? 0 : 1) 10225 << RHS->getSourceRange(); 10226 return true; 10227 } 10228 RHS = cast->getSubExpr(); 10229 } 10230 10231 if (LT == Qualifiers::OCL_Weak && 10232 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 10233 return true; 10234 10235 return false; 10236 } 10237 10238 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 10239 QualType LHS, Expr *RHS) { 10240 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 10241 10242 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 10243 return false; 10244 10245 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 10246 return true; 10247 10248 return false; 10249 } 10250 10251 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 10252 Expr *LHS, Expr *RHS) { 10253 QualType LHSType; 10254 // PropertyRef on LHS type need be directly obtained from 10255 // its declaration as it has a PseudoType. 10256 ObjCPropertyRefExpr *PRE 10257 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 10258 if (PRE && !PRE->isImplicitProperty()) { 10259 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 10260 if (PD) 10261 LHSType = PD->getType(); 10262 } 10263 10264 if (LHSType.isNull()) 10265 LHSType = LHS->getType(); 10266 10267 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 10268 10269 if (LT == Qualifiers::OCL_Weak) { 10270 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 10271 getCurFunction()->markSafeWeakUse(LHS); 10272 } 10273 10274 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 10275 return; 10276 10277 // FIXME. Check for other life times. 10278 if (LT != Qualifiers::OCL_None) 10279 return; 10280 10281 if (PRE) { 10282 if (PRE->isImplicitProperty()) 10283 return; 10284 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 10285 if (!PD) 10286 return; 10287 10288 unsigned Attributes = PD->getPropertyAttributes(); 10289 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 10290 // when 'assign' attribute was not explicitly specified 10291 // by user, ignore it and rely on property type itself 10292 // for lifetime info. 10293 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 10294 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 10295 LHSType->isObjCRetainableType()) 10296 return; 10297 10298 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 10299 if (cast->getCastKind() == CK_ARCConsumeObject) { 10300 Diag(Loc, diag::warn_arc_retained_property_assign) 10301 << RHS->getSourceRange(); 10302 return; 10303 } 10304 RHS = cast->getSubExpr(); 10305 } 10306 } 10307 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 10308 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 10309 return; 10310 } 10311 } 10312 } 10313 10314 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 10315 10316 namespace { 10317 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 10318 SourceLocation StmtLoc, 10319 const NullStmt *Body) { 10320 // Do not warn if the body is a macro that expands to nothing, e.g: 10321 // 10322 // #define CALL(x) 10323 // if (condition) 10324 // CALL(0); 10325 // 10326 if (Body->hasLeadingEmptyMacro()) 10327 return false; 10328 10329 // Get line numbers of statement and body. 10330 bool StmtLineInvalid; 10331 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 10332 &StmtLineInvalid); 10333 if (StmtLineInvalid) 10334 return false; 10335 10336 bool BodyLineInvalid; 10337 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 10338 &BodyLineInvalid); 10339 if (BodyLineInvalid) 10340 return false; 10341 10342 // Warn if null statement and body are on the same line. 10343 if (StmtLine != BodyLine) 10344 return false; 10345 10346 return true; 10347 } 10348 } // end anonymous namespace 10349 10350 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 10351 const Stmt *Body, 10352 unsigned DiagID) { 10353 // Since this is a syntactic check, don't emit diagnostic for template 10354 // instantiations, this just adds noise. 10355 if (CurrentInstantiationScope) 10356 return; 10357 10358 // The body should be a null statement. 10359 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 10360 if (!NBody) 10361 return; 10362 10363 // Do the usual checks. 10364 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 10365 return; 10366 10367 Diag(NBody->getSemiLoc(), DiagID); 10368 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 10369 } 10370 10371 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 10372 const Stmt *PossibleBody) { 10373 assert(!CurrentInstantiationScope); // Ensured by caller 10374 10375 SourceLocation StmtLoc; 10376 const Stmt *Body; 10377 unsigned DiagID; 10378 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 10379 StmtLoc = FS->getRParenLoc(); 10380 Body = FS->getBody(); 10381 DiagID = diag::warn_empty_for_body; 10382 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 10383 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 10384 Body = WS->getBody(); 10385 DiagID = diag::warn_empty_while_body; 10386 } else 10387 return; // Neither `for' nor `while'. 10388 10389 // The body should be a null statement. 10390 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 10391 if (!NBody) 10392 return; 10393 10394 // Skip expensive checks if diagnostic is disabled. 10395 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 10396 return; 10397 10398 // Do the usual checks. 10399 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 10400 return; 10401 10402 // `for(...);' and `while(...);' are popular idioms, so in order to keep 10403 // noise level low, emit diagnostics only if for/while is followed by a 10404 // CompoundStmt, e.g.: 10405 // for (int i = 0; i < n; i++); 10406 // { 10407 // a(i); 10408 // } 10409 // or if for/while is followed by a statement with more indentation 10410 // than for/while itself: 10411 // for (int i = 0; i < n; i++); 10412 // a(i); 10413 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 10414 if (!ProbableTypo) { 10415 bool BodyColInvalid; 10416 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 10417 PossibleBody->getLocStart(), 10418 &BodyColInvalid); 10419 if (BodyColInvalid) 10420 return; 10421 10422 bool StmtColInvalid; 10423 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 10424 S->getLocStart(), 10425 &StmtColInvalid); 10426 if (StmtColInvalid) 10427 return; 10428 10429 if (BodyCol > StmtCol) 10430 ProbableTypo = true; 10431 } 10432 10433 if (ProbableTypo) { 10434 Diag(NBody->getSemiLoc(), DiagID); 10435 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 10436 } 10437 } 10438 10439 //===--- CHECK: Warn on self move with std::move. -------------------------===// 10440 10441 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 10442 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 10443 SourceLocation OpLoc) { 10444 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 10445 return; 10446 10447 if (!ActiveTemplateInstantiations.empty()) 10448 return; 10449 10450 // Strip parens and casts away. 10451 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10452 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10453 10454 // Check for a call expression 10455 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 10456 if (!CE || CE->getNumArgs() != 1) 10457 return; 10458 10459 // Check for a call to std::move 10460 const FunctionDecl *FD = CE->getDirectCallee(); 10461 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() || 10462 !FD->getIdentifier()->isStr("move")) 10463 return; 10464 10465 // Get argument from std::move 10466 RHSExpr = CE->getArg(0); 10467 10468 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10469 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10470 10471 // Two DeclRefExpr's, check that the decls are the same. 10472 if (LHSDeclRef && RHSDeclRef) { 10473 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 10474 return; 10475 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 10476 RHSDeclRef->getDecl()->getCanonicalDecl()) 10477 return; 10478 10479 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 10480 << LHSExpr->getSourceRange() 10481 << RHSExpr->getSourceRange(); 10482 return; 10483 } 10484 10485 // Member variables require a different approach to check for self moves. 10486 // MemberExpr's are the same if every nested MemberExpr refers to the same 10487 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 10488 // the base Expr's are CXXThisExpr's. 10489 const Expr *LHSBase = LHSExpr; 10490 const Expr *RHSBase = RHSExpr; 10491 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 10492 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 10493 if (!LHSME || !RHSME) 10494 return; 10495 10496 while (LHSME && RHSME) { 10497 if (LHSME->getMemberDecl()->getCanonicalDecl() != 10498 RHSME->getMemberDecl()->getCanonicalDecl()) 10499 return; 10500 10501 LHSBase = LHSME->getBase(); 10502 RHSBase = RHSME->getBase(); 10503 LHSME = dyn_cast<MemberExpr>(LHSBase); 10504 RHSME = dyn_cast<MemberExpr>(RHSBase); 10505 } 10506 10507 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 10508 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 10509 if (LHSDeclRef && RHSDeclRef) { 10510 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 10511 return; 10512 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 10513 RHSDeclRef->getDecl()->getCanonicalDecl()) 10514 return; 10515 10516 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 10517 << LHSExpr->getSourceRange() 10518 << RHSExpr->getSourceRange(); 10519 return; 10520 } 10521 10522 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 10523 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 10524 << LHSExpr->getSourceRange() 10525 << RHSExpr->getSourceRange(); 10526 } 10527 10528 //===--- Layout compatibility ----------------------------------------------// 10529 10530 namespace { 10531 10532 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 10533 10534 /// \brief Check if two enumeration types are layout-compatible. 10535 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 10536 // C++11 [dcl.enum] p8: 10537 // Two enumeration types are layout-compatible if they have the same 10538 // underlying type. 10539 return ED1->isComplete() && ED2->isComplete() && 10540 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 10541 } 10542 10543 /// \brief Check if two fields are layout-compatible. 10544 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 10545 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 10546 return false; 10547 10548 if (Field1->isBitField() != Field2->isBitField()) 10549 return false; 10550 10551 if (Field1->isBitField()) { 10552 // Make sure that the bit-fields are the same length. 10553 unsigned Bits1 = Field1->getBitWidthValue(C); 10554 unsigned Bits2 = Field2->getBitWidthValue(C); 10555 10556 if (Bits1 != Bits2) 10557 return false; 10558 } 10559 10560 return true; 10561 } 10562 10563 /// \brief Check if two standard-layout structs are layout-compatible. 10564 /// (C++11 [class.mem] p17) 10565 bool isLayoutCompatibleStruct(ASTContext &C, 10566 RecordDecl *RD1, 10567 RecordDecl *RD2) { 10568 // If both records are C++ classes, check that base classes match. 10569 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 10570 // If one of records is a CXXRecordDecl we are in C++ mode, 10571 // thus the other one is a CXXRecordDecl, too. 10572 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 10573 // Check number of base classes. 10574 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 10575 return false; 10576 10577 // Check the base classes. 10578 for (CXXRecordDecl::base_class_const_iterator 10579 Base1 = D1CXX->bases_begin(), 10580 BaseEnd1 = D1CXX->bases_end(), 10581 Base2 = D2CXX->bases_begin(); 10582 Base1 != BaseEnd1; 10583 ++Base1, ++Base2) { 10584 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 10585 return false; 10586 } 10587 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 10588 // If only RD2 is a C++ class, it should have zero base classes. 10589 if (D2CXX->getNumBases() > 0) 10590 return false; 10591 } 10592 10593 // Check the fields. 10594 RecordDecl::field_iterator Field2 = RD2->field_begin(), 10595 Field2End = RD2->field_end(), 10596 Field1 = RD1->field_begin(), 10597 Field1End = RD1->field_end(); 10598 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 10599 if (!isLayoutCompatible(C, *Field1, *Field2)) 10600 return false; 10601 } 10602 if (Field1 != Field1End || Field2 != Field2End) 10603 return false; 10604 10605 return true; 10606 } 10607 10608 /// \brief Check if two standard-layout unions are layout-compatible. 10609 /// (C++11 [class.mem] p18) 10610 bool isLayoutCompatibleUnion(ASTContext &C, 10611 RecordDecl *RD1, 10612 RecordDecl *RD2) { 10613 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 10614 for (auto *Field2 : RD2->fields()) 10615 UnmatchedFields.insert(Field2); 10616 10617 for (auto *Field1 : RD1->fields()) { 10618 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 10619 I = UnmatchedFields.begin(), 10620 E = UnmatchedFields.end(); 10621 10622 for ( ; I != E; ++I) { 10623 if (isLayoutCompatible(C, Field1, *I)) { 10624 bool Result = UnmatchedFields.erase(*I); 10625 (void) Result; 10626 assert(Result); 10627 break; 10628 } 10629 } 10630 if (I == E) 10631 return false; 10632 } 10633 10634 return UnmatchedFields.empty(); 10635 } 10636 10637 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 10638 if (RD1->isUnion() != RD2->isUnion()) 10639 return false; 10640 10641 if (RD1->isUnion()) 10642 return isLayoutCompatibleUnion(C, RD1, RD2); 10643 else 10644 return isLayoutCompatibleStruct(C, RD1, RD2); 10645 } 10646 10647 /// \brief Check if two types are layout-compatible in C++11 sense. 10648 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 10649 if (T1.isNull() || T2.isNull()) 10650 return false; 10651 10652 // C++11 [basic.types] p11: 10653 // If two types T1 and T2 are the same type, then T1 and T2 are 10654 // layout-compatible types. 10655 if (C.hasSameType(T1, T2)) 10656 return true; 10657 10658 T1 = T1.getCanonicalType().getUnqualifiedType(); 10659 T2 = T2.getCanonicalType().getUnqualifiedType(); 10660 10661 const Type::TypeClass TC1 = T1->getTypeClass(); 10662 const Type::TypeClass TC2 = T2->getTypeClass(); 10663 10664 if (TC1 != TC2) 10665 return false; 10666 10667 if (TC1 == Type::Enum) { 10668 return isLayoutCompatible(C, 10669 cast<EnumType>(T1)->getDecl(), 10670 cast<EnumType>(T2)->getDecl()); 10671 } else if (TC1 == Type::Record) { 10672 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 10673 return false; 10674 10675 return isLayoutCompatible(C, 10676 cast<RecordType>(T1)->getDecl(), 10677 cast<RecordType>(T2)->getDecl()); 10678 } 10679 10680 return false; 10681 } 10682 } // end anonymous namespace 10683 10684 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 10685 10686 namespace { 10687 /// \brief Given a type tag expression find the type tag itself. 10688 /// 10689 /// \param TypeExpr Type tag expression, as it appears in user's code. 10690 /// 10691 /// \param VD Declaration of an identifier that appears in a type tag. 10692 /// 10693 /// \param MagicValue Type tag magic value. 10694 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 10695 const ValueDecl **VD, uint64_t *MagicValue) { 10696 while(true) { 10697 if (!TypeExpr) 10698 return false; 10699 10700 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 10701 10702 switch (TypeExpr->getStmtClass()) { 10703 case Stmt::UnaryOperatorClass: { 10704 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 10705 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 10706 TypeExpr = UO->getSubExpr(); 10707 continue; 10708 } 10709 return false; 10710 } 10711 10712 case Stmt::DeclRefExprClass: { 10713 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 10714 *VD = DRE->getDecl(); 10715 return true; 10716 } 10717 10718 case Stmt::IntegerLiteralClass: { 10719 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 10720 llvm::APInt MagicValueAPInt = IL->getValue(); 10721 if (MagicValueAPInt.getActiveBits() <= 64) { 10722 *MagicValue = MagicValueAPInt.getZExtValue(); 10723 return true; 10724 } else 10725 return false; 10726 } 10727 10728 case Stmt::BinaryConditionalOperatorClass: 10729 case Stmt::ConditionalOperatorClass: { 10730 const AbstractConditionalOperator *ACO = 10731 cast<AbstractConditionalOperator>(TypeExpr); 10732 bool Result; 10733 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 10734 if (Result) 10735 TypeExpr = ACO->getTrueExpr(); 10736 else 10737 TypeExpr = ACO->getFalseExpr(); 10738 continue; 10739 } 10740 return false; 10741 } 10742 10743 case Stmt::BinaryOperatorClass: { 10744 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 10745 if (BO->getOpcode() == BO_Comma) { 10746 TypeExpr = BO->getRHS(); 10747 continue; 10748 } 10749 return false; 10750 } 10751 10752 default: 10753 return false; 10754 } 10755 } 10756 } 10757 10758 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 10759 /// 10760 /// \param TypeExpr Expression that specifies a type tag. 10761 /// 10762 /// \param MagicValues Registered magic values. 10763 /// 10764 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 10765 /// kind. 10766 /// 10767 /// \param TypeInfo Information about the corresponding C type. 10768 /// 10769 /// \returns true if the corresponding C type was found. 10770 bool GetMatchingCType( 10771 const IdentifierInfo *ArgumentKind, 10772 const Expr *TypeExpr, const ASTContext &Ctx, 10773 const llvm::DenseMap<Sema::TypeTagMagicValue, 10774 Sema::TypeTagData> *MagicValues, 10775 bool &FoundWrongKind, 10776 Sema::TypeTagData &TypeInfo) { 10777 FoundWrongKind = false; 10778 10779 // Variable declaration that has type_tag_for_datatype attribute. 10780 const ValueDecl *VD = nullptr; 10781 10782 uint64_t MagicValue; 10783 10784 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 10785 return false; 10786 10787 if (VD) { 10788 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 10789 if (I->getArgumentKind() != ArgumentKind) { 10790 FoundWrongKind = true; 10791 return false; 10792 } 10793 TypeInfo.Type = I->getMatchingCType(); 10794 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 10795 TypeInfo.MustBeNull = I->getMustBeNull(); 10796 return true; 10797 } 10798 return false; 10799 } 10800 10801 if (!MagicValues) 10802 return false; 10803 10804 llvm::DenseMap<Sema::TypeTagMagicValue, 10805 Sema::TypeTagData>::const_iterator I = 10806 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 10807 if (I == MagicValues->end()) 10808 return false; 10809 10810 TypeInfo = I->second; 10811 return true; 10812 } 10813 } // end anonymous namespace 10814 10815 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 10816 uint64_t MagicValue, QualType Type, 10817 bool LayoutCompatible, 10818 bool MustBeNull) { 10819 if (!TypeTagForDatatypeMagicValues) 10820 TypeTagForDatatypeMagicValues.reset( 10821 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 10822 10823 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 10824 (*TypeTagForDatatypeMagicValues)[Magic] = 10825 TypeTagData(Type, LayoutCompatible, MustBeNull); 10826 } 10827 10828 namespace { 10829 bool IsSameCharType(QualType T1, QualType T2) { 10830 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 10831 if (!BT1) 10832 return false; 10833 10834 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 10835 if (!BT2) 10836 return false; 10837 10838 BuiltinType::Kind T1Kind = BT1->getKind(); 10839 BuiltinType::Kind T2Kind = BT2->getKind(); 10840 10841 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 10842 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 10843 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 10844 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 10845 } 10846 } // end anonymous namespace 10847 10848 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 10849 const Expr * const *ExprArgs) { 10850 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 10851 bool IsPointerAttr = Attr->getIsPointer(); 10852 10853 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 10854 bool FoundWrongKind; 10855 TypeTagData TypeInfo; 10856 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 10857 TypeTagForDatatypeMagicValues.get(), 10858 FoundWrongKind, TypeInfo)) { 10859 if (FoundWrongKind) 10860 Diag(TypeTagExpr->getExprLoc(), 10861 diag::warn_type_tag_for_datatype_wrong_kind) 10862 << TypeTagExpr->getSourceRange(); 10863 return; 10864 } 10865 10866 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 10867 if (IsPointerAttr) { 10868 // Skip implicit cast of pointer to `void *' (as a function argument). 10869 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 10870 if (ICE->getType()->isVoidPointerType() && 10871 ICE->getCastKind() == CK_BitCast) 10872 ArgumentExpr = ICE->getSubExpr(); 10873 } 10874 QualType ArgumentType = ArgumentExpr->getType(); 10875 10876 // Passing a `void*' pointer shouldn't trigger a warning. 10877 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 10878 return; 10879 10880 if (TypeInfo.MustBeNull) { 10881 // Type tag with matching void type requires a null pointer. 10882 if (!ArgumentExpr->isNullPointerConstant(Context, 10883 Expr::NPC_ValueDependentIsNotNull)) { 10884 Diag(ArgumentExpr->getExprLoc(), 10885 diag::warn_type_safety_null_pointer_required) 10886 << ArgumentKind->getName() 10887 << ArgumentExpr->getSourceRange() 10888 << TypeTagExpr->getSourceRange(); 10889 } 10890 return; 10891 } 10892 10893 QualType RequiredType = TypeInfo.Type; 10894 if (IsPointerAttr) 10895 RequiredType = Context.getPointerType(RequiredType); 10896 10897 bool mismatch = false; 10898 if (!TypeInfo.LayoutCompatible) { 10899 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 10900 10901 // C++11 [basic.fundamental] p1: 10902 // Plain char, signed char, and unsigned char are three distinct types. 10903 // 10904 // But we treat plain `char' as equivalent to `signed char' or `unsigned 10905 // char' depending on the current char signedness mode. 10906 if (mismatch) 10907 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 10908 RequiredType->getPointeeType())) || 10909 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 10910 mismatch = false; 10911 } else 10912 if (IsPointerAttr) 10913 mismatch = !isLayoutCompatible(Context, 10914 ArgumentType->getPointeeType(), 10915 RequiredType->getPointeeType()); 10916 else 10917 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 10918 10919 if (mismatch) 10920 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 10921 << ArgumentType << ArgumentKind 10922 << TypeInfo.LayoutCompatible << RequiredType 10923 << ArgumentExpr->getSourceRange() 10924 << TypeTagExpr->getSourceRange(); 10925 } 10926