1 //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements extra semantic analysis beyond what is enforced 11 // by the C type system. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CharUnits.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/DeclObjC.h" 19 #include "clang/AST/EvaluatedExprVisitor.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/ExprObjC.h" 23 #include "clang/AST/ExprOpenMP.h" 24 #include "clang/AST/StmtCXX.h" 25 #include "clang/AST/StmtObjC.h" 26 #include "clang/Analysis/Analyses/FormatString.h" 27 #include "clang/Basic/CharInfo.h" 28 #include "clang/Basic/TargetBuiltins.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 31 #include "clang/Sema/Initialization.h" 32 #include "clang/Sema/Lookup.h" 33 #include "clang/Sema/ScopeInfo.h" 34 #include "clang/Sema/Sema.h" 35 #include "clang/Sema/SemaInternal.h" 36 #include "llvm/ADT/STLExtras.h" 37 #include "llvm/ADT/SmallBitVector.h" 38 #include "llvm/ADT/SmallString.h" 39 #include "llvm/Support/ConvertUTF.h" 40 #include "llvm/Support/Format.h" 41 #include "llvm/Support/Locale.h" 42 #include "llvm/Support/raw_ostream.h" 43 44 using namespace clang; 45 using namespace sema; 46 47 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 48 unsigned ByteNo) const { 49 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 50 Context.getTargetInfo()); 51 } 52 53 /// Checks that a call expression's argument count is the desired number. 54 /// This is useful when doing custom type-checking. Returns true on error. 55 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 56 unsigned argCount = call->getNumArgs(); 57 if (argCount == desiredArgCount) return false; 58 59 if (argCount < desiredArgCount) 60 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 61 << 0 /*function call*/ << desiredArgCount << argCount 62 << call->getSourceRange(); 63 64 // Highlight all the excess arguments. 65 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 66 call->getArg(argCount - 1)->getLocEnd()); 67 68 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 69 << 0 /*function call*/ << desiredArgCount << argCount 70 << call->getArg(1)->getSourceRange(); 71 } 72 73 /// Check that the first argument to __builtin_annotation is an integer 74 /// and the second argument is a non-wide string literal. 75 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 76 if (checkArgCount(S, TheCall, 2)) 77 return true; 78 79 // First argument should be an integer. 80 Expr *ValArg = TheCall->getArg(0); 81 QualType Ty = ValArg->getType(); 82 if (!Ty->isIntegerType()) { 83 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 84 << ValArg->getSourceRange(); 85 return true; 86 } 87 88 // Second argument should be a constant string. 89 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 90 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 91 if (!Literal || !Literal->isAscii()) { 92 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 93 << StrArg->getSourceRange(); 94 return true; 95 } 96 97 TheCall->setType(Ty); 98 return false; 99 } 100 101 /// Check that the argument to __builtin_addressof is a glvalue, and set the 102 /// result type to the corresponding pointer type. 103 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 104 if (checkArgCount(S, TheCall, 1)) 105 return true; 106 107 ExprResult Arg(TheCall->getArg(0)); 108 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 109 if (ResultType.isNull()) 110 return true; 111 112 TheCall->setArg(0, Arg.get()); 113 TheCall->setType(ResultType); 114 return false; 115 } 116 117 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 118 if (checkArgCount(S, TheCall, 3)) 119 return true; 120 121 // First two arguments should be integers. 122 for (unsigned I = 0; I < 2; ++I) { 123 Expr *Arg = TheCall->getArg(I); 124 QualType Ty = Arg->getType(); 125 if (!Ty->isIntegerType()) { 126 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int) 127 << Ty << Arg->getSourceRange(); 128 return true; 129 } 130 } 131 132 // Third argument should be a pointer to a non-const integer. 133 // IRGen correctly handles volatile, restrict, and address spaces, and 134 // the other qualifiers aren't possible. 135 { 136 Expr *Arg = TheCall->getArg(2); 137 QualType Ty = Arg->getType(); 138 const auto *PtrTy = Ty->getAs<PointerType>(); 139 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 140 !PtrTy->getPointeeType().isConstQualified())) { 141 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int) 142 << Ty << Arg->getSourceRange(); 143 return true; 144 } 145 } 146 147 return false; 148 } 149 150 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 151 CallExpr *TheCall, unsigned SizeIdx, 152 unsigned DstSizeIdx) { 153 if (TheCall->getNumArgs() <= SizeIdx || 154 TheCall->getNumArgs() <= DstSizeIdx) 155 return; 156 157 const Expr *SizeArg = TheCall->getArg(SizeIdx); 158 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 159 160 llvm::APSInt Size, DstSize; 161 162 // find out if both sizes are known at compile time 163 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 164 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 165 return; 166 167 if (Size.ule(DstSize)) 168 return; 169 170 // confirmed overflow so generate the diagnostic. 171 IdentifierInfo *FnName = FDecl->getIdentifier(); 172 SourceLocation SL = TheCall->getLocStart(); 173 SourceRange SR = TheCall->getSourceRange(); 174 175 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; 176 } 177 178 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 179 if (checkArgCount(S, BuiltinCall, 2)) 180 return true; 181 182 SourceLocation BuiltinLoc = BuiltinCall->getLocStart(); 183 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 184 Expr *Call = BuiltinCall->getArg(0); 185 Expr *Chain = BuiltinCall->getArg(1); 186 187 if (Call->getStmtClass() != Stmt::CallExprClass) { 188 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 189 << Call->getSourceRange(); 190 return true; 191 } 192 193 auto CE = cast<CallExpr>(Call); 194 if (CE->getCallee()->getType()->isBlockPointerType()) { 195 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 196 << Call->getSourceRange(); 197 return true; 198 } 199 200 const Decl *TargetDecl = CE->getCalleeDecl(); 201 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 202 if (FD->getBuiltinID()) { 203 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 204 << Call->getSourceRange(); 205 return true; 206 } 207 208 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 209 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 210 << Call->getSourceRange(); 211 return true; 212 } 213 214 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 215 if (ChainResult.isInvalid()) 216 return true; 217 if (!ChainResult.get()->getType()->isPointerType()) { 218 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 219 << Chain->getSourceRange(); 220 return true; 221 } 222 223 QualType ReturnTy = CE->getCallReturnType(S.Context); 224 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 225 QualType BuiltinTy = S.Context.getFunctionType( 226 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 227 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 228 229 Builtin = 230 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 231 232 BuiltinCall->setType(CE->getType()); 233 BuiltinCall->setValueKind(CE->getValueKind()); 234 BuiltinCall->setObjectKind(CE->getObjectKind()); 235 BuiltinCall->setCallee(Builtin); 236 BuiltinCall->setArg(1, ChainResult.get()); 237 238 return false; 239 } 240 241 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 242 Scope::ScopeFlags NeededScopeFlags, 243 unsigned DiagID) { 244 // Scopes aren't available during instantiation. Fortunately, builtin 245 // functions cannot be template args so they cannot be formed through template 246 // instantiation. Therefore checking once during the parse is sufficient. 247 if (!SemaRef.ActiveTemplateInstantiations.empty()) 248 return false; 249 250 Scope *S = SemaRef.getCurScope(); 251 while (S && !S->isSEHExceptScope()) 252 S = S->getParent(); 253 if (!S || !(S->getFlags() & NeededScopeFlags)) { 254 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 255 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 256 << DRE->getDecl()->getIdentifier(); 257 return true; 258 } 259 260 return false; 261 } 262 263 static inline bool isBlockPointer(Expr *Arg) { 264 return Arg->getType()->isBlockPointerType(); 265 } 266 267 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 268 /// void*, which is a requirement of device side enqueue. 269 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 270 const BlockPointerType *BPT = 271 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 272 ArrayRef<QualType> Params = 273 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 274 unsigned ArgCounter = 0; 275 bool IllegalParams = false; 276 // Iterate through the block parameters until either one is found that is not 277 // a local void*, or the block is valid. 278 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 279 I != E; ++I, ++ArgCounter) { 280 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 281 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 282 LangAS::opencl_local) { 283 // Get the location of the error. If a block literal has been passed 284 // (BlockExpr) then we can point straight to the offending argument, 285 // else we just point to the variable reference. 286 SourceLocation ErrorLoc; 287 if (isa<BlockExpr>(BlockArg)) { 288 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 289 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart(); 290 } else if (isa<DeclRefExpr>(BlockArg)) { 291 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart(); 292 } 293 S.Diag(ErrorLoc, 294 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 295 IllegalParams = true; 296 } 297 } 298 299 return IllegalParams; 300 } 301 302 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 303 /// get_kernel_work_group_size 304 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 305 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 306 if (checkArgCount(S, TheCall, 1)) 307 return true; 308 309 Expr *BlockArg = TheCall->getArg(0); 310 if (!isBlockPointer(BlockArg)) { 311 S.Diag(BlockArg->getLocStart(), 312 diag::err_opencl_enqueue_kernel_expected_type) << "block"; 313 return true; 314 } 315 return checkOpenCLBlockArgs(S, BlockArg); 316 } 317 318 /// Diagnose integer type and any valid implicit convertion to it. 319 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 320 const QualType &IntType); 321 322 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 323 unsigned Start, unsigned End) { 324 bool IllegalParams = false; 325 for (unsigned I = Start; I <= End; ++I) 326 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 327 S.Context.getSizeType()); 328 return IllegalParams; 329 } 330 331 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 332 /// 'local void*' parameter of passed block. 333 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 334 Expr *BlockArg, 335 unsigned NumNonVarArgs) { 336 const BlockPointerType *BPT = 337 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 338 unsigned NumBlockParams = 339 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 340 unsigned TotalNumArgs = TheCall->getNumArgs(); 341 342 // For each argument passed to the block, a corresponding uint needs to 343 // be passed to describe the size of the local memory. 344 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 345 S.Diag(TheCall->getLocStart(), 346 diag::err_opencl_enqueue_kernel_local_size_args); 347 return true; 348 } 349 350 // Check that the sizes of the local memory are specified by integers. 351 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 352 TotalNumArgs - 1); 353 } 354 355 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 356 /// overload formats specified in Table 6.13.17.1. 357 /// int enqueue_kernel(queue_t queue, 358 /// kernel_enqueue_flags_t flags, 359 /// const ndrange_t ndrange, 360 /// void (^block)(void)) 361 /// int enqueue_kernel(queue_t queue, 362 /// kernel_enqueue_flags_t flags, 363 /// const ndrange_t ndrange, 364 /// uint num_events_in_wait_list, 365 /// clk_event_t *event_wait_list, 366 /// clk_event_t *event_ret, 367 /// void (^block)(void)) 368 /// int enqueue_kernel(queue_t queue, 369 /// kernel_enqueue_flags_t flags, 370 /// const ndrange_t ndrange, 371 /// void (^block)(local void*, ...), 372 /// uint size0, ...) 373 /// int enqueue_kernel(queue_t queue, 374 /// kernel_enqueue_flags_t flags, 375 /// const ndrange_t ndrange, 376 /// uint num_events_in_wait_list, 377 /// clk_event_t *event_wait_list, 378 /// clk_event_t *event_ret, 379 /// void (^block)(local void*, ...), 380 /// uint size0, ...) 381 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 382 unsigned NumArgs = TheCall->getNumArgs(); 383 384 if (NumArgs < 4) { 385 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args); 386 return true; 387 } 388 389 Expr *Arg0 = TheCall->getArg(0); 390 Expr *Arg1 = TheCall->getArg(1); 391 Expr *Arg2 = TheCall->getArg(2); 392 Expr *Arg3 = TheCall->getArg(3); 393 394 // First argument always needs to be a queue_t type. 395 if (!Arg0->getType()->isQueueT()) { 396 S.Diag(TheCall->getArg(0)->getLocStart(), 397 diag::err_opencl_enqueue_kernel_expected_type) 398 << S.Context.OCLQueueTy; 399 return true; 400 } 401 402 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 403 if (!Arg1->getType()->isIntegerType()) { 404 S.Diag(TheCall->getArg(1)->getLocStart(), 405 diag::err_opencl_enqueue_kernel_expected_type) 406 << "'kernel_enqueue_flags_t' (i.e. uint)"; 407 return true; 408 } 409 410 // Third argument is always an ndrange_t type. 411 if (!Arg2->getType()->isNDRangeT()) { 412 S.Diag(TheCall->getArg(2)->getLocStart(), 413 diag::err_opencl_enqueue_kernel_expected_type) 414 << S.Context.OCLNDRangeTy; 415 return true; 416 } 417 418 // With four arguments, there is only one form that the function could be 419 // called in: no events and no variable arguments. 420 if (NumArgs == 4) { 421 // check that the last argument is the right block type. 422 if (!isBlockPointer(Arg3)) { 423 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type) 424 << "block"; 425 return true; 426 } 427 // we have a block type, check the prototype 428 const BlockPointerType *BPT = 429 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 430 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 431 S.Diag(Arg3->getLocStart(), 432 diag::err_opencl_enqueue_kernel_blocks_no_args); 433 return true; 434 } 435 return false; 436 } 437 // we can have block + varargs. 438 if (isBlockPointer(Arg3)) 439 return (checkOpenCLBlockArgs(S, Arg3) || 440 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 441 // last two cases with either exactly 7 args or 7 args and varargs. 442 if (NumArgs >= 7) { 443 // check common block argument. 444 Expr *Arg6 = TheCall->getArg(6); 445 if (!isBlockPointer(Arg6)) { 446 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type) 447 << "block"; 448 return true; 449 } 450 if (checkOpenCLBlockArgs(S, Arg6)) 451 return true; 452 453 // Forth argument has to be any integer type. 454 if (!Arg3->getType()->isIntegerType()) { 455 S.Diag(TheCall->getArg(3)->getLocStart(), 456 diag::err_opencl_enqueue_kernel_expected_type) 457 << "integer"; 458 return true; 459 } 460 // check remaining common arguments. 461 Expr *Arg4 = TheCall->getArg(4); 462 Expr *Arg5 = TheCall->getArg(5); 463 464 // Fifth argument is always passed as a pointer to clk_event_t. 465 if (!Arg4->isNullPointerConstant(S.Context, 466 Expr::NPC_ValueDependentIsNotNull) && 467 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 468 S.Diag(TheCall->getArg(4)->getLocStart(), 469 diag::err_opencl_enqueue_kernel_expected_type) 470 << S.Context.getPointerType(S.Context.OCLClkEventTy); 471 return true; 472 } 473 474 // Sixth argument is always passed as a pointer to clk_event_t. 475 if (!Arg5->isNullPointerConstant(S.Context, 476 Expr::NPC_ValueDependentIsNotNull) && 477 !(Arg5->getType()->isPointerType() && 478 Arg5->getType()->getPointeeType()->isClkEventT())) { 479 S.Diag(TheCall->getArg(5)->getLocStart(), 480 diag::err_opencl_enqueue_kernel_expected_type) 481 << S.Context.getPointerType(S.Context.OCLClkEventTy); 482 return true; 483 } 484 485 if (NumArgs == 7) 486 return false; 487 488 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 489 } 490 491 // None of the specific case has been detected, give generic error 492 S.Diag(TheCall->getLocStart(), 493 diag::err_opencl_enqueue_kernel_incorrect_args); 494 return true; 495 } 496 497 /// Returns OpenCL access qual. 498 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 499 return D->getAttr<OpenCLAccessAttr>(); 500 } 501 502 /// Returns true if pipe element type is different from the pointer. 503 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 504 const Expr *Arg0 = Call->getArg(0); 505 // First argument type should always be pipe. 506 if (!Arg0->getType()->isPipeType()) { 507 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 508 << Call->getDirectCallee() << Arg0->getSourceRange(); 509 return true; 510 } 511 OpenCLAccessAttr *AccessQual = 512 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 513 // Validates the access qualifier is compatible with the call. 514 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 515 // read_only and write_only, and assumed to be read_only if no qualifier is 516 // specified. 517 switch (Call->getDirectCallee()->getBuiltinID()) { 518 case Builtin::BIread_pipe: 519 case Builtin::BIreserve_read_pipe: 520 case Builtin::BIcommit_read_pipe: 521 case Builtin::BIwork_group_reserve_read_pipe: 522 case Builtin::BIsub_group_reserve_read_pipe: 523 case Builtin::BIwork_group_commit_read_pipe: 524 case Builtin::BIsub_group_commit_read_pipe: 525 if (!(!AccessQual || AccessQual->isReadOnly())) { 526 S.Diag(Arg0->getLocStart(), 527 diag::err_opencl_builtin_pipe_invalid_access_modifier) 528 << "read_only" << Arg0->getSourceRange(); 529 return true; 530 } 531 break; 532 case Builtin::BIwrite_pipe: 533 case Builtin::BIreserve_write_pipe: 534 case Builtin::BIcommit_write_pipe: 535 case Builtin::BIwork_group_reserve_write_pipe: 536 case Builtin::BIsub_group_reserve_write_pipe: 537 case Builtin::BIwork_group_commit_write_pipe: 538 case Builtin::BIsub_group_commit_write_pipe: 539 if (!(AccessQual && AccessQual->isWriteOnly())) { 540 S.Diag(Arg0->getLocStart(), 541 diag::err_opencl_builtin_pipe_invalid_access_modifier) 542 << "write_only" << Arg0->getSourceRange(); 543 return true; 544 } 545 break; 546 default: 547 break; 548 } 549 return false; 550 } 551 552 /// Returns true if pipe element type is different from the pointer. 553 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 554 const Expr *Arg0 = Call->getArg(0); 555 const Expr *ArgIdx = Call->getArg(Idx); 556 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 557 const QualType EltTy = PipeTy->getElementType(); 558 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 559 // The Idx argument should be a pointer and the type of the pointer and 560 // the type of pipe element should also be the same. 561 if (!ArgTy || 562 !S.Context.hasSameType( 563 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 564 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 565 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 566 << ArgIdx->getType() << ArgIdx->getSourceRange(); 567 return true; 568 } 569 return false; 570 } 571 572 // \brief Performs semantic analysis for the read/write_pipe call. 573 // \param S Reference to the semantic analyzer. 574 // \param Call A pointer to the builtin call. 575 // \return True if a semantic error has been found, false otherwise. 576 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 577 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 578 // functions have two forms. 579 switch (Call->getNumArgs()) { 580 case 2: { 581 if (checkOpenCLPipeArg(S, Call)) 582 return true; 583 // The call with 2 arguments should be 584 // read/write_pipe(pipe T, T*). 585 // Check packet type T. 586 if (checkOpenCLPipePacketType(S, Call, 1)) 587 return true; 588 } break; 589 590 case 4: { 591 if (checkOpenCLPipeArg(S, Call)) 592 return true; 593 // The call with 4 arguments should be 594 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 595 // Check reserve_id_t. 596 if (!Call->getArg(1)->getType()->isReserveIDT()) { 597 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 598 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 599 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 600 return true; 601 } 602 603 // Check the index. 604 const Expr *Arg2 = Call->getArg(2); 605 if (!Arg2->getType()->isIntegerType() && 606 !Arg2->getType()->isUnsignedIntegerType()) { 607 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 608 << Call->getDirectCallee() << S.Context.UnsignedIntTy 609 << Arg2->getType() << Arg2->getSourceRange(); 610 return true; 611 } 612 613 // Check packet type T. 614 if (checkOpenCLPipePacketType(S, Call, 3)) 615 return true; 616 } break; 617 default: 618 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) 619 << Call->getDirectCallee() << Call->getSourceRange(); 620 return true; 621 } 622 623 return false; 624 } 625 626 // \brief Performs a semantic analysis on the {work_group_/sub_group_ 627 // /_}reserve_{read/write}_pipe 628 // \param S Reference to the semantic analyzer. 629 // \param Call The call to the builtin function to be analyzed. 630 // \return True if a semantic error was found, false otherwise. 631 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 632 if (checkArgCount(S, Call, 2)) 633 return true; 634 635 if (checkOpenCLPipeArg(S, Call)) 636 return true; 637 638 // Check the reserve size. 639 if (!Call->getArg(1)->getType()->isIntegerType() && 640 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 641 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 642 << Call->getDirectCallee() << S.Context.UnsignedIntTy 643 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 644 return true; 645 } 646 647 return false; 648 } 649 650 // \brief Performs a semantic analysis on {work_group_/sub_group_ 651 // /_}commit_{read/write}_pipe 652 // \param S Reference to the semantic analyzer. 653 // \param Call The call to the builtin function to be analyzed. 654 // \return True if a semantic error was found, false otherwise. 655 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 656 if (checkArgCount(S, Call, 2)) 657 return true; 658 659 if (checkOpenCLPipeArg(S, Call)) 660 return true; 661 662 // Check reserve_id_t. 663 if (!Call->getArg(1)->getType()->isReserveIDT()) { 664 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 665 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 666 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 667 return true; 668 } 669 670 return false; 671 } 672 673 // \brief Performs a semantic analysis on the call to built-in Pipe 674 // Query Functions. 675 // \param S Reference to the semantic analyzer. 676 // \param Call The call to the builtin function to be analyzed. 677 // \return True if a semantic error was found, false otherwise. 678 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 679 if (checkArgCount(S, Call, 1)) 680 return true; 681 682 if (!Call->getArg(0)->getType()->isPipeType()) { 683 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 684 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 685 return true; 686 } 687 688 return false; 689 } 690 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions. 691 // \brief Performs semantic analysis for the to_global/local/private call. 692 // \param S Reference to the semantic analyzer. 693 // \param BuiltinID ID of the builtin function. 694 // \param Call A pointer to the builtin call. 695 // \return True if a semantic error has been found, false otherwise. 696 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 697 CallExpr *Call) { 698 if (Call->getNumArgs() != 1) { 699 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 700 << Call->getDirectCallee() << Call->getSourceRange(); 701 return true; 702 } 703 704 auto RT = Call->getArg(0)->getType(); 705 if (!RT->isPointerType() || RT->getPointeeType() 706 .getAddressSpace() == LangAS::opencl_constant) { 707 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 708 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 709 return true; 710 } 711 712 RT = RT->getPointeeType(); 713 auto Qual = RT.getQualifiers(); 714 switch (BuiltinID) { 715 case Builtin::BIto_global: 716 Qual.setAddressSpace(LangAS::opencl_global); 717 break; 718 case Builtin::BIto_local: 719 Qual.setAddressSpace(LangAS::opencl_local); 720 break; 721 default: 722 Qual.removeAddressSpace(); 723 } 724 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 725 RT.getUnqualifiedType(), Qual))); 726 727 return false; 728 } 729 730 ExprResult 731 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 732 CallExpr *TheCall) { 733 ExprResult TheCallResult(TheCall); 734 735 // Find out if any arguments are required to be integer constant expressions. 736 unsigned ICEArguments = 0; 737 ASTContext::GetBuiltinTypeError Error; 738 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 739 if (Error != ASTContext::GE_None) 740 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 741 742 // If any arguments are required to be ICE's, check and diagnose. 743 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 744 // Skip arguments not required to be ICE's. 745 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 746 747 llvm::APSInt Result; 748 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 749 return true; 750 ICEArguments &= ~(1 << ArgNo); 751 } 752 753 switch (BuiltinID) { 754 case Builtin::BI__builtin___CFStringMakeConstantString: 755 assert(TheCall->getNumArgs() == 1 && 756 "Wrong # arguments to builtin CFStringMakeConstantString"); 757 if (CheckObjCString(TheCall->getArg(0))) 758 return ExprError(); 759 break; 760 case Builtin::BI__builtin_stdarg_start: 761 case Builtin::BI__builtin_va_start: 762 if (SemaBuiltinVAStart(TheCall)) 763 return ExprError(); 764 break; 765 case Builtin::BI__va_start: { 766 switch (Context.getTargetInfo().getTriple().getArch()) { 767 case llvm::Triple::arm: 768 case llvm::Triple::thumb: 769 if (SemaBuiltinVAStartARM(TheCall)) 770 return ExprError(); 771 break; 772 default: 773 if (SemaBuiltinVAStart(TheCall)) 774 return ExprError(); 775 break; 776 } 777 break; 778 } 779 case Builtin::BI__builtin_isgreater: 780 case Builtin::BI__builtin_isgreaterequal: 781 case Builtin::BI__builtin_isless: 782 case Builtin::BI__builtin_islessequal: 783 case Builtin::BI__builtin_islessgreater: 784 case Builtin::BI__builtin_isunordered: 785 if (SemaBuiltinUnorderedCompare(TheCall)) 786 return ExprError(); 787 break; 788 case Builtin::BI__builtin_fpclassify: 789 if (SemaBuiltinFPClassification(TheCall, 6)) 790 return ExprError(); 791 break; 792 case Builtin::BI__builtin_isfinite: 793 case Builtin::BI__builtin_isinf: 794 case Builtin::BI__builtin_isinf_sign: 795 case Builtin::BI__builtin_isnan: 796 case Builtin::BI__builtin_isnormal: 797 if (SemaBuiltinFPClassification(TheCall, 1)) 798 return ExprError(); 799 break; 800 case Builtin::BI__builtin_shufflevector: 801 return SemaBuiltinShuffleVector(TheCall); 802 // TheCall will be freed by the smart pointer here, but that's fine, since 803 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 804 case Builtin::BI__builtin_prefetch: 805 if (SemaBuiltinPrefetch(TheCall)) 806 return ExprError(); 807 break; 808 case Builtin::BI__builtin_alloca_with_align: 809 if (SemaBuiltinAllocaWithAlign(TheCall)) 810 return ExprError(); 811 break; 812 case Builtin::BI__assume: 813 case Builtin::BI__builtin_assume: 814 if (SemaBuiltinAssume(TheCall)) 815 return ExprError(); 816 break; 817 case Builtin::BI__builtin_assume_aligned: 818 if (SemaBuiltinAssumeAligned(TheCall)) 819 return ExprError(); 820 break; 821 case Builtin::BI__builtin_object_size: 822 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 823 return ExprError(); 824 break; 825 case Builtin::BI__builtin_longjmp: 826 if (SemaBuiltinLongjmp(TheCall)) 827 return ExprError(); 828 break; 829 case Builtin::BI__builtin_setjmp: 830 if (SemaBuiltinSetjmp(TheCall)) 831 return ExprError(); 832 break; 833 case Builtin::BI_setjmp: 834 case Builtin::BI_setjmpex: 835 if (checkArgCount(*this, TheCall, 1)) 836 return true; 837 break; 838 839 case Builtin::BI__builtin_classify_type: 840 if (checkArgCount(*this, TheCall, 1)) return true; 841 TheCall->setType(Context.IntTy); 842 break; 843 case Builtin::BI__builtin_constant_p: 844 if (checkArgCount(*this, TheCall, 1)) return true; 845 TheCall->setType(Context.IntTy); 846 break; 847 case Builtin::BI__sync_fetch_and_add: 848 case Builtin::BI__sync_fetch_and_add_1: 849 case Builtin::BI__sync_fetch_and_add_2: 850 case Builtin::BI__sync_fetch_and_add_4: 851 case Builtin::BI__sync_fetch_and_add_8: 852 case Builtin::BI__sync_fetch_and_add_16: 853 case Builtin::BI__sync_fetch_and_sub: 854 case Builtin::BI__sync_fetch_and_sub_1: 855 case Builtin::BI__sync_fetch_and_sub_2: 856 case Builtin::BI__sync_fetch_and_sub_4: 857 case Builtin::BI__sync_fetch_and_sub_8: 858 case Builtin::BI__sync_fetch_and_sub_16: 859 case Builtin::BI__sync_fetch_and_or: 860 case Builtin::BI__sync_fetch_and_or_1: 861 case Builtin::BI__sync_fetch_and_or_2: 862 case Builtin::BI__sync_fetch_and_or_4: 863 case Builtin::BI__sync_fetch_and_or_8: 864 case Builtin::BI__sync_fetch_and_or_16: 865 case Builtin::BI__sync_fetch_and_and: 866 case Builtin::BI__sync_fetch_and_and_1: 867 case Builtin::BI__sync_fetch_and_and_2: 868 case Builtin::BI__sync_fetch_and_and_4: 869 case Builtin::BI__sync_fetch_and_and_8: 870 case Builtin::BI__sync_fetch_and_and_16: 871 case Builtin::BI__sync_fetch_and_xor: 872 case Builtin::BI__sync_fetch_and_xor_1: 873 case Builtin::BI__sync_fetch_and_xor_2: 874 case Builtin::BI__sync_fetch_and_xor_4: 875 case Builtin::BI__sync_fetch_and_xor_8: 876 case Builtin::BI__sync_fetch_and_xor_16: 877 case Builtin::BI__sync_fetch_and_nand: 878 case Builtin::BI__sync_fetch_and_nand_1: 879 case Builtin::BI__sync_fetch_and_nand_2: 880 case Builtin::BI__sync_fetch_and_nand_4: 881 case Builtin::BI__sync_fetch_and_nand_8: 882 case Builtin::BI__sync_fetch_and_nand_16: 883 case Builtin::BI__sync_add_and_fetch: 884 case Builtin::BI__sync_add_and_fetch_1: 885 case Builtin::BI__sync_add_and_fetch_2: 886 case Builtin::BI__sync_add_and_fetch_4: 887 case Builtin::BI__sync_add_and_fetch_8: 888 case Builtin::BI__sync_add_and_fetch_16: 889 case Builtin::BI__sync_sub_and_fetch: 890 case Builtin::BI__sync_sub_and_fetch_1: 891 case Builtin::BI__sync_sub_and_fetch_2: 892 case Builtin::BI__sync_sub_and_fetch_4: 893 case Builtin::BI__sync_sub_and_fetch_8: 894 case Builtin::BI__sync_sub_and_fetch_16: 895 case Builtin::BI__sync_and_and_fetch: 896 case Builtin::BI__sync_and_and_fetch_1: 897 case Builtin::BI__sync_and_and_fetch_2: 898 case Builtin::BI__sync_and_and_fetch_4: 899 case Builtin::BI__sync_and_and_fetch_8: 900 case Builtin::BI__sync_and_and_fetch_16: 901 case Builtin::BI__sync_or_and_fetch: 902 case Builtin::BI__sync_or_and_fetch_1: 903 case Builtin::BI__sync_or_and_fetch_2: 904 case Builtin::BI__sync_or_and_fetch_4: 905 case Builtin::BI__sync_or_and_fetch_8: 906 case Builtin::BI__sync_or_and_fetch_16: 907 case Builtin::BI__sync_xor_and_fetch: 908 case Builtin::BI__sync_xor_and_fetch_1: 909 case Builtin::BI__sync_xor_and_fetch_2: 910 case Builtin::BI__sync_xor_and_fetch_4: 911 case Builtin::BI__sync_xor_and_fetch_8: 912 case Builtin::BI__sync_xor_and_fetch_16: 913 case Builtin::BI__sync_nand_and_fetch: 914 case Builtin::BI__sync_nand_and_fetch_1: 915 case Builtin::BI__sync_nand_and_fetch_2: 916 case Builtin::BI__sync_nand_and_fetch_4: 917 case Builtin::BI__sync_nand_and_fetch_8: 918 case Builtin::BI__sync_nand_and_fetch_16: 919 case Builtin::BI__sync_val_compare_and_swap: 920 case Builtin::BI__sync_val_compare_and_swap_1: 921 case Builtin::BI__sync_val_compare_and_swap_2: 922 case Builtin::BI__sync_val_compare_and_swap_4: 923 case Builtin::BI__sync_val_compare_and_swap_8: 924 case Builtin::BI__sync_val_compare_and_swap_16: 925 case Builtin::BI__sync_bool_compare_and_swap: 926 case Builtin::BI__sync_bool_compare_and_swap_1: 927 case Builtin::BI__sync_bool_compare_and_swap_2: 928 case Builtin::BI__sync_bool_compare_and_swap_4: 929 case Builtin::BI__sync_bool_compare_and_swap_8: 930 case Builtin::BI__sync_bool_compare_and_swap_16: 931 case Builtin::BI__sync_lock_test_and_set: 932 case Builtin::BI__sync_lock_test_and_set_1: 933 case Builtin::BI__sync_lock_test_and_set_2: 934 case Builtin::BI__sync_lock_test_and_set_4: 935 case Builtin::BI__sync_lock_test_and_set_8: 936 case Builtin::BI__sync_lock_test_and_set_16: 937 case Builtin::BI__sync_lock_release: 938 case Builtin::BI__sync_lock_release_1: 939 case Builtin::BI__sync_lock_release_2: 940 case Builtin::BI__sync_lock_release_4: 941 case Builtin::BI__sync_lock_release_8: 942 case Builtin::BI__sync_lock_release_16: 943 case Builtin::BI__sync_swap: 944 case Builtin::BI__sync_swap_1: 945 case Builtin::BI__sync_swap_2: 946 case Builtin::BI__sync_swap_4: 947 case Builtin::BI__sync_swap_8: 948 case Builtin::BI__sync_swap_16: 949 return SemaBuiltinAtomicOverloaded(TheCallResult); 950 case Builtin::BI__builtin_nontemporal_load: 951 case Builtin::BI__builtin_nontemporal_store: 952 return SemaBuiltinNontemporalOverloaded(TheCallResult); 953 #define BUILTIN(ID, TYPE, ATTRS) 954 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 955 case Builtin::BI##ID: \ 956 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 957 #include "clang/Basic/Builtins.def" 958 case Builtin::BI__builtin_annotation: 959 if (SemaBuiltinAnnotation(*this, TheCall)) 960 return ExprError(); 961 break; 962 case Builtin::BI__builtin_addressof: 963 if (SemaBuiltinAddressof(*this, TheCall)) 964 return ExprError(); 965 break; 966 case Builtin::BI__builtin_add_overflow: 967 case Builtin::BI__builtin_sub_overflow: 968 case Builtin::BI__builtin_mul_overflow: 969 if (SemaBuiltinOverflow(*this, TheCall)) 970 return ExprError(); 971 break; 972 case Builtin::BI__builtin_operator_new: 973 case Builtin::BI__builtin_operator_delete: 974 if (!getLangOpts().CPlusPlus) { 975 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 976 << (BuiltinID == Builtin::BI__builtin_operator_new 977 ? "__builtin_operator_new" 978 : "__builtin_operator_delete") 979 << "C++"; 980 return ExprError(); 981 } 982 // CodeGen assumes it can find the global new and delete to call, 983 // so ensure that they are declared. 984 DeclareGlobalNewDelete(); 985 break; 986 987 // check secure string manipulation functions where overflows 988 // are detectable at compile time 989 case Builtin::BI__builtin___memcpy_chk: 990 case Builtin::BI__builtin___memmove_chk: 991 case Builtin::BI__builtin___memset_chk: 992 case Builtin::BI__builtin___strlcat_chk: 993 case Builtin::BI__builtin___strlcpy_chk: 994 case Builtin::BI__builtin___strncat_chk: 995 case Builtin::BI__builtin___strncpy_chk: 996 case Builtin::BI__builtin___stpncpy_chk: 997 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 998 break; 999 case Builtin::BI__builtin___memccpy_chk: 1000 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 1001 break; 1002 case Builtin::BI__builtin___snprintf_chk: 1003 case Builtin::BI__builtin___vsnprintf_chk: 1004 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 1005 break; 1006 case Builtin::BI__builtin_call_with_static_chain: 1007 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1008 return ExprError(); 1009 break; 1010 case Builtin::BI__exception_code: 1011 case Builtin::BI_exception_code: 1012 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1013 diag::err_seh___except_block)) 1014 return ExprError(); 1015 break; 1016 case Builtin::BI__exception_info: 1017 case Builtin::BI_exception_info: 1018 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1019 diag::err_seh___except_filter)) 1020 return ExprError(); 1021 break; 1022 case Builtin::BI__GetExceptionInfo: 1023 if (checkArgCount(*this, TheCall, 1)) 1024 return ExprError(); 1025 1026 if (CheckCXXThrowOperand( 1027 TheCall->getLocStart(), 1028 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1029 TheCall)) 1030 return ExprError(); 1031 1032 TheCall->setType(Context.VoidPtrTy); 1033 break; 1034 // OpenCL v2.0, s6.13.16 - Pipe functions 1035 case Builtin::BIread_pipe: 1036 case Builtin::BIwrite_pipe: 1037 // Since those two functions are declared with var args, we need a semantic 1038 // check for the argument. 1039 if (SemaBuiltinRWPipe(*this, TheCall)) 1040 return ExprError(); 1041 TheCall->setType(Context.IntTy); 1042 break; 1043 case Builtin::BIreserve_read_pipe: 1044 case Builtin::BIreserve_write_pipe: 1045 case Builtin::BIwork_group_reserve_read_pipe: 1046 case Builtin::BIwork_group_reserve_write_pipe: 1047 case Builtin::BIsub_group_reserve_read_pipe: 1048 case Builtin::BIsub_group_reserve_write_pipe: 1049 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1050 return ExprError(); 1051 // Since return type of reserve_read/write_pipe built-in function is 1052 // reserve_id_t, which is not defined in the builtin def file , we used int 1053 // as return type and need to override the return type of these functions. 1054 TheCall->setType(Context.OCLReserveIDTy); 1055 break; 1056 case Builtin::BIcommit_read_pipe: 1057 case Builtin::BIcommit_write_pipe: 1058 case Builtin::BIwork_group_commit_read_pipe: 1059 case Builtin::BIwork_group_commit_write_pipe: 1060 case Builtin::BIsub_group_commit_read_pipe: 1061 case Builtin::BIsub_group_commit_write_pipe: 1062 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1063 return ExprError(); 1064 break; 1065 case Builtin::BIget_pipe_num_packets: 1066 case Builtin::BIget_pipe_max_packets: 1067 if (SemaBuiltinPipePackets(*this, TheCall)) 1068 return ExprError(); 1069 TheCall->setType(Context.UnsignedIntTy); 1070 break; 1071 case Builtin::BIto_global: 1072 case Builtin::BIto_local: 1073 case Builtin::BIto_private: 1074 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1075 return ExprError(); 1076 break; 1077 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1078 case Builtin::BIenqueue_kernel: 1079 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1080 return ExprError(); 1081 break; 1082 case Builtin::BIget_kernel_work_group_size: 1083 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1084 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1085 return ExprError(); 1086 break; 1087 case Builtin::BI__builtin_os_log_format: 1088 case Builtin::BI__builtin_os_log_format_buffer_size: 1089 if (SemaBuiltinOSLogFormat(TheCall)) { 1090 return ExprError(); 1091 } 1092 break; 1093 } 1094 1095 // Since the target specific builtins for each arch overlap, only check those 1096 // of the arch we are compiling for. 1097 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1098 switch (Context.getTargetInfo().getTriple().getArch()) { 1099 case llvm::Triple::arm: 1100 case llvm::Triple::armeb: 1101 case llvm::Triple::thumb: 1102 case llvm::Triple::thumbeb: 1103 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1104 return ExprError(); 1105 break; 1106 case llvm::Triple::aarch64: 1107 case llvm::Triple::aarch64_be: 1108 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1109 return ExprError(); 1110 break; 1111 case llvm::Triple::mips: 1112 case llvm::Triple::mipsel: 1113 case llvm::Triple::mips64: 1114 case llvm::Triple::mips64el: 1115 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1116 return ExprError(); 1117 break; 1118 case llvm::Triple::systemz: 1119 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1120 return ExprError(); 1121 break; 1122 case llvm::Triple::x86: 1123 case llvm::Triple::x86_64: 1124 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1125 return ExprError(); 1126 break; 1127 case llvm::Triple::ppc: 1128 case llvm::Triple::ppc64: 1129 case llvm::Triple::ppc64le: 1130 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1131 return ExprError(); 1132 break; 1133 default: 1134 break; 1135 } 1136 } 1137 1138 return TheCallResult; 1139 } 1140 1141 // Get the valid immediate range for the specified NEON type code. 1142 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1143 NeonTypeFlags Type(t); 1144 int IsQuad = ForceQuad ? true : Type.isQuad(); 1145 switch (Type.getEltType()) { 1146 case NeonTypeFlags::Int8: 1147 case NeonTypeFlags::Poly8: 1148 return shift ? 7 : (8 << IsQuad) - 1; 1149 case NeonTypeFlags::Int16: 1150 case NeonTypeFlags::Poly16: 1151 return shift ? 15 : (4 << IsQuad) - 1; 1152 case NeonTypeFlags::Int32: 1153 return shift ? 31 : (2 << IsQuad) - 1; 1154 case NeonTypeFlags::Int64: 1155 case NeonTypeFlags::Poly64: 1156 return shift ? 63 : (1 << IsQuad) - 1; 1157 case NeonTypeFlags::Poly128: 1158 return shift ? 127 : (1 << IsQuad) - 1; 1159 case NeonTypeFlags::Float16: 1160 assert(!shift && "cannot shift float types!"); 1161 return (4 << IsQuad) - 1; 1162 case NeonTypeFlags::Float32: 1163 assert(!shift && "cannot shift float types!"); 1164 return (2 << IsQuad) - 1; 1165 case NeonTypeFlags::Float64: 1166 assert(!shift && "cannot shift float types!"); 1167 return (1 << IsQuad) - 1; 1168 } 1169 llvm_unreachable("Invalid NeonTypeFlag!"); 1170 } 1171 1172 /// getNeonEltType - Return the QualType corresponding to the elements of 1173 /// the vector type specified by the NeonTypeFlags. This is used to check 1174 /// the pointer arguments for Neon load/store intrinsics. 1175 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1176 bool IsPolyUnsigned, bool IsInt64Long) { 1177 switch (Flags.getEltType()) { 1178 case NeonTypeFlags::Int8: 1179 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1180 case NeonTypeFlags::Int16: 1181 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1182 case NeonTypeFlags::Int32: 1183 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1184 case NeonTypeFlags::Int64: 1185 if (IsInt64Long) 1186 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1187 else 1188 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1189 : Context.LongLongTy; 1190 case NeonTypeFlags::Poly8: 1191 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1192 case NeonTypeFlags::Poly16: 1193 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1194 case NeonTypeFlags::Poly64: 1195 if (IsInt64Long) 1196 return Context.UnsignedLongTy; 1197 else 1198 return Context.UnsignedLongLongTy; 1199 case NeonTypeFlags::Poly128: 1200 break; 1201 case NeonTypeFlags::Float16: 1202 return Context.HalfTy; 1203 case NeonTypeFlags::Float32: 1204 return Context.FloatTy; 1205 case NeonTypeFlags::Float64: 1206 return Context.DoubleTy; 1207 } 1208 llvm_unreachable("Invalid NeonTypeFlag!"); 1209 } 1210 1211 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1212 llvm::APSInt Result; 1213 uint64_t mask = 0; 1214 unsigned TV = 0; 1215 int PtrArgNum = -1; 1216 bool HasConstPtr = false; 1217 switch (BuiltinID) { 1218 #define GET_NEON_OVERLOAD_CHECK 1219 #include "clang/Basic/arm_neon.inc" 1220 #undef GET_NEON_OVERLOAD_CHECK 1221 } 1222 1223 // For NEON intrinsics which are overloaded on vector element type, validate 1224 // the immediate which specifies which variant to emit. 1225 unsigned ImmArg = TheCall->getNumArgs()-1; 1226 if (mask) { 1227 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1228 return true; 1229 1230 TV = Result.getLimitedValue(64); 1231 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1232 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1233 << TheCall->getArg(ImmArg)->getSourceRange(); 1234 } 1235 1236 if (PtrArgNum >= 0) { 1237 // Check that pointer arguments have the specified type. 1238 Expr *Arg = TheCall->getArg(PtrArgNum); 1239 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1240 Arg = ICE->getSubExpr(); 1241 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1242 QualType RHSTy = RHS.get()->getType(); 1243 1244 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1245 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64; 1246 bool IsInt64Long = 1247 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1248 QualType EltTy = 1249 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1250 if (HasConstPtr) 1251 EltTy = EltTy.withConst(); 1252 QualType LHSTy = Context.getPointerType(EltTy); 1253 AssignConvertType ConvTy; 1254 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1255 if (RHS.isInvalid()) 1256 return true; 1257 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1258 RHS.get(), AA_Assigning)) 1259 return true; 1260 } 1261 1262 // For NEON intrinsics which take an immediate value as part of the 1263 // instruction, range check them here. 1264 unsigned i = 0, l = 0, u = 0; 1265 switch (BuiltinID) { 1266 default: 1267 return false; 1268 #define GET_NEON_IMMEDIATE_CHECK 1269 #include "clang/Basic/arm_neon.inc" 1270 #undef GET_NEON_IMMEDIATE_CHECK 1271 } 1272 1273 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1274 } 1275 1276 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1277 unsigned MaxWidth) { 1278 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1279 BuiltinID == ARM::BI__builtin_arm_ldaex || 1280 BuiltinID == ARM::BI__builtin_arm_strex || 1281 BuiltinID == ARM::BI__builtin_arm_stlex || 1282 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1283 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1284 BuiltinID == AArch64::BI__builtin_arm_strex || 1285 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1286 "unexpected ARM builtin"); 1287 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1288 BuiltinID == ARM::BI__builtin_arm_ldaex || 1289 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1290 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1291 1292 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1293 1294 // Ensure that we have the proper number of arguments. 1295 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1296 return true; 1297 1298 // Inspect the pointer argument of the atomic builtin. This should always be 1299 // a pointer type, whose element is an integral scalar or pointer type. 1300 // Because it is a pointer type, we don't have to worry about any implicit 1301 // casts here. 1302 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1303 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1304 if (PointerArgRes.isInvalid()) 1305 return true; 1306 PointerArg = PointerArgRes.get(); 1307 1308 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1309 if (!pointerType) { 1310 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1311 << PointerArg->getType() << PointerArg->getSourceRange(); 1312 return true; 1313 } 1314 1315 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1316 // task is to insert the appropriate casts into the AST. First work out just 1317 // what the appropriate type is. 1318 QualType ValType = pointerType->getPointeeType(); 1319 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1320 if (IsLdrex) 1321 AddrType.addConst(); 1322 1323 // Issue a warning if the cast is dodgy. 1324 CastKind CastNeeded = CK_NoOp; 1325 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1326 CastNeeded = CK_BitCast; 1327 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1328 << PointerArg->getType() 1329 << Context.getPointerType(AddrType) 1330 << AA_Passing << PointerArg->getSourceRange(); 1331 } 1332 1333 // Finally, do the cast and replace the argument with the corrected version. 1334 AddrType = Context.getPointerType(AddrType); 1335 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1336 if (PointerArgRes.isInvalid()) 1337 return true; 1338 PointerArg = PointerArgRes.get(); 1339 1340 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1341 1342 // In general, we allow ints, floats and pointers to be loaded and stored. 1343 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1344 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1345 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1346 << PointerArg->getType() << PointerArg->getSourceRange(); 1347 return true; 1348 } 1349 1350 // But ARM doesn't have instructions to deal with 128-bit versions. 1351 if (Context.getTypeSize(ValType) > MaxWidth) { 1352 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1353 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1354 << PointerArg->getType() << PointerArg->getSourceRange(); 1355 return true; 1356 } 1357 1358 switch (ValType.getObjCLifetime()) { 1359 case Qualifiers::OCL_None: 1360 case Qualifiers::OCL_ExplicitNone: 1361 // okay 1362 break; 1363 1364 case Qualifiers::OCL_Weak: 1365 case Qualifiers::OCL_Strong: 1366 case Qualifiers::OCL_Autoreleasing: 1367 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1368 << ValType << PointerArg->getSourceRange(); 1369 return true; 1370 } 1371 1372 if (IsLdrex) { 1373 TheCall->setType(ValType); 1374 return false; 1375 } 1376 1377 // Initialize the argument to be stored. 1378 ExprResult ValArg = TheCall->getArg(0); 1379 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1380 Context, ValType, /*consume*/ false); 1381 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1382 if (ValArg.isInvalid()) 1383 return true; 1384 TheCall->setArg(0, ValArg.get()); 1385 1386 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1387 // but the custom checker bypasses all default analysis. 1388 TheCall->setType(Context.IntTy); 1389 return false; 1390 } 1391 1392 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1393 llvm::APSInt Result; 1394 1395 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1396 BuiltinID == ARM::BI__builtin_arm_ldaex || 1397 BuiltinID == ARM::BI__builtin_arm_strex || 1398 BuiltinID == ARM::BI__builtin_arm_stlex) { 1399 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1400 } 1401 1402 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1403 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1404 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1405 } 1406 1407 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1408 BuiltinID == ARM::BI__builtin_arm_wsr64) 1409 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1410 1411 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1412 BuiltinID == ARM::BI__builtin_arm_rsrp || 1413 BuiltinID == ARM::BI__builtin_arm_wsr || 1414 BuiltinID == ARM::BI__builtin_arm_wsrp) 1415 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1416 1417 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1418 return true; 1419 1420 // For intrinsics which take an immediate value as part of the instruction, 1421 // range check them here. 1422 unsigned i = 0, l = 0, u = 0; 1423 switch (BuiltinID) { 1424 default: return false; 1425 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 1426 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 1427 case ARM::BI__builtin_arm_vcvtr_f: 1428 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 1429 case ARM::BI__builtin_arm_dmb: 1430 case ARM::BI__builtin_arm_dsb: 1431 case ARM::BI__builtin_arm_isb: 1432 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break; 1433 } 1434 1435 // FIXME: VFP Intrinsics should error if VFP not present. 1436 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1437 } 1438 1439 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1440 CallExpr *TheCall) { 1441 llvm::APSInt Result; 1442 1443 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1444 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1445 BuiltinID == AArch64::BI__builtin_arm_strex || 1446 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1447 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1448 } 1449 1450 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1451 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1452 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1453 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1454 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1455 } 1456 1457 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1458 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1459 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1460 1461 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1462 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1463 BuiltinID == AArch64::BI__builtin_arm_wsr || 1464 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1465 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1466 1467 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1468 return true; 1469 1470 // For intrinsics which take an immediate value as part of the instruction, 1471 // range check them here. 1472 unsigned i = 0, l = 0, u = 0; 1473 switch (BuiltinID) { 1474 default: return false; 1475 case AArch64::BI__builtin_arm_dmb: 1476 case AArch64::BI__builtin_arm_dsb: 1477 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1478 } 1479 1480 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1481 } 1482 1483 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1484 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1485 // ordering for DSP is unspecified. MSA is ordered by the data format used 1486 // by the underlying instruction i.e., df/m, df/n and then by size. 1487 // 1488 // FIXME: The size tests here should instead be tablegen'd along with the 1489 // definitions from include/clang/Basic/BuiltinsMips.def. 1490 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1491 // be too. 1492 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1493 unsigned i = 0, l = 0, u = 0, m = 0; 1494 switch (BuiltinID) { 1495 default: return false; 1496 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1497 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1498 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1499 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1500 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1501 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1502 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1503 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1504 // df/m field. 1505 // These intrinsics take an unsigned 3 bit immediate. 1506 case Mips::BI__builtin_msa_bclri_b: 1507 case Mips::BI__builtin_msa_bnegi_b: 1508 case Mips::BI__builtin_msa_bseti_b: 1509 case Mips::BI__builtin_msa_sat_s_b: 1510 case Mips::BI__builtin_msa_sat_u_b: 1511 case Mips::BI__builtin_msa_slli_b: 1512 case Mips::BI__builtin_msa_srai_b: 1513 case Mips::BI__builtin_msa_srari_b: 1514 case Mips::BI__builtin_msa_srli_b: 1515 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1516 case Mips::BI__builtin_msa_binsli_b: 1517 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1518 // These intrinsics take an unsigned 4 bit immediate. 1519 case Mips::BI__builtin_msa_bclri_h: 1520 case Mips::BI__builtin_msa_bnegi_h: 1521 case Mips::BI__builtin_msa_bseti_h: 1522 case Mips::BI__builtin_msa_sat_s_h: 1523 case Mips::BI__builtin_msa_sat_u_h: 1524 case Mips::BI__builtin_msa_slli_h: 1525 case Mips::BI__builtin_msa_srai_h: 1526 case Mips::BI__builtin_msa_srari_h: 1527 case Mips::BI__builtin_msa_srli_h: 1528 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1529 case Mips::BI__builtin_msa_binsli_h: 1530 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 1531 // These intrinsics take an unsigned 5 bit immedate. 1532 // The first block of intrinsics actually have an unsigned 5 bit field, 1533 // not a df/n field. 1534 case Mips::BI__builtin_msa_clei_u_b: 1535 case Mips::BI__builtin_msa_clei_u_h: 1536 case Mips::BI__builtin_msa_clei_u_w: 1537 case Mips::BI__builtin_msa_clei_u_d: 1538 case Mips::BI__builtin_msa_clti_u_b: 1539 case Mips::BI__builtin_msa_clti_u_h: 1540 case Mips::BI__builtin_msa_clti_u_w: 1541 case Mips::BI__builtin_msa_clti_u_d: 1542 case Mips::BI__builtin_msa_maxi_u_b: 1543 case Mips::BI__builtin_msa_maxi_u_h: 1544 case Mips::BI__builtin_msa_maxi_u_w: 1545 case Mips::BI__builtin_msa_maxi_u_d: 1546 case Mips::BI__builtin_msa_mini_u_b: 1547 case Mips::BI__builtin_msa_mini_u_h: 1548 case Mips::BI__builtin_msa_mini_u_w: 1549 case Mips::BI__builtin_msa_mini_u_d: 1550 case Mips::BI__builtin_msa_addvi_b: 1551 case Mips::BI__builtin_msa_addvi_h: 1552 case Mips::BI__builtin_msa_addvi_w: 1553 case Mips::BI__builtin_msa_addvi_d: 1554 case Mips::BI__builtin_msa_bclri_w: 1555 case Mips::BI__builtin_msa_bnegi_w: 1556 case Mips::BI__builtin_msa_bseti_w: 1557 case Mips::BI__builtin_msa_sat_s_w: 1558 case Mips::BI__builtin_msa_sat_u_w: 1559 case Mips::BI__builtin_msa_slli_w: 1560 case Mips::BI__builtin_msa_srai_w: 1561 case Mips::BI__builtin_msa_srari_w: 1562 case Mips::BI__builtin_msa_srli_w: 1563 case Mips::BI__builtin_msa_srlri_w: 1564 case Mips::BI__builtin_msa_subvi_b: 1565 case Mips::BI__builtin_msa_subvi_h: 1566 case Mips::BI__builtin_msa_subvi_w: 1567 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 1568 case Mips::BI__builtin_msa_binsli_w: 1569 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 1570 // These intrinsics take an unsigned 6 bit immediate. 1571 case Mips::BI__builtin_msa_bclri_d: 1572 case Mips::BI__builtin_msa_bnegi_d: 1573 case Mips::BI__builtin_msa_bseti_d: 1574 case Mips::BI__builtin_msa_sat_s_d: 1575 case Mips::BI__builtin_msa_sat_u_d: 1576 case Mips::BI__builtin_msa_slli_d: 1577 case Mips::BI__builtin_msa_srai_d: 1578 case Mips::BI__builtin_msa_srari_d: 1579 case Mips::BI__builtin_msa_srli_d: 1580 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 1581 case Mips::BI__builtin_msa_binsli_d: 1582 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 1583 // These intrinsics take a signed 5 bit immediate. 1584 case Mips::BI__builtin_msa_ceqi_b: 1585 case Mips::BI__builtin_msa_ceqi_h: 1586 case Mips::BI__builtin_msa_ceqi_w: 1587 case Mips::BI__builtin_msa_ceqi_d: 1588 case Mips::BI__builtin_msa_clti_s_b: 1589 case Mips::BI__builtin_msa_clti_s_h: 1590 case Mips::BI__builtin_msa_clti_s_w: 1591 case Mips::BI__builtin_msa_clti_s_d: 1592 case Mips::BI__builtin_msa_clei_s_b: 1593 case Mips::BI__builtin_msa_clei_s_h: 1594 case Mips::BI__builtin_msa_clei_s_w: 1595 case Mips::BI__builtin_msa_clei_s_d: 1596 case Mips::BI__builtin_msa_maxi_s_b: 1597 case Mips::BI__builtin_msa_maxi_s_h: 1598 case Mips::BI__builtin_msa_maxi_s_w: 1599 case Mips::BI__builtin_msa_maxi_s_d: 1600 case Mips::BI__builtin_msa_mini_s_b: 1601 case Mips::BI__builtin_msa_mini_s_h: 1602 case Mips::BI__builtin_msa_mini_s_w: 1603 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 1604 // These intrinsics take an unsigned 8 bit immediate. 1605 case Mips::BI__builtin_msa_andi_b: 1606 case Mips::BI__builtin_msa_nori_b: 1607 case Mips::BI__builtin_msa_ori_b: 1608 case Mips::BI__builtin_msa_shf_b: 1609 case Mips::BI__builtin_msa_shf_h: 1610 case Mips::BI__builtin_msa_shf_w: 1611 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 1612 case Mips::BI__builtin_msa_bseli_b: 1613 case Mips::BI__builtin_msa_bmnzi_b: 1614 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 1615 // df/n format 1616 // These intrinsics take an unsigned 4 bit immediate. 1617 case Mips::BI__builtin_msa_copy_s_b: 1618 case Mips::BI__builtin_msa_copy_u_b: 1619 case Mips::BI__builtin_msa_insve_b: 1620 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 1621 case Mips::BI__builtin_msa_sld_b: 1622 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 1623 // These intrinsics take an unsigned 3 bit immediate. 1624 case Mips::BI__builtin_msa_copy_s_h: 1625 case Mips::BI__builtin_msa_copy_u_h: 1626 case Mips::BI__builtin_msa_insve_h: 1627 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 1628 case Mips::BI__builtin_msa_sld_h: 1629 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 1630 // These intrinsics take an unsigned 2 bit immediate. 1631 case Mips::BI__builtin_msa_copy_s_w: 1632 case Mips::BI__builtin_msa_copy_u_w: 1633 case Mips::BI__builtin_msa_insve_w: 1634 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 1635 case Mips::BI__builtin_msa_sld_w: 1636 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 1637 // These intrinsics take an unsigned 1 bit immediate. 1638 case Mips::BI__builtin_msa_copy_s_d: 1639 case Mips::BI__builtin_msa_copy_u_d: 1640 case Mips::BI__builtin_msa_insve_d: 1641 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 1642 case Mips::BI__builtin_msa_sld_d: 1643 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 1644 // Memory offsets and immediate loads. 1645 // These intrinsics take a signed 10 bit immediate. 1646 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break; 1647 case Mips::BI__builtin_msa_ldi_h: 1648 case Mips::BI__builtin_msa_ldi_w: 1649 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 1650 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 1651 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 1652 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 1653 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 1654 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 1655 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 1656 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 1657 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 1658 } 1659 1660 if (!m) 1661 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1662 1663 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 1664 SemaBuiltinConstantArgMultiple(TheCall, i, m); 1665 } 1666 1667 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1668 unsigned i = 0, l = 0, u = 0; 1669 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 1670 BuiltinID == PPC::BI__builtin_divdeu || 1671 BuiltinID == PPC::BI__builtin_bpermd; 1672 bool IsTarget64Bit = Context.getTargetInfo() 1673 .getTypeWidth(Context 1674 .getTargetInfo() 1675 .getIntPtrType()) == 64; 1676 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 1677 BuiltinID == PPC::BI__builtin_divweu || 1678 BuiltinID == PPC::BI__builtin_divde || 1679 BuiltinID == PPC::BI__builtin_divdeu; 1680 1681 if (Is64BitBltin && !IsTarget64Bit) 1682 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 1683 << TheCall->getSourceRange(); 1684 1685 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 1686 (BuiltinID == PPC::BI__builtin_bpermd && 1687 !Context.getTargetInfo().hasFeature("bpermd"))) 1688 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 1689 << TheCall->getSourceRange(); 1690 1691 switch (BuiltinID) { 1692 default: return false; 1693 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 1694 case PPC::BI__builtin_altivec_crypto_vshasigmad: 1695 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1696 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1697 case PPC::BI__builtin_tbegin: 1698 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 1699 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 1700 case PPC::BI__builtin_tabortwc: 1701 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 1702 case PPC::BI__builtin_tabortwci: 1703 case PPC::BI__builtin_tabortdci: 1704 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 1705 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 1706 } 1707 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1708 } 1709 1710 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 1711 CallExpr *TheCall) { 1712 if (BuiltinID == SystemZ::BI__builtin_tabort) { 1713 Expr *Arg = TheCall->getArg(0); 1714 llvm::APSInt AbortCode(32); 1715 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 1716 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 1717 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 1718 << Arg->getSourceRange(); 1719 } 1720 1721 // For intrinsics which take an immediate value as part of the instruction, 1722 // range check them here. 1723 unsigned i = 0, l = 0, u = 0; 1724 switch (BuiltinID) { 1725 default: return false; 1726 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 1727 case SystemZ::BI__builtin_s390_verimb: 1728 case SystemZ::BI__builtin_s390_verimh: 1729 case SystemZ::BI__builtin_s390_verimf: 1730 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 1731 case SystemZ::BI__builtin_s390_vfaeb: 1732 case SystemZ::BI__builtin_s390_vfaeh: 1733 case SystemZ::BI__builtin_s390_vfaef: 1734 case SystemZ::BI__builtin_s390_vfaebs: 1735 case SystemZ::BI__builtin_s390_vfaehs: 1736 case SystemZ::BI__builtin_s390_vfaefs: 1737 case SystemZ::BI__builtin_s390_vfaezb: 1738 case SystemZ::BI__builtin_s390_vfaezh: 1739 case SystemZ::BI__builtin_s390_vfaezf: 1740 case SystemZ::BI__builtin_s390_vfaezbs: 1741 case SystemZ::BI__builtin_s390_vfaezhs: 1742 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 1743 case SystemZ::BI__builtin_s390_vfidb: 1744 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 1745 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1746 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 1747 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 1748 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 1749 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 1750 case SystemZ::BI__builtin_s390_vstrcb: 1751 case SystemZ::BI__builtin_s390_vstrch: 1752 case SystemZ::BI__builtin_s390_vstrcf: 1753 case SystemZ::BI__builtin_s390_vstrczb: 1754 case SystemZ::BI__builtin_s390_vstrczh: 1755 case SystemZ::BI__builtin_s390_vstrczf: 1756 case SystemZ::BI__builtin_s390_vstrcbs: 1757 case SystemZ::BI__builtin_s390_vstrchs: 1758 case SystemZ::BI__builtin_s390_vstrcfs: 1759 case SystemZ::BI__builtin_s390_vstrczbs: 1760 case SystemZ::BI__builtin_s390_vstrczhs: 1761 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 1762 } 1763 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1764 } 1765 1766 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 1767 /// This checks that the target supports __builtin_cpu_supports and 1768 /// that the string argument is constant and valid. 1769 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 1770 Expr *Arg = TheCall->getArg(0); 1771 1772 // Check if the argument is a string literal. 1773 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1774 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1775 << Arg->getSourceRange(); 1776 1777 // Check the contents of the string. 1778 StringRef Feature = 1779 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1780 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 1781 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 1782 << Arg->getSourceRange(); 1783 return false; 1784 } 1785 1786 // Check if the rounding mode is legal. 1787 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 1788 // Indicates if this instruction has rounding control or just SAE. 1789 bool HasRC = false; 1790 1791 unsigned ArgNum = 0; 1792 switch (BuiltinID) { 1793 default: 1794 return false; 1795 case X86::BI__builtin_ia32_vcvttsd2si32: 1796 case X86::BI__builtin_ia32_vcvttsd2si64: 1797 case X86::BI__builtin_ia32_vcvttsd2usi32: 1798 case X86::BI__builtin_ia32_vcvttsd2usi64: 1799 case X86::BI__builtin_ia32_vcvttss2si32: 1800 case X86::BI__builtin_ia32_vcvttss2si64: 1801 case X86::BI__builtin_ia32_vcvttss2usi32: 1802 case X86::BI__builtin_ia32_vcvttss2usi64: 1803 ArgNum = 1; 1804 break; 1805 case X86::BI__builtin_ia32_cvtps2pd512_mask: 1806 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 1807 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 1808 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 1809 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 1810 case X86::BI__builtin_ia32_cvttps2dq512_mask: 1811 case X86::BI__builtin_ia32_cvttps2qq512_mask: 1812 case X86::BI__builtin_ia32_cvttps2udq512_mask: 1813 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 1814 case X86::BI__builtin_ia32_exp2pd_mask: 1815 case X86::BI__builtin_ia32_exp2ps_mask: 1816 case X86::BI__builtin_ia32_getexppd512_mask: 1817 case X86::BI__builtin_ia32_getexpps512_mask: 1818 case X86::BI__builtin_ia32_rcp28pd_mask: 1819 case X86::BI__builtin_ia32_rcp28ps_mask: 1820 case X86::BI__builtin_ia32_rsqrt28pd_mask: 1821 case X86::BI__builtin_ia32_rsqrt28ps_mask: 1822 case X86::BI__builtin_ia32_vcomisd: 1823 case X86::BI__builtin_ia32_vcomiss: 1824 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 1825 ArgNum = 3; 1826 break; 1827 case X86::BI__builtin_ia32_cmppd512_mask: 1828 case X86::BI__builtin_ia32_cmpps512_mask: 1829 case X86::BI__builtin_ia32_cmpsd_mask: 1830 case X86::BI__builtin_ia32_cmpss_mask: 1831 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 1832 case X86::BI__builtin_ia32_getexpsd128_round_mask: 1833 case X86::BI__builtin_ia32_getexpss128_round_mask: 1834 case X86::BI__builtin_ia32_maxpd512_mask: 1835 case X86::BI__builtin_ia32_maxps512_mask: 1836 case X86::BI__builtin_ia32_maxsd_round_mask: 1837 case X86::BI__builtin_ia32_maxss_round_mask: 1838 case X86::BI__builtin_ia32_minpd512_mask: 1839 case X86::BI__builtin_ia32_minps512_mask: 1840 case X86::BI__builtin_ia32_minsd_round_mask: 1841 case X86::BI__builtin_ia32_minss_round_mask: 1842 case X86::BI__builtin_ia32_rcp28sd_round_mask: 1843 case X86::BI__builtin_ia32_rcp28ss_round_mask: 1844 case X86::BI__builtin_ia32_reducepd512_mask: 1845 case X86::BI__builtin_ia32_reduceps512_mask: 1846 case X86::BI__builtin_ia32_rndscalepd_mask: 1847 case X86::BI__builtin_ia32_rndscaleps_mask: 1848 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 1849 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 1850 ArgNum = 4; 1851 break; 1852 case X86::BI__builtin_ia32_fixupimmpd512_mask: 1853 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 1854 case X86::BI__builtin_ia32_fixupimmps512_mask: 1855 case X86::BI__builtin_ia32_fixupimmps512_maskz: 1856 case X86::BI__builtin_ia32_fixupimmsd_mask: 1857 case X86::BI__builtin_ia32_fixupimmsd_maskz: 1858 case X86::BI__builtin_ia32_fixupimmss_mask: 1859 case X86::BI__builtin_ia32_fixupimmss_maskz: 1860 case X86::BI__builtin_ia32_rangepd512_mask: 1861 case X86::BI__builtin_ia32_rangeps512_mask: 1862 case X86::BI__builtin_ia32_rangesd128_round_mask: 1863 case X86::BI__builtin_ia32_rangess128_round_mask: 1864 case X86::BI__builtin_ia32_reducesd_mask: 1865 case X86::BI__builtin_ia32_reducess_mask: 1866 case X86::BI__builtin_ia32_rndscalesd_round_mask: 1867 case X86::BI__builtin_ia32_rndscaless_round_mask: 1868 ArgNum = 5; 1869 break; 1870 case X86::BI__builtin_ia32_vcvtsd2si64: 1871 case X86::BI__builtin_ia32_vcvtsd2si32: 1872 case X86::BI__builtin_ia32_vcvtsd2usi32: 1873 case X86::BI__builtin_ia32_vcvtsd2usi64: 1874 case X86::BI__builtin_ia32_vcvtss2si32: 1875 case X86::BI__builtin_ia32_vcvtss2si64: 1876 case X86::BI__builtin_ia32_vcvtss2usi32: 1877 case X86::BI__builtin_ia32_vcvtss2usi64: 1878 ArgNum = 1; 1879 HasRC = true; 1880 break; 1881 case X86::BI__builtin_ia32_cvtsi2sd64: 1882 case X86::BI__builtin_ia32_cvtsi2ss32: 1883 case X86::BI__builtin_ia32_cvtsi2ss64: 1884 case X86::BI__builtin_ia32_cvtusi2sd64: 1885 case X86::BI__builtin_ia32_cvtusi2ss32: 1886 case X86::BI__builtin_ia32_cvtusi2ss64: 1887 ArgNum = 2; 1888 HasRC = true; 1889 break; 1890 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 1891 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 1892 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 1893 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 1894 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 1895 case X86::BI__builtin_ia32_cvtps2qq512_mask: 1896 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 1897 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 1898 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 1899 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 1900 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 1901 case X86::BI__builtin_ia32_sqrtpd512_mask: 1902 case X86::BI__builtin_ia32_sqrtps512_mask: 1903 ArgNum = 3; 1904 HasRC = true; 1905 break; 1906 case X86::BI__builtin_ia32_addpd512_mask: 1907 case X86::BI__builtin_ia32_addps512_mask: 1908 case X86::BI__builtin_ia32_divpd512_mask: 1909 case X86::BI__builtin_ia32_divps512_mask: 1910 case X86::BI__builtin_ia32_mulpd512_mask: 1911 case X86::BI__builtin_ia32_mulps512_mask: 1912 case X86::BI__builtin_ia32_subpd512_mask: 1913 case X86::BI__builtin_ia32_subps512_mask: 1914 case X86::BI__builtin_ia32_addss_round_mask: 1915 case X86::BI__builtin_ia32_addsd_round_mask: 1916 case X86::BI__builtin_ia32_divss_round_mask: 1917 case X86::BI__builtin_ia32_divsd_round_mask: 1918 case X86::BI__builtin_ia32_mulss_round_mask: 1919 case X86::BI__builtin_ia32_mulsd_round_mask: 1920 case X86::BI__builtin_ia32_subss_round_mask: 1921 case X86::BI__builtin_ia32_subsd_round_mask: 1922 case X86::BI__builtin_ia32_scalefpd512_mask: 1923 case X86::BI__builtin_ia32_scalefps512_mask: 1924 case X86::BI__builtin_ia32_scalefsd_round_mask: 1925 case X86::BI__builtin_ia32_scalefss_round_mask: 1926 case X86::BI__builtin_ia32_getmantpd512_mask: 1927 case X86::BI__builtin_ia32_getmantps512_mask: 1928 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 1929 case X86::BI__builtin_ia32_sqrtsd_round_mask: 1930 case X86::BI__builtin_ia32_sqrtss_round_mask: 1931 case X86::BI__builtin_ia32_vfmaddpd512_mask: 1932 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 1933 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 1934 case X86::BI__builtin_ia32_vfmaddps512_mask: 1935 case X86::BI__builtin_ia32_vfmaddps512_mask3: 1936 case X86::BI__builtin_ia32_vfmaddps512_maskz: 1937 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 1938 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 1939 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 1940 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 1941 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 1942 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 1943 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 1944 case X86::BI__builtin_ia32_vfmsubps512_mask3: 1945 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 1946 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 1947 case X86::BI__builtin_ia32_vfnmaddpd512_mask: 1948 case X86::BI__builtin_ia32_vfnmaddps512_mask: 1949 case X86::BI__builtin_ia32_vfnmsubpd512_mask: 1950 case X86::BI__builtin_ia32_vfnmsubpd512_mask3: 1951 case X86::BI__builtin_ia32_vfnmsubps512_mask: 1952 case X86::BI__builtin_ia32_vfnmsubps512_mask3: 1953 case X86::BI__builtin_ia32_vfmaddsd3_mask: 1954 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 1955 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 1956 case X86::BI__builtin_ia32_vfmaddss3_mask: 1957 case X86::BI__builtin_ia32_vfmaddss3_maskz: 1958 case X86::BI__builtin_ia32_vfmaddss3_mask3: 1959 ArgNum = 4; 1960 HasRC = true; 1961 break; 1962 case X86::BI__builtin_ia32_getmantsd_round_mask: 1963 case X86::BI__builtin_ia32_getmantss_round_mask: 1964 ArgNum = 5; 1965 HasRC = true; 1966 break; 1967 } 1968 1969 llvm::APSInt Result; 1970 1971 // We can't check the value of a dependent argument. 1972 Expr *Arg = TheCall->getArg(ArgNum); 1973 if (Arg->isTypeDependent() || Arg->isValueDependent()) 1974 return false; 1975 1976 // Check constant-ness first. 1977 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 1978 return true; 1979 1980 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 1981 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 1982 // combined with ROUND_NO_EXC. 1983 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 1984 Result == 8/*ROUND_NO_EXC*/ || 1985 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 1986 return false; 1987 1988 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 1989 << Arg->getSourceRange(); 1990 } 1991 1992 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1993 if (BuiltinID == X86::BI__builtin_cpu_supports) 1994 return SemaBuiltinCpuSupports(*this, TheCall); 1995 1996 if (BuiltinID == X86::BI__builtin_ms_va_start) 1997 return SemaBuiltinMSVAStart(TheCall); 1998 1999 // If the intrinsic has rounding or SAE make sure its valid. 2000 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 2001 return true; 2002 2003 // For intrinsics which take an immediate value as part of the instruction, 2004 // range check them here. 2005 int i = 0, l = 0, u = 0; 2006 switch (BuiltinID) { 2007 default: 2008 return false; 2009 case X86::BI_mm_prefetch: 2010 i = 1; l = 0; u = 3; 2011 break; 2012 case X86::BI__builtin_ia32_sha1rnds4: 2013 case X86::BI__builtin_ia32_shuf_f32x4_256_mask: 2014 case X86::BI__builtin_ia32_shuf_f64x2_256_mask: 2015 case X86::BI__builtin_ia32_shuf_i32x4_256_mask: 2016 case X86::BI__builtin_ia32_shuf_i64x2_256_mask: 2017 i = 2; l = 0; u = 3; 2018 break; 2019 case X86::BI__builtin_ia32_vpermil2pd: 2020 case X86::BI__builtin_ia32_vpermil2pd256: 2021 case X86::BI__builtin_ia32_vpermil2ps: 2022 case X86::BI__builtin_ia32_vpermil2ps256: 2023 i = 3; l = 0; u = 3; 2024 break; 2025 case X86::BI__builtin_ia32_cmpb128_mask: 2026 case X86::BI__builtin_ia32_cmpw128_mask: 2027 case X86::BI__builtin_ia32_cmpd128_mask: 2028 case X86::BI__builtin_ia32_cmpq128_mask: 2029 case X86::BI__builtin_ia32_cmpb256_mask: 2030 case X86::BI__builtin_ia32_cmpw256_mask: 2031 case X86::BI__builtin_ia32_cmpd256_mask: 2032 case X86::BI__builtin_ia32_cmpq256_mask: 2033 case X86::BI__builtin_ia32_cmpb512_mask: 2034 case X86::BI__builtin_ia32_cmpw512_mask: 2035 case X86::BI__builtin_ia32_cmpd512_mask: 2036 case X86::BI__builtin_ia32_cmpq512_mask: 2037 case X86::BI__builtin_ia32_ucmpb128_mask: 2038 case X86::BI__builtin_ia32_ucmpw128_mask: 2039 case X86::BI__builtin_ia32_ucmpd128_mask: 2040 case X86::BI__builtin_ia32_ucmpq128_mask: 2041 case X86::BI__builtin_ia32_ucmpb256_mask: 2042 case X86::BI__builtin_ia32_ucmpw256_mask: 2043 case X86::BI__builtin_ia32_ucmpd256_mask: 2044 case X86::BI__builtin_ia32_ucmpq256_mask: 2045 case X86::BI__builtin_ia32_ucmpb512_mask: 2046 case X86::BI__builtin_ia32_ucmpw512_mask: 2047 case X86::BI__builtin_ia32_ucmpd512_mask: 2048 case X86::BI__builtin_ia32_ucmpq512_mask: 2049 case X86::BI__builtin_ia32_vpcomub: 2050 case X86::BI__builtin_ia32_vpcomuw: 2051 case X86::BI__builtin_ia32_vpcomud: 2052 case X86::BI__builtin_ia32_vpcomuq: 2053 case X86::BI__builtin_ia32_vpcomb: 2054 case X86::BI__builtin_ia32_vpcomw: 2055 case X86::BI__builtin_ia32_vpcomd: 2056 case X86::BI__builtin_ia32_vpcomq: 2057 i = 2; l = 0; u = 7; 2058 break; 2059 case X86::BI__builtin_ia32_roundps: 2060 case X86::BI__builtin_ia32_roundpd: 2061 case X86::BI__builtin_ia32_roundps256: 2062 case X86::BI__builtin_ia32_roundpd256: 2063 i = 1; l = 0; u = 15; 2064 break; 2065 case X86::BI__builtin_ia32_roundss: 2066 case X86::BI__builtin_ia32_roundsd: 2067 case X86::BI__builtin_ia32_rangepd128_mask: 2068 case X86::BI__builtin_ia32_rangepd256_mask: 2069 case X86::BI__builtin_ia32_rangepd512_mask: 2070 case X86::BI__builtin_ia32_rangeps128_mask: 2071 case X86::BI__builtin_ia32_rangeps256_mask: 2072 case X86::BI__builtin_ia32_rangeps512_mask: 2073 case X86::BI__builtin_ia32_getmantsd_round_mask: 2074 case X86::BI__builtin_ia32_getmantss_round_mask: 2075 i = 2; l = 0; u = 15; 2076 break; 2077 case X86::BI__builtin_ia32_cmpps: 2078 case X86::BI__builtin_ia32_cmpss: 2079 case X86::BI__builtin_ia32_cmppd: 2080 case X86::BI__builtin_ia32_cmpsd: 2081 case X86::BI__builtin_ia32_cmpps256: 2082 case X86::BI__builtin_ia32_cmppd256: 2083 case X86::BI__builtin_ia32_cmpps128_mask: 2084 case X86::BI__builtin_ia32_cmppd128_mask: 2085 case X86::BI__builtin_ia32_cmpps256_mask: 2086 case X86::BI__builtin_ia32_cmppd256_mask: 2087 case X86::BI__builtin_ia32_cmpps512_mask: 2088 case X86::BI__builtin_ia32_cmppd512_mask: 2089 case X86::BI__builtin_ia32_cmpsd_mask: 2090 case X86::BI__builtin_ia32_cmpss_mask: 2091 i = 2; l = 0; u = 31; 2092 break; 2093 case X86::BI__builtin_ia32_xabort: 2094 i = 0; l = -128; u = 255; 2095 break; 2096 case X86::BI__builtin_ia32_pshufw: 2097 case X86::BI__builtin_ia32_aeskeygenassist128: 2098 i = 1; l = -128; u = 255; 2099 break; 2100 case X86::BI__builtin_ia32_vcvtps2ph: 2101 case X86::BI__builtin_ia32_vcvtps2ph256: 2102 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2103 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2104 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2105 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2106 case X86::BI__builtin_ia32_rndscaleps_mask: 2107 case X86::BI__builtin_ia32_rndscalepd_mask: 2108 case X86::BI__builtin_ia32_reducepd128_mask: 2109 case X86::BI__builtin_ia32_reducepd256_mask: 2110 case X86::BI__builtin_ia32_reducepd512_mask: 2111 case X86::BI__builtin_ia32_reduceps128_mask: 2112 case X86::BI__builtin_ia32_reduceps256_mask: 2113 case X86::BI__builtin_ia32_reduceps512_mask: 2114 case X86::BI__builtin_ia32_prold512_mask: 2115 case X86::BI__builtin_ia32_prolq512_mask: 2116 case X86::BI__builtin_ia32_prold128_mask: 2117 case X86::BI__builtin_ia32_prold256_mask: 2118 case X86::BI__builtin_ia32_prolq128_mask: 2119 case X86::BI__builtin_ia32_prolq256_mask: 2120 case X86::BI__builtin_ia32_prord128_mask: 2121 case X86::BI__builtin_ia32_prord256_mask: 2122 case X86::BI__builtin_ia32_prorq128_mask: 2123 case X86::BI__builtin_ia32_prorq256_mask: 2124 case X86::BI__builtin_ia32_fpclasspd128_mask: 2125 case X86::BI__builtin_ia32_fpclasspd256_mask: 2126 case X86::BI__builtin_ia32_fpclassps128_mask: 2127 case X86::BI__builtin_ia32_fpclassps256_mask: 2128 case X86::BI__builtin_ia32_fpclassps512_mask: 2129 case X86::BI__builtin_ia32_fpclasspd512_mask: 2130 case X86::BI__builtin_ia32_fpclasssd_mask: 2131 case X86::BI__builtin_ia32_fpclassss_mask: 2132 i = 1; l = 0; u = 255; 2133 break; 2134 case X86::BI__builtin_ia32_palignr: 2135 case X86::BI__builtin_ia32_insertps128: 2136 case X86::BI__builtin_ia32_dpps: 2137 case X86::BI__builtin_ia32_dppd: 2138 case X86::BI__builtin_ia32_dpps256: 2139 case X86::BI__builtin_ia32_mpsadbw128: 2140 case X86::BI__builtin_ia32_mpsadbw256: 2141 case X86::BI__builtin_ia32_pcmpistrm128: 2142 case X86::BI__builtin_ia32_pcmpistri128: 2143 case X86::BI__builtin_ia32_pcmpistria128: 2144 case X86::BI__builtin_ia32_pcmpistric128: 2145 case X86::BI__builtin_ia32_pcmpistrio128: 2146 case X86::BI__builtin_ia32_pcmpistris128: 2147 case X86::BI__builtin_ia32_pcmpistriz128: 2148 case X86::BI__builtin_ia32_pclmulqdq128: 2149 case X86::BI__builtin_ia32_vperm2f128_pd256: 2150 case X86::BI__builtin_ia32_vperm2f128_ps256: 2151 case X86::BI__builtin_ia32_vperm2f128_si256: 2152 case X86::BI__builtin_ia32_permti256: 2153 i = 2; l = -128; u = 255; 2154 break; 2155 case X86::BI__builtin_ia32_palignr128: 2156 case X86::BI__builtin_ia32_palignr256: 2157 case X86::BI__builtin_ia32_palignr512_mask: 2158 case X86::BI__builtin_ia32_vcomisd: 2159 case X86::BI__builtin_ia32_vcomiss: 2160 case X86::BI__builtin_ia32_shuf_f32x4_mask: 2161 case X86::BI__builtin_ia32_shuf_f64x2_mask: 2162 case X86::BI__builtin_ia32_shuf_i32x4_mask: 2163 case X86::BI__builtin_ia32_shuf_i64x2_mask: 2164 case X86::BI__builtin_ia32_dbpsadbw128_mask: 2165 case X86::BI__builtin_ia32_dbpsadbw256_mask: 2166 case X86::BI__builtin_ia32_dbpsadbw512_mask: 2167 i = 2; l = 0; u = 255; 2168 break; 2169 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2170 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2171 case X86::BI__builtin_ia32_fixupimmps512_mask: 2172 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2173 case X86::BI__builtin_ia32_fixupimmsd_mask: 2174 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2175 case X86::BI__builtin_ia32_fixupimmss_mask: 2176 case X86::BI__builtin_ia32_fixupimmss_maskz: 2177 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2178 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2179 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2180 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2181 case X86::BI__builtin_ia32_fixupimmps128_mask: 2182 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2183 case X86::BI__builtin_ia32_fixupimmps256_mask: 2184 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2185 case X86::BI__builtin_ia32_pternlogd512_mask: 2186 case X86::BI__builtin_ia32_pternlogd512_maskz: 2187 case X86::BI__builtin_ia32_pternlogq512_mask: 2188 case X86::BI__builtin_ia32_pternlogq512_maskz: 2189 case X86::BI__builtin_ia32_pternlogd128_mask: 2190 case X86::BI__builtin_ia32_pternlogd128_maskz: 2191 case X86::BI__builtin_ia32_pternlogd256_mask: 2192 case X86::BI__builtin_ia32_pternlogd256_maskz: 2193 case X86::BI__builtin_ia32_pternlogq128_mask: 2194 case X86::BI__builtin_ia32_pternlogq128_maskz: 2195 case X86::BI__builtin_ia32_pternlogq256_mask: 2196 case X86::BI__builtin_ia32_pternlogq256_maskz: 2197 i = 3; l = 0; u = 255; 2198 break; 2199 case X86::BI__builtin_ia32_pcmpestrm128: 2200 case X86::BI__builtin_ia32_pcmpestri128: 2201 case X86::BI__builtin_ia32_pcmpestria128: 2202 case X86::BI__builtin_ia32_pcmpestric128: 2203 case X86::BI__builtin_ia32_pcmpestrio128: 2204 case X86::BI__builtin_ia32_pcmpestris128: 2205 case X86::BI__builtin_ia32_pcmpestriz128: 2206 i = 4; l = -128; u = 255; 2207 break; 2208 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2209 case X86::BI__builtin_ia32_rndscaless_round_mask: 2210 i = 4; l = 0; u = 255; 2211 break; 2212 } 2213 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2214 } 2215 2216 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2217 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2218 /// Returns true when the format fits the function and the FormatStringInfo has 2219 /// been populated. 2220 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2221 FormatStringInfo *FSI) { 2222 FSI->HasVAListArg = Format->getFirstArg() == 0; 2223 FSI->FormatIdx = Format->getFormatIdx() - 1; 2224 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2225 2226 // The way the format attribute works in GCC, the implicit this argument 2227 // of member functions is counted. However, it doesn't appear in our own 2228 // lists, so decrement format_idx in that case. 2229 if (IsCXXMember) { 2230 if(FSI->FormatIdx == 0) 2231 return false; 2232 --FSI->FormatIdx; 2233 if (FSI->FirstDataArg != 0) 2234 --FSI->FirstDataArg; 2235 } 2236 return true; 2237 } 2238 2239 /// Checks if a the given expression evaluates to null. 2240 /// 2241 /// \brief Returns true if the value evaluates to null. 2242 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2243 // If the expression has non-null type, it doesn't evaluate to null. 2244 if (auto nullability 2245 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2246 if (*nullability == NullabilityKind::NonNull) 2247 return false; 2248 } 2249 2250 // As a special case, transparent unions initialized with zero are 2251 // considered null for the purposes of the nonnull attribute. 2252 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2253 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2254 if (const CompoundLiteralExpr *CLE = 2255 dyn_cast<CompoundLiteralExpr>(Expr)) 2256 if (const InitListExpr *ILE = 2257 dyn_cast<InitListExpr>(CLE->getInitializer())) 2258 Expr = ILE->getInit(0); 2259 } 2260 2261 bool Result; 2262 return (!Expr->isValueDependent() && 2263 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2264 !Result); 2265 } 2266 2267 static void CheckNonNullArgument(Sema &S, 2268 const Expr *ArgExpr, 2269 SourceLocation CallSiteLoc) { 2270 if (CheckNonNullExpr(S, ArgExpr)) 2271 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2272 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2273 } 2274 2275 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2276 FormatStringInfo FSI; 2277 if ((GetFormatStringType(Format) == FST_NSString) && 2278 getFormatStringInfo(Format, false, &FSI)) { 2279 Idx = FSI.FormatIdx; 2280 return true; 2281 } 2282 return false; 2283 } 2284 /// \brief Diagnose use of %s directive in an NSString which is being passed 2285 /// as formatting string to formatting method. 2286 static void 2287 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 2288 const NamedDecl *FDecl, 2289 Expr **Args, 2290 unsigned NumArgs) { 2291 unsigned Idx = 0; 2292 bool Format = false; 2293 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 2294 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 2295 Idx = 2; 2296 Format = true; 2297 } 2298 else 2299 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2300 if (S.GetFormatNSStringIdx(I, Idx)) { 2301 Format = true; 2302 break; 2303 } 2304 } 2305 if (!Format || NumArgs <= Idx) 2306 return; 2307 const Expr *FormatExpr = Args[Idx]; 2308 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2309 FormatExpr = CSCE->getSubExpr(); 2310 const StringLiteral *FormatString; 2311 if (const ObjCStringLiteral *OSL = 2312 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2313 FormatString = OSL->getString(); 2314 else 2315 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2316 if (!FormatString) 2317 return; 2318 if (S.FormatStringHasSArg(FormatString)) { 2319 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2320 << "%s" << 1 << 1; 2321 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2322 << FDecl->getDeclName(); 2323 } 2324 } 2325 2326 /// Determine whether the given type has a non-null nullability annotation. 2327 static bool isNonNullType(ASTContext &ctx, QualType type) { 2328 if (auto nullability = type->getNullability(ctx)) 2329 return *nullability == NullabilityKind::NonNull; 2330 2331 return false; 2332 } 2333 2334 static void CheckNonNullArguments(Sema &S, 2335 const NamedDecl *FDecl, 2336 const FunctionProtoType *Proto, 2337 ArrayRef<const Expr *> Args, 2338 SourceLocation CallSiteLoc) { 2339 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2340 2341 // Check the attributes attached to the method/function itself. 2342 llvm::SmallBitVector NonNullArgs; 2343 if (FDecl) { 2344 // Handle the nonnull attribute on the function/method declaration itself. 2345 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2346 if (!NonNull->args_size()) { 2347 // Easy case: all pointer arguments are nonnull. 2348 for (const auto *Arg : Args) 2349 if (S.isValidPointerAttrType(Arg->getType())) 2350 CheckNonNullArgument(S, Arg, CallSiteLoc); 2351 return; 2352 } 2353 2354 for (unsigned Val : NonNull->args()) { 2355 if (Val >= Args.size()) 2356 continue; 2357 if (NonNullArgs.empty()) 2358 NonNullArgs.resize(Args.size()); 2359 NonNullArgs.set(Val); 2360 } 2361 } 2362 } 2363 2364 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2365 // Handle the nonnull attribute on the parameters of the 2366 // function/method. 2367 ArrayRef<ParmVarDecl*> parms; 2368 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2369 parms = FD->parameters(); 2370 else 2371 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2372 2373 unsigned ParamIndex = 0; 2374 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2375 I != E; ++I, ++ParamIndex) { 2376 const ParmVarDecl *PVD = *I; 2377 if (PVD->hasAttr<NonNullAttr>() || 2378 isNonNullType(S.Context, PVD->getType())) { 2379 if (NonNullArgs.empty()) 2380 NonNullArgs.resize(Args.size()); 2381 2382 NonNullArgs.set(ParamIndex); 2383 } 2384 } 2385 } else { 2386 // If we have a non-function, non-method declaration but no 2387 // function prototype, try to dig out the function prototype. 2388 if (!Proto) { 2389 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2390 QualType type = VD->getType().getNonReferenceType(); 2391 if (auto pointerType = type->getAs<PointerType>()) 2392 type = pointerType->getPointeeType(); 2393 else if (auto blockType = type->getAs<BlockPointerType>()) 2394 type = blockType->getPointeeType(); 2395 // FIXME: data member pointers? 2396 2397 // Dig out the function prototype, if there is one. 2398 Proto = type->getAs<FunctionProtoType>(); 2399 } 2400 } 2401 2402 // Fill in non-null argument information from the nullability 2403 // information on the parameter types (if we have them). 2404 if (Proto) { 2405 unsigned Index = 0; 2406 for (auto paramType : Proto->getParamTypes()) { 2407 if (isNonNullType(S.Context, paramType)) { 2408 if (NonNullArgs.empty()) 2409 NonNullArgs.resize(Args.size()); 2410 2411 NonNullArgs.set(Index); 2412 } 2413 2414 ++Index; 2415 } 2416 } 2417 } 2418 2419 // Check for non-null arguments. 2420 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2421 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2422 if (NonNullArgs[ArgIndex]) 2423 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2424 } 2425 } 2426 2427 /// Handles the checks for format strings, non-POD arguments to vararg 2428 /// functions, and NULL arguments passed to non-NULL parameters. 2429 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2430 ArrayRef<const Expr *> Args, bool IsMemberFunction, 2431 SourceLocation Loc, SourceRange Range, 2432 VariadicCallType CallType) { 2433 // FIXME: We should check as much as we can in the template definition. 2434 if (CurContext->isDependentContext()) 2435 return; 2436 2437 // Printf and scanf checking. 2438 llvm::SmallBitVector CheckedVarArgs; 2439 if (FDecl) { 2440 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2441 // Only create vector if there are format attributes. 2442 CheckedVarArgs.resize(Args.size()); 2443 2444 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2445 CheckedVarArgs); 2446 } 2447 } 2448 2449 // Refuse POD arguments that weren't caught by the format string 2450 // checks above. 2451 if (CallType != VariadicDoesNotApply) { 2452 unsigned NumParams = Proto ? Proto->getNumParams() 2453 : FDecl && isa<FunctionDecl>(FDecl) 2454 ? cast<FunctionDecl>(FDecl)->getNumParams() 2455 : FDecl && isa<ObjCMethodDecl>(FDecl) 2456 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2457 : 0; 2458 2459 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2460 // Args[ArgIdx] can be null in malformed code. 2461 if (const Expr *Arg = Args[ArgIdx]) { 2462 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 2463 checkVariadicArgument(Arg, CallType); 2464 } 2465 } 2466 } 2467 2468 if (FDecl || Proto) { 2469 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 2470 2471 // Type safety checking. 2472 if (FDecl) { 2473 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 2474 CheckArgumentWithTypeTag(I, Args.data()); 2475 } 2476 } 2477 } 2478 2479 /// CheckConstructorCall - Check a constructor call for correctness and safety 2480 /// properties not enforced by the C type system. 2481 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 2482 ArrayRef<const Expr *> Args, 2483 const FunctionProtoType *Proto, 2484 SourceLocation Loc) { 2485 VariadicCallType CallType = 2486 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 2487 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(), 2488 CallType); 2489 } 2490 2491 /// CheckFunctionCall - Check a direct function call for various correctness 2492 /// and safety properties not strictly enforced by the C type system. 2493 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2494 const FunctionProtoType *Proto) { 2495 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 2496 isa<CXXMethodDecl>(FDecl); 2497 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 2498 IsMemberOperatorCall; 2499 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 2500 TheCall->getCallee()); 2501 Expr** Args = TheCall->getArgs(); 2502 unsigned NumArgs = TheCall->getNumArgs(); 2503 if (IsMemberOperatorCall) { 2504 // If this is a call to a member operator, hide the first argument 2505 // from checkCall. 2506 // FIXME: Our choice of AST representation here is less than ideal. 2507 ++Args; 2508 --NumArgs; 2509 } 2510 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs), 2511 IsMemberFunction, TheCall->getRParenLoc(), 2512 TheCall->getCallee()->getSourceRange(), CallType); 2513 2514 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 2515 // None of the checks below are needed for functions that don't have 2516 // simple names (e.g., C++ conversion functions). 2517 if (!FnInfo) 2518 return false; 2519 2520 CheckAbsoluteValueFunction(TheCall, FDecl); 2521 CheckMaxUnsignedZero(TheCall, FDecl); 2522 2523 if (getLangOpts().ObjC1) 2524 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 2525 2526 unsigned CMId = FDecl->getMemoryFunctionKind(); 2527 if (CMId == 0) 2528 return false; 2529 2530 // Handle memory setting and copying functions. 2531 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 2532 CheckStrlcpycatArguments(TheCall, FnInfo); 2533 else if (CMId == Builtin::BIstrncat) 2534 CheckStrncatArguments(TheCall, FnInfo); 2535 else 2536 CheckMemaccessArguments(TheCall, CMId, FnInfo); 2537 2538 return false; 2539 } 2540 2541 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 2542 ArrayRef<const Expr *> Args) { 2543 VariadicCallType CallType = 2544 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 2545 2546 checkCall(Method, nullptr, Args, 2547 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 2548 CallType); 2549 2550 return false; 2551 } 2552 2553 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2554 const FunctionProtoType *Proto) { 2555 QualType Ty; 2556 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 2557 Ty = V->getType().getNonReferenceType(); 2558 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 2559 Ty = F->getType().getNonReferenceType(); 2560 else 2561 return false; 2562 2563 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 2564 !Ty->isFunctionProtoType()) 2565 return false; 2566 2567 VariadicCallType CallType; 2568 if (!Proto || !Proto->isVariadic()) { 2569 CallType = VariadicDoesNotApply; 2570 } else if (Ty->isBlockPointerType()) { 2571 CallType = VariadicBlock; 2572 } else { // Ty->isFunctionPointerType() 2573 CallType = VariadicFunction; 2574 } 2575 2576 checkCall(NDecl, Proto, 2577 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2578 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2579 TheCall->getCallee()->getSourceRange(), CallType); 2580 2581 return false; 2582 } 2583 2584 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2585 /// such as function pointers returned from functions. 2586 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 2587 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 2588 TheCall->getCallee()); 2589 checkCall(/*FDecl=*/nullptr, Proto, 2590 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2591 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2592 TheCall->getCallee()->getSourceRange(), CallType); 2593 2594 return false; 2595 } 2596 2597 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 2598 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 2599 return false; 2600 2601 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 2602 switch (Op) { 2603 case AtomicExpr::AO__c11_atomic_init: 2604 llvm_unreachable("There is no ordering argument for an init"); 2605 2606 case AtomicExpr::AO__c11_atomic_load: 2607 case AtomicExpr::AO__atomic_load_n: 2608 case AtomicExpr::AO__atomic_load: 2609 return OrderingCABI != llvm::AtomicOrderingCABI::release && 2610 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2611 2612 case AtomicExpr::AO__c11_atomic_store: 2613 case AtomicExpr::AO__atomic_store: 2614 case AtomicExpr::AO__atomic_store_n: 2615 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 2616 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 2617 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2618 2619 default: 2620 return true; 2621 } 2622 } 2623 2624 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 2625 AtomicExpr::AtomicOp Op) { 2626 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 2627 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2628 2629 // All these operations take one of the following forms: 2630 enum { 2631 // C __c11_atomic_init(A *, C) 2632 Init, 2633 // C __c11_atomic_load(A *, int) 2634 Load, 2635 // void __atomic_load(A *, CP, int) 2636 LoadCopy, 2637 // void __atomic_store(A *, CP, int) 2638 Copy, 2639 // C __c11_atomic_add(A *, M, int) 2640 Arithmetic, 2641 // C __atomic_exchange_n(A *, CP, int) 2642 Xchg, 2643 // void __atomic_exchange(A *, C *, CP, int) 2644 GNUXchg, 2645 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 2646 C11CmpXchg, 2647 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 2648 GNUCmpXchg 2649 } Form = Init; 2650 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 2651 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 2652 // where: 2653 // C is an appropriate type, 2654 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 2655 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 2656 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 2657 // the int parameters are for orderings. 2658 2659 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 2660 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 2661 AtomicExpr::AO__atomic_load, 2662 "need to update code for modified C11 atomics"); 2663 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init && 2664 Op <= AtomicExpr::AO__c11_atomic_fetch_xor; 2665 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 2666 Op == AtomicExpr::AO__atomic_store_n || 2667 Op == AtomicExpr::AO__atomic_exchange_n || 2668 Op == AtomicExpr::AO__atomic_compare_exchange_n; 2669 bool IsAddSub = false; 2670 2671 switch (Op) { 2672 case AtomicExpr::AO__c11_atomic_init: 2673 Form = Init; 2674 break; 2675 2676 case AtomicExpr::AO__c11_atomic_load: 2677 case AtomicExpr::AO__atomic_load_n: 2678 Form = Load; 2679 break; 2680 2681 case AtomicExpr::AO__atomic_load: 2682 Form = LoadCopy; 2683 break; 2684 2685 case AtomicExpr::AO__c11_atomic_store: 2686 case AtomicExpr::AO__atomic_store: 2687 case AtomicExpr::AO__atomic_store_n: 2688 Form = Copy; 2689 break; 2690 2691 case AtomicExpr::AO__c11_atomic_fetch_add: 2692 case AtomicExpr::AO__c11_atomic_fetch_sub: 2693 case AtomicExpr::AO__atomic_fetch_add: 2694 case AtomicExpr::AO__atomic_fetch_sub: 2695 case AtomicExpr::AO__atomic_add_fetch: 2696 case AtomicExpr::AO__atomic_sub_fetch: 2697 IsAddSub = true; 2698 // Fall through. 2699 case AtomicExpr::AO__c11_atomic_fetch_and: 2700 case AtomicExpr::AO__c11_atomic_fetch_or: 2701 case AtomicExpr::AO__c11_atomic_fetch_xor: 2702 case AtomicExpr::AO__atomic_fetch_and: 2703 case AtomicExpr::AO__atomic_fetch_or: 2704 case AtomicExpr::AO__atomic_fetch_xor: 2705 case AtomicExpr::AO__atomic_fetch_nand: 2706 case AtomicExpr::AO__atomic_and_fetch: 2707 case AtomicExpr::AO__atomic_or_fetch: 2708 case AtomicExpr::AO__atomic_xor_fetch: 2709 case AtomicExpr::AO__atomic_nand_fetch: 2710 Form = Arithmetic; 2711 break; 2712 2713 case AtomicExpr::AO__c11_atomic_exchange: 2714 case AtomicExpr::AO__atomic_exchange_n: 2715 Form = Xchg; 2716 break; 2717 2718 case AtomicExpr::AO__atomic_exchange: 2719 Form = GNUXchg; 2720 break; 2721 2722 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 2723 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 2724 Form = C11CmpXchg; 2725 break; 2726 2727 case AtomicExpr::AO__atomic_compare_exchange: 2728 case AtomicExpr::AO__atomic_compare_exchange_n: 2729 Form = GNUCmpXchg; 2730 break; 2731 } 2732 2733 // Check we have the right number of arguments. 2734 if (TheCall->getNumArgs() < NumArgs[Form]) { 2735 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 2736 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2737 << TheCall->getCallee()->getSourceRange(); 2738 return ExprError(); 2739 } else if (TheCall->getNumArgs() > NumArgs[Form]) { 2740 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(), 2741 diag::err_typecheck_call_too_many_args) 2742 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2743 << TheCall->getCallee()->getSourceRange(); 2744 return ExprError(); 2745 } 2746 2747 // Inspect the first argument of the atomic operation. 2748 Expr *Ptr = TheCall->getArg(0); 2749 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 2750 if (ConvertedPtr.isInvalid()) 2751 return ExprError(); 2752 2753 Ptr = ConvertedPtr.get(); 2754 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 2755 if (!pointerType) { 2756 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 2757 << Ptr->getType() << Ptr->getSourceRange(); 2758 return ExprError(); 2759 } 2760 2761 // For a __c11 builtin, this should be a pointer to an _Atomic type. 2762 QualType AtomTy = pointerType->getPointeeType(); // 'A' 2763 QualType ValType = AtomTy; // 'C' 2764 if (IsC11) { 2765 if (!AtomTy->isAtomicType()) { 2766 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 2767 << Ptr->getType() << Ptr->getSourceRange(); 2768 return ExprError(); 2769 } 2770 if (AtomTy.isConstQualified()) { 2771 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 2772 << Ptr->getType() << Ptr->getSourceRange(); 2773 return ExprError(); 2774 } 2775 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 2776 } else if (Form != Load && Form != LoadCopy) { 2777 if (ValType.isConstQualified()) { 2778 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 2779 << Ptr->getType() << Ptr->getSourceRange(); 2780 return ExprError(); 2781 } 2782 } 2783 2784 // For an arithmetic operation, the implied arithmetic must be well-formed. 2785 if (Form == Arithmetic) { 2786 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 2787 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 2788 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2789 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2790 return ExprError(); 2791 } 2792 if (!IsAddSub && !ValType->isIntegerType()) { 2793 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 2794 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2795 return ExprError(); 2796 } 2797 if (IsC11 && ValType->isPointerType() && 2798 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 2799 diag::err_incomplete_type)) { 2800 return ExprError(); 2801 } 2802 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 2803 // For __atomic_*_n operations, the value type must be a scalar integral or 2804 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 2805 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2806 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2807 return ExprError(); 2808 } 2809 2810 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 2811 !AtomTy->isScalarType()) { 2812 // For GNU atomics, require a trivially-copyable type. This is not part of 2813 // the GNU atomics specification, but we enforce it for sanity. 2814 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 2815 << Ptr->getType() << Ptr->getSourceRange(); 2816 return ExprError(); 2817 } 2818 2819 switch (ValType.getObjCLifetime()) { 2820 case Qualifiers::OCL_None: 2821 case Qualifiers::OCL_ExplicitNone: 2822 // okay 2823 break; 2824 2825 case Qualifiers::OCL_Weak: 2826 case Qualifiers::OCL_Strong: 2827 case Qualifiers::OCL_Autoreleasing: 2828 // FIXME: Can this happen? By this point, ValType should be known 2829 // to be trivially copyable. 2830 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 2831 << ValType << Ptr->getSourceRange(); 2832 return ExprError(); 2833 } 2834 2835 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 2836 // volatile-ness of the pointee-type inject itself into the result or the 2837 // other operands. Similarly atomic_load can take a pointer to a const 'A'. 2838 ValType.removeLocalVolatile(); 2839 ValType.removeLocalConst(); 2840 QualType ResultType = ValType; 2841 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init) 2842 ResultType = Context.VoidTy; 2843 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 2844 ResultType = Context.BoolTy; 2845 2846 // The type of a parameter passed 'by value'. In the GNU atomics, such 2847 // arguments are actually passed as pointers. 2848 QualType ByValType = ValType; // 'CP' 2849 if (!IsC11 && !IsN) 2850 ByValType = Ptr->getType(); 2851 2852 // The first argument --- the pointer --- has a fixed type; we 2853 // deduce the types of the rest of the arguments accordingly. Walk 2854 // the remaining arguments, converting them to the deduced value type. 2855 for (unsigned i = 1; i != NumArgs[Form]; ++i) { 2856 QualType Ty; 2857 if (i < NumVals[Form] + 1) { 2858 switch (i) { 2859 case 1: 2860 // The second argument is the non-atomic operand. For arithmetic, this 2861 // is always passed by value, and for a compare_exchange it is always 2862 // passed by address. For the rest, GNU uses by-address and C11 uses 2863 // by-value. 2864 assert(Form != Load); 2865 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 2866 Ty = ValType; 2867 else if (Form == Copy || Form == Xchg) 2868 Ty = ByValType; 2869 else if (Form == Arithmetic) 2870 Ty = Context.getPointerDiffType(); 2871 else { 2872 Expr *ValArg = TheCall->getArg(i); 2873 // Treat this argument as _Nonnull as we want to show a warning if 2874 // NULL is passed into it. 2875 CheckNonNullArgument(*this, ValArg, DRE->getLocStart()); 2876 unsigned AS = 0; 2877 // Keep address space of non-atomic pointer type. 2878 if (const PointerType *PtrTy = 2879 ValArg->getType()->getAs<PointerType>()) { 2880 AS = PtrTy->getPointeeType().getAddressSpace(); 2881 } 2882 Ty = Context.getPointerType( 2883 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 2884 } 2885 break; 2886 case 2: 2887 // The third argument to compare_exchange / GNU exchange is a 2888 // (pointer to a) desired value. 2889 Ty = ByValType; 2890 break; 2891 case 3: 2892 // The fourth argument to GNU compare_exchange is a 'weak' flag. 2893 Ty = Context.BoolTy; 2894 break; 2895 } 2896 } else { 2897 // The order(s) are always converted to int. 2898 Ty = Context.IntTy; 2899 } 2900 2901 InitializedEntity Entity = 2902 InitializedEntity::InitializeParameter(Context, Ty, false); 2903 ExprResult Arg = TheCall->getArg(i); 2904 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 2905 if (Arg.isInvalid()) 2906 return true; 2907 TheCall->setArg(i, Arg.get()); 2908 } 2909 2910 // Permute the arguments into a 'consistent' order. 2911 SmallVector<Expr*, 5> SubExprs; 2912 SubExprs.push_back(Ptr); 2913 switch (Form) { 2914 case Init: 2915 // Note, AtomicExpr::getVal1() has a special case for this atomic. 2916 SubExprs.push_back(TheCall->getArg(1)); // Val1 2917 break; 2918 case Load: 2919 SubExprs.push_back(TheCall->getArg(1)); // Order 2920 break; 2921 case LoadCopy: 2922 case Copy: 2923 case Arithmetic: 2924 case Xchg: 2925 SubExprs.push_back(TheCall->getArg(2)); // Order 2926 SubExprs.push_back(TheCall->getArg(1)); // Val1 2927 break; 2928 case GNUXchg: 2929 // Note, AtomicExpr::getVal2() has a special case for this atomic. 2930 SubExprs.push_back(TheCall->getArg(3)); // Order 2931 SubExprs.push_back(TheCall->getArg(1)); // Val1 2932 SubExprs.push_back(TheCall->getArg(2)); // Val2 2933 break; 2934 case C11CmpXchg: 2935 SubExprs.push_back(TheCall->getArg(3)); // Order 2936 SubExprs.push_back(TheCall->getArg(1)); // Val1 2937 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 2938 SubExprs.push_back(TheCall->getArg(2)); // Val2 2939 break; 2940 case GNUCmpXchg: 2941 SubExprs.push_back(TheCall->getArg(4)); // Order 2942 SubExprs.push_back(TheCall->getArg(1)); // Val1 2943 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 2944 SubExprs.push_back(TheCall->getArg(2)); // Val2 2945 SubExprs.push_back(TheCall->getArg(3)); // Weak 2946 break; 2947 } 2948 2949 if (SubExprs.size() >= 2 && Form != Init) { 2950 llvm::APSInt Result(32); 2951 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 2952 !isValidOrderingForOp(Result.getSExtValue(), Op)) 2953 Diag(SubExprs[1]->getLocStart(), 2954 diag::warn_atomic_op_has_invalid_memory_order) 2955 << SubExprs[1]->getSourceRange(); 2956 } 2957 2958 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 2959 SubExprs, ResultType, Op, 2960 TheCall->getRParenLoc()); 2961 2962 if ((Op == AtomicExpr::AO__c11_atomic_load || 2963 (Op == AtomicExpr::AO__c11_atomic_store)) && 2964 Context.AtomicUsesUnsupportedLibcall(AE)) 2965 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) << 2966 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1); 2967 2968 return AE; 2969 } 2970 2971 /// checkBuiltinArgument - Given a call to a builtin function, perform 2972 /// normal type-checking on the given argument, updating the call in 2973 /// place. This is useful when a builtin function requires custom 2974 /// type-checking for some of its arguments but not necessarily all of 2975 /// them. 2976 /// 2977 /// Returns true on error. 2978 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 2979 FunctionDecl *Fn = E->getDirectCallee(); 2980 assert(Fn && "builtin call without direct callee!"); 2981 2982 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 2983 InitializedEntity Entity = 2984 InitializedEntity::InitializeParameter(S.Context, Param); 2985 2986 ExprResult Arg = E->getArg(0); 2987 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 2988 if (Arg.isInvalid()) 2989 return true; 2990 2991 E->setArg(ArgIndex, Arg.get()); 2992 return false; 2993 } 2994 2995 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 2996 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 2997 /// type of its first argument. The main ActOnCallExpr routines have already 2998 /// promoted the types of arguments because all of these calls are prototyped as 2999 /// void(...). 3000 /// 3001 /// This function goes through and does final semantic checking for these 3002 /// builtins, 3003 ExprResult 3004 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3005 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3006 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3007 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3008 3009 // Ensure that we have at least one argument to do type inference from. 3010 if (TheCall->getNumArgs() < 1) { 3011 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3012 << 0 << 1 << TheCall->getNumArgs() 3013 << TheCall->getCallee()->getSourceRange(); 3014 return ExprError(); 3015 } 3016 3017 // Inspect the first argument of the atomic builtin. This should always be 3018 // a pointer type, whose element is an integral scalar or pointer type. 3019 // Because it is a pointer type, we don't have to worry about any implicit 3020 // casts here. 3021 // FIXME: We don't allow floating point scalars as input. 3022 Expr *FirstArg = TheCall->getArg(0); 3023 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3024 if (FirstArgResult.isInvalid()) 3025 return ExprError(); 3026 FirstArg = FirstArgResult.get(); 3027 TheCall->setArg(0, FirstArg); 3028 3029 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3030 if (!pointerType) { 3031 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3032 << FirstArg->getType() << FirstArg->getSourceRange(); 3033 return ExprError(); 3034 } 3035 3036 QualType ValType = pointerType->getPointeeType(); 3037 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3038 !ValType->isBlockPointerType()) { 3039 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3040 << FirstArg->getType() << FirstArg->getSourceRange(); 3041 return ExprError(); 3042 } 3043 3044 switch (ValType.getObjCLifetime()) { 3045 case Qualifiers::OCL_None: 3046 case Qualifiers::OCL_ExplicitNone: 3047 // okay 3048 break; 3049 3050 case Qualifiers::OCL_Weak: 3051 case Qualifiers::OCL_Strong: 3052 case Qualifiers::OCL_Autoreleasing: 3053 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3054 << ValType << FirstArg->getSourceRange(); 3055 return ExprError(); 3056 } 3057 3058 // Strip any qualifiers off ValType. 3059 ValType = ValType.getUnqualifiedType(); 3060 3061 // The majority of builtins return a value, but a few have special return 3062 // types, so allow them to override appropriately below. 3063 QualType ResultType = ValType; 3064 3065 // We need to figure out which concrete builtin this maps onto. For example, 3066 // __sync_fetch_and_add with a 2 byte object turns into 3067 // __sync_fetch_and_add_2. 3068 #define BUILTIN_ROW(x) \ 3069 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3070 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3071 3072 static const unsigned BuiltinIndices[][5] = { 3073 BUILTIN_ROW(__sync_fetch_and_add), 3074 BUILTIN_ROW(__sync_fetch_and_sub), 3075 BUILTIN_ROW(__sync_fetch_and_or), 3076 BUILTIN_ROW(__sync_fetch_and_and), 3077 BUILTIN_ROW(__sync_fetch_and_xor), 3078 BUILTIN_ROW(__sync_fetch_and_nand), 3079 3080 BUILTIN_ROW(__sync_add_and_fetch), 3081 BUILTIN_ROW(__sync_sub_and_fetch), 3082 BUILTIN_ROW(__sync_and_and_fetch), 3083 BUILTIN_ROW(__sync_or_and_fetch), 3084 BUILTIN_ROW(__sync_xor_and_fetch), 3085 BUILTIN_ROW(__sync_nand_and_fetch), 3086 3087 BUILTIN_ROW(__sync_val_compare_and_swap), 3088 BUILTIN_ROW(__sync_bool_compare_and_swap), 3089 BUILTIN_ROW(__sync_lock_test_and_set), 3090 BUILTIN_ROW(__sync_lock_release), 3091 BUILTIN_ROW(__sync_swap) 3092 }; 3093 #undef BUILTIN_ROW 3094 3095 // Determine the index of the size. 3096 unsigned SizeIndex; 3097 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3098 case 1: SizeIndex = 0; break; 3099 case 2: SizeIndex = 1; break; 3100 case 4: SizeIndex = 2; break; 3101 case 8: SizeIndex = 3; break; 3102 case 16: SizeIndex = 4; break; 3103 default: 3104 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3105 << FirstArg->getType() << FirstArg->getSourceRange(); 3106 return ExprError(); 3107 } 3108 3109 // Each of these builtins has one pointer argument, followed by some number of 3110 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3111 // that we ignore. Find out which row of BuiltinIndices to read from as well 3112 // as the number of fixed args. 3113 unsigned BuiltinID = FDecl->getBuiltinID(); 3114 unsigned BuiltinIndex, NumFixed = 1; 3115 bool WarnAboutSemanticsChange = false; 3116 switch (BuiltinID) { 3117 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3118 case Builtin::BI__sync_fetch_and_add: 3119 case Builtin::BI__sync_fetch_and_add_1: 3120 case Builtin::BI__sync_fetch_and_add_2: 3121 case Builtin::BI__sync_fetch_and_add_4: 3122 case Builtin::BI__sync_fetch_and_add_8: 3123 case Builtin::BI__sync_fetch_and_add_16: 3124 BuiltinIndex = 0; 3125 break; 3126 3127 case Builtin::BI__sync_fetch_and_sub: 3128 case Builtin::BI__sync_fetch_and_sub_1: 3129 case Builtin::BI__sync_fetch_and_sub_2: 3130 case Builtin::BI__sync_fetch_and_sub_4: 3131 case Builtin::BI__sync_fetch_and_sub_8: 3132 case Builtin::BI__sync_fetch_and_sub_16: 3133 BuiltinIndex = 1; 3134 break; 3135 3136 case Builtin::BI__sync_fetch_and_or: 3137 case Builtin::BI__sync_fetch_and_or_1: 3138 case Builtin::BI__sync_fetch_and_or_2: 3139 case Builtin::BI__sync_fetch_and_or_4: 3140 case Builtin::BI__sync_fetch_and_or_8: 3141 case Builtin::BI__sync_fetch_and_or_16: 3142 BuiltinIndex = 2; 3143 break; 3144 3145 case Builtin::BI__sync_fetch_and_and: 3146 case Builtin::BI__sync_fetch_and_and_1: 3147 case Builtin::BI__sync_fetch_and_and_2: 3148 case Builtin::BI__sync_fetch_and_and_4: 3149 case Builtin::BI__sync_fetch_and_and_8: 3150 case Builtin::BI__sync_fetch_and_and_16: 3151 BuiltinIndex = 3; 3152 break; 3153 3154 case Builtin::BI__sync_fetch_and_xor: 3155 case Builtin::BI__sync_fetch_and_xor_1: 3156 case Builtin::BI__sync_fetch_and_xor_2: 3157 case Builtin::BI__sync_fetch_and_xor_4: 3158 case Builtin::BI__sync_fetch_and_xor_8: 3159 case Builtin::BI__sync_fetch_and_xor_16: 3160 BuiltinIndex = 4; 3161 break; 3162 3163 case Builtin::BI__sync_fetch_and_nand: 3164 case Builtin::BI__sync_fetch_and_nand_1: 3165 case Builtin::BI__sync_fetch_and_nand_2: 3166 case Builtin::BI__sync_fetch_and_nand_4: 3167 case Builtin::BI__sync_fetch_and_nand_8: 3168 case Builtin::BI__sync_fetch_and_nand_16: 3169 BuiltinIndex = 5; 3170 WarnAboutSemanticsChange = true; 3171 break; 3172 3173 case Builtin::BI__sync_add_and_fetch: 3174 case Builtin::BI__sync_add_and_fetch_1: 3175 case Builtin::BI__sync_add_and_fetch_2: 3176 case Builtin::BI__sync_add_and_fetch_4: 3177 case Builtin::BI__sync_add_and_fetch_8: 3178 case Builtin::BI__sync_add_and_fetch_16: 3179 BuiltinIndex = 6; 3180 break; 3181 3182 case Builtin::BI__sync_sub_and_fetch: 3183 case Builtin::BI__sync_sub_and_fetch_1: 3184 case Builtin::BI__sync_sub_and_fetch_2: 3185 case Builtin::BI__sync_sub_and_fetch_4: 3186 case Builtin::BI__sync_sub_and_fetch_8: 3187 case Builtin::BI__sync_sub_and_fetch_16: 3188 BuiltinIndex = 7; 3189 break; 3190 3191 case Builtin::BI__sync_and_and_fetch: 3192 case Builtin::BI__sync_and_and_fetch_1: 3193 case Builtin::BI__sync_and_and_fetch_2: 3194 case Builtin::BI__sync_and_and_fetch_4: 3195 case Builtin::BI__sync_and_and_fetch_8: 3196 case Builtin::BI__sync_and_and_fetch_16: 3197 BuiltinIndex = 8; 3198 break; 3199 3200 case Builtin::BI__sync_or_and_fetch: 3201 case Builtin::BI__sync_or_and_fetch_1: 3202 case Builtin::BI__sync_or_and_fetch_2: 3203 case Builtin::BI__sync_or_and_fetch_4: 3204 case Builtin::BI__sync_or_and_fetch_8: 3205 case Builtin::BI__sync_or_and_fetch_16: 3206 BuiltinIndex = 9; 3207 break; 3208 3209 case Builtin::BI__sync_xor_and_fetch: 3210 case Builtin::BI__sync_xor_and_fetch_1: 3211 case Builtin::BI__sync_xor_and_fetch_2: 3212 case Builtin::BI__sync_xor_and_fetch_4: 3213 case Builtin::BI__sync_xor_and_fetch_8: 3214 case Builtin::BI__sync_xor_and_fetch_16: 3215 BuiltinIndex = 10; 3216 break; 3217 3218 case Builtin::BI__sync_nand_and_fetch: 3219 case Builtin::BI__sync_nand_and_fetch_1: 3220 case Builtin::BI__sync_nand_and_fetch_2: 3221 case Builtin::BI__sync_nand_and_fetch_4: 3222 case Builtin::BI__sync_nand_and_fetch_8: 3223 case Builtin::BI__sync_nand_and_fetch_16: 3224 BuiltinIndex = 11; 3225 WarnAboutSemanticsChange = true; 3226 break; 3227 3228 case Builtin::BI__sync_val_compare_and_swap: 3229 case Builtin::BI__sync_val_compare_and_swap_1: 3230 case Builtin::BI__sync_val_compare_and_swap_2: 3231 case Builtin::BI__sync_val_compare_and_swap_4: 3232 case Builtin::BI__sync_val_compare_and_swap_8: 3233 case Builtin::BI__sync_val_compare_and_swap_16: 3234 BuiltinIndex = 12; 3235 NumFixed = 2; 3236 break; 3237 3238 case Builtin::BI__sync_bool_compare_and_swap: 3239 case Builtin::BI__sync_bool_compare_and_swap_1: 3240 case Builtin::BI__sync_bool_compare_and_swap_2: 3241 case Builtin::BI__sync_bool_compare_and_swap_4: 3242 case Builtin::BI__sync_bool_compare_and_swap_8: 3243 case Builtin::BI__sync_bool_compare_and_swap_16: 3244 BuiltinIndex = 13; 3245 NumFixed = 2; 3246 ResultType = Context.BoolTy; 3247 break; 3248 3249 case Builtin::BI__sync_lock_test_and_set: 3250 case Builtin::BI__sync_lock_test_and_set_1: 3251 case Builtin::BI__sync_lock_test_and_set_2: 3252 case Builtin::BI__sync_lock_test_and_set_4: 3253 case Builtin::BI__sync_lock_test_and_set_8: 3254 case Builtin::BI__sync_lock_test_and_set_16: 3255 BuiltinIndex = 14; 3256 break; 3257 3258 case Builtin::BI__sync_lock_release: 3259 case Builtin::BI__sync_lock_release_1: 3260 case Builtin::BI__sync_lock_release_2: 3261 case Builtin::BI__sync_lock_release_4: 3262 case Builtin::BI__sync_lock_release_8: 3263 case Builtin::BI__sync_lock_release_16: 3264 BuiltinIndex = 15; 3265 NumFixed = 0; 3266 ResultType = Context.VoidTy; 3267 break; 3268 3269 case Builtin::BI__sync_swap: 3270 case Builtin::BI__sync_swap_1: 3271 case Builtin::BI__sync_swap_2: 3272 case Builtin::BI__sync_swap_4: 3273 case Builtin::BI__sync_swap_8: 3274 case Builtin::BI__sync_swap_16: 3275 BuiltinIndex = 16; 3276 break; 3277 } 3278 3279 // Now that we know how many fixed arguments we expect, first check that we 3280 // have at least that many. 3281 if (TheCall->getNumArgs() < 1+NumFixed) { 3282 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3283 << 0 << 1+NumFixed << TheCall->getNumArgs() 3284 << TheCall->getCallee()->getSourceRange(); 3285 return ExprError(); 3286 } 3287 3288 if (WarnAboutSemanticsChange) { 3289 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 3290 << TheCall->getCallee()->getSourceRange(); 3291 } 3292 3293 // Get the decl for the concrete builtin from this, we can tell what the 3294 // concrete integer type we should convert to is. 3295 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 3296 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 3297 FunctionDecl *NewBuiltinDecl; 3298 if (NewBuiltinID == BuiltinID) 3299 NewBuiltinDecl = FDecl; 3300 else { 3301 // Perform builtin lookup to avoid redeclaring it. 3302 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3303 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3304 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3305 assert(Res.getFoundDecl()); 3306 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3307 if (!NewBuiltinDecl) 3308 return ExprError(); 3309 } 3310 3311 // The first argument --- the pointer --- has a fixed type; we 3312 // deduce the types of the rest of the arguments accordingly. Walk 3313 // the remaining arguments, converting them to the deduced value type. 3314 for (unsigned i = 0; i != NumFixed; ++i) { 3315 ExprResult Arg = TheCall->getArg(i+1); 3316 3317 // GCC does an implicit conversion to the pointer or integer ValType. This 3318 // can fail in some cases (1i -> int**), check for this error case now. 3319 // Initialize the argument. 3320 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3321 ValType, /*consume*/ false); 3322 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3323 if (Arg.isInvalid()) 3324 return ExprError(); 3325 3326 // Okay, we have something that *can* be converted to the right type. Check 3327 // to see if there is a potentially weird extension going on here. This can 3328 // happen when you do an atomic operation on something like an char* and 3329 // pass in 42. The 42 gets converted to char. This is even more strange 3330 // for things like 45.123 -> char, etc. 3331 // FIXME: Do this check. 3332 TheCall->setArg(i+1, Arg.get()); 3333 } 3334 3335 ASTContext& Context = this->getASTContext(); 3336 3337 // Create a new DeclRefExpr to refer to the new decl. 3338 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3339 Context, 3340 DRE->getQualifierLoc(), 3341 SourceLocation(), 3342 NewBuiltinDecl, 3343 /*enclosing*/ false, 3344 DRE->getLocation(), 3345 Context.BuiltinFnTy, 3346 DRE->getValueKind()); 3347 3348 // Set the callee in the CallExpr. 3349 // FIXME: This loses syntactic information. 3350 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3351 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3352 CK_BuiltinFnToFnPtr); 3353 TheCall->setCallee(PromotedCall.get()); 3354 3355 // Change the result type of the call to match the original value type. This 3356 // is arbitrary, but the codegen for these builtins ins design to handle it 3357 // gracefully. 3358 TheCall->setType(ResultType); 3359 3360 return TheCallResult; 3361 } 3362 3363 /// SemaBuiltinNontemporalOverloaded - We have a call to 3364 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 3365 /// overloaded function based on the pointer type of its last argument. 3366 /// 3367 /// This function goes through and does final semantic checking for these 3368 /// builtins. 3369 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 3370 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3371 DeclRefExpr *DRE = 3372 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3373 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3374 unsigned BuiltinID = FDecl->getBuiltinID(); 3375 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 3376 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 3377 "Unexpected nontemporal load/store builtin!"); 3378 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 3379 unsigned numArgs = isStore ? 2 : 1; 3380 3381 // Ensure that we have the proper number of arguments. 3382 if (checkArgCount(*this, TheCall, numArgs)) 3383 return ExprError(); 3384 3385 // Inspect the last argument of the nontemporal builtin. This should always 3386 // be a pointer type, from which we imply the type of the memory access. 3387 // Because it is a pointer type, we don't have to worry about any implicit 3388 // casts here. 3389 Expr *PointerArg = TheCall->getArg(numArgs - 1); 3390 ExprResult PointerArgResult = 3391 DefaultFunctionArrayLvalueConversion(PointerArg); 3392 3393 if (PointerArgResult.isInvalid()) 3394 return ExprError(); 3395 PointerArg = PointerArgResult.get(); 3396 TheCall->setArg(numArgs - 1, PointerArg); 3397 3398 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3399 if (!pointerType) { 3400 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 3401 << PointerArg->getType() << PointerArg->getSourceRange(); 3402 return ExprError(); 3403 } 3404 3405 QualType ValType = pointerType->getPointeeType(); 3406 3407 // Strip any qualifiers off ValType. 3408 ValType = ValType.getUnqualifiedType(); 3409 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3410 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 3411 !ValType->isVectorType()) { 3412 Diag(DRE->getLocStart(), 3413 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 3414 << PointerArg->getType() << PointerArg->getSourceRange(); 3415 return ExprError(); 3416 } 3417 3418 if (!isStore) { 3419 TheCall->setType(ValType); 3420 return TheCallResult; 3421 } 3422 3423 ExprResult ValArg = TheCall->getArg(0); 3424 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3425 Context, ValType, /*consume*/ false); 3426 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3427 if (ValArg.isInvalid()) 3428 return ExprError(); 3429 3430 TheCall->setArg(0, ValArg.get()); 3431 TheCall->setType(Context.VoidTy); 3432 return TheCallResult; 3433 } 3434 3435 /// CheckObjCString - Checks that the argument to the builtin 3436 /// CFString constructor is correct 3437 /// Note: It might also make sense to do the UTF-16 conversion here (would 3438 /// simplify the backend). 3439 bool Sema::CheckObjCString(Expr *Arg) { 3440 Arg = Arg->IgnoreParenCasts(); 3441 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 3442 3443 if (!Literal || !Literal->isAscii()) { 3444 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 3445 << Arg->getSourceRange(); 3446 return true; 3447 } 3448 3449 if (Literal->containsNonAsciiOrNull()) { 3450 StringRef String = Literal->getString(); 3451 unsigned NumBytes = String.size(); 3452 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 3453 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 3454 llvm::UTF16 *ToPtr = &ToBuf[0]; 3455 3456 llvm::ConversionResult Result = 3457 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 3458 ToPtr + NumBytes, llvm::strictConversion); 3459 // Check for conversion failure. 3460 if (Result != llvm::conversionOK) 3461 Diag(Arg->getLocStart(), 3462 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 3463 } 3464 return false; 3465 } 3466 3467 /// CheckObjCString - Checks that the format string argument to the os_log() 3468 /// and os_trace() functions is correct, and converts it to const char *. 3469 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 3470 Arg = Arg->IgnoreParenCasts(); 3471 auto *Literal = dyn_cast<StringLiteral>(Arg); 3472 if (!Literal) { 3473 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 3474 Literal = ObjcLiteral->getString(); 3475 } 3476 } 3477 3478 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 3479 return ExprError( 3480 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 3481 << Arg->getSourceRange()); 3482 } 3483 3484 ExprResult Result(Literal); 3485 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 3486 InitializedEntity Entity = 3487 InitializedEntity::InitializeParameter(Context, ResultTy, false); 3488 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 3489 return Result; 3490 } 3491 3492 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 3493 /// for validity. Emit an error and return true on failure; return false 3494 /// on success. 3495 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) { 3496 Expr *Fn = TheCall->getCallee(); 3497 if (TheCall->getNumArgs() > 2) { 3498 Diag(TheCall->getArg(2)->getLocStart(), 3499 diag::err_typecheck_call_too_many_args) 3500 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3501 << Fn->getSourceRange() 3502 << SourceRange(TheCall->getArg(2)->getLocStart(), 3503 (*(TheCall->arg_end()-1))->getLocEnd()); 3504 return true; 3505 } 3506 3507 if (TheCall->getNumArgs() < 2) { 3508 return Diag(TheCall->getLocEnd(), 3509 diag::err_typecheck_call_too_few_args_at_least) 3510 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 3511 } 3512 3513 // Type-check the first argument normally. 3514 if (checkBuiltinArgument(*this, TheCall, 0)) 3515 return true; 3516 3517 // Determine whether the current function is variadic or not. 3518 BlockScopeInfo *CurBlock = getCurBlock(); 3519 bool isVariadic; 3520 if (CurBlock) 3521 isVariadic = CurBlock->TheDecl->isVariadic(); 3522 else if (FunctionDecl *FD = getCurFunctionDecl()) 3523 isVariadic = FD->isVariadic(); 3524 else 3525 isVariadic = getCurMethodDecl()->isVariadic(); 3526 3527 if (!isVariadic) { 3528 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 3529 return true; 3530 } 3531 3532 // Verify that the second argument to the builtin is the last argument of the 3533 // current function or method. 3534 bool SecondArgIsLastNamedArgument = false; 3535 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 3536 3537 // These are valid if SecondArgIsLastNamedArgument is false after the next 3538 // block. 3539 QualType Type; 3540 SourceLocation ParamLoc; 3541 bool IsCRegister = false; 3542 3543 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 3544 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 3545 // FIXME: This isn't correct for methods (results in bogus warning). 3546 // Get the last formal in the current function. 3547 const ParmVarDecl *LastArg; 3548 if (CurBlock) 3549 LastArg = CurBlock->TheDecl->parameters().back(); 3550 else if (FunctionDecl *FD = getCurFunctionDecl()) 3551 LastArg = FD->parameters().back(); 3552 else 3553 LastArg = getCurMethodDecl()->parameters().back(); 3554 SecondArgIsLastNamedArgument = PV == LastArg; 3555 3556 Type = PV->getType(); 3557 ParamLoc = PV->getLocation(); 3558 IsCRegister = 3559 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 3560 } 3561 } 3562 3563 if (!SecondArgIsLastNamedArgument) 3564 Diag(TheCall->getArg(1)->getLocStart(), 3565 diag::warn_second_arg_of_va_start_not_last_named_param); 3566 else if (IsCRegister || Type->isReferenceType() || 3567 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 3568 // Promotable integers are UB, but enumerations need a bit of 3569 // extra checking to see what their promotable type actually is. 3570 if (!Type->isPromotableIntegerType()) 3571 return false; 3572 if (!Type->isEnumeralType()) 3573 return true; 3574 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 3575 return !(ED && 3576 Context.typesAreCompatible(ED->getPromotionType(), Type)); 3577 }()) { 3578 unsigned Reason = 0; 3579 if (Type->isReferenceType()) Reason = 1; 3580 else if (IsCRegister) Reason = 2; 3581 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 3582 Diag(ParamLoc, diag::note_parameter_type) << Type; 3583 } 3584 3585 TheCall->setType(Context.VoidTy); 3586 return false; 3587 } 3588 3589 /// Check the arguments to '__builtin_va_start' for validity, and that 3590 /// it was called from a function of the native ABI. 3591 /// Emit an error and return true on failure; return false on success. 3592 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 3593 // On x86-64 Unix, don't allow this in Win64 ABI functions. 3594 // On x64 Windows, don't allow this in System V ABI functions. 3595 // (Yes, that means there's no corresponding way to support variadic 3596 // System V ABI functions on Windows.) 3597 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) { 3598 unsigned OS = Context.getTargetInfo().getTriple().getOS(); 3599 clang::CallingConv CC = CC_C; 3600 if (const FunctionDecl *FD = getCurFunctionDecl()) 3601 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3602 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) || 3603 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64)) 3604 return Diag(TheCall->getCallee()->getLocStart(), 3605 diag::err_va_start_used_in_wrong_abi_function) 3606 << (OS != llvm::Triple::Win32); 3607 } 3608 return SemaBuiltinVAStartImpl(TheCall); 3609 } 3610 3611 /// Check the arguments to '__builtin_ms_va_start' for validity, and that 3612 /// it was called from a Win64 ABI function. 3613 /// Emit an error and return true on failure; return false on success. 3614 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) { 3615 // This only makes sense for x86-64. 3616 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3617 Expr *Callee = TheCall->getCallee(); 3618 if (TT.getArch() != llvm::Triple::x86_64) 3619 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt); 3620 // Don't allow this in System V ABI functions. 3621 clang::CallingConv CC = CC_C; 3622 if (const FunctionDecl *FD = getCurFunctionDecl()) 3623 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3624 if (CC == CC_X86_64SysV || 3625 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64)) 3626 return Diag(Callee->getLocStart(), 3627 diag::err_ms_va_start_used_in_sysv_function); 3628 return SemaBuiltinVAStartImpl(TheCall); 3629 } 3630 3631 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) { 3632 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 3633 // const char *named_addr); 3634 3635 Expr *Func = Call->getCallee(); 3636 3637 if (Call->getNumArgs() < 3) 3638 return Diag(Call->getLocEnd(), 3639 diag::err_typecheck_call_too_few_args_at_least) 3640 << 0 /*function call*/ << 3 << Call->getNumArgs(); 3641 3642 // Determine whether the current function is variadic or not. 3643 bool IsVariadic; 3644 if (BlockScopeInfo *CurBlock = getCurBlock()) 3645 IsVariadic = CurBlock->TheDecl->isVariadic(); 3646 else if (FunctionDecl *FD = getCurFunctionDecl()) 3647 IsVariadic = FD->isVariadic(); 3648 else if (ObjCMethodDecl *MD = getCurMethodDecl()) 3649 IsVariadic = MD->isVariadic(); 3650 else 3651 llvm_unreachable("unexpected statement type"); 3652 3653 if (!IsVariadic) { 3654 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 3655 return true; 3656 } 3657 3658 // Type-check the first argument normally. 3659 if (checkBuiltinArgument(*this, Call, 0)) 3660 return true; 3661 3662 const struct { 3663 unsigned ArgNo; 3664 QualType Type; 3665 } ArgumentTypes[] = { 3666 { 1, Context.getPointerType(Context.CharTy.withConst()) }, 3667 { 2, Context.getSizeType() }, 3668 }; 3669 3670 for (const auto &AT : ArgumentTypes) { 3671 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens(); 3672 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType()) 3673 continue; 3674 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible) 3675 << Arg->getType() << AT.Type << 1 /* different class */ 3676 << 0 /* qualifier difference */ << 3 /* parameter mismatch */ 3677 << AT.ArgNo + 1 << Arg->getType() << AT.Type; 3678 } 3679 3680 return false; 3681 } 3682 3683 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 3684 /// friends. This is declared to take (...), so we have to check everything. 3685 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 3686 if (TheCall->getNumArgs() < 2) 3687 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3688 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 3689 if (TheCall->getNumArgs() > 2) 3690 return Diag(TheCall->getArg(2)->getLocStart(), 3691 diag::err_typecheck_call_too_many_args) 3692 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3693 << SourceRange(TheCall->getArg(2)->getLocStart(), 3694 (*(TheCall->arg_end()-1))->getLocEnd()); 3695 3696 ExprResult OrigArg0 = TheCall->getArg(0); 3697 ExprResult OrigArg1 = TheCall->getArg(1); 3698 3699 // Do standard promotions between the two arguments, returning their common 3700 // type. 3701 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 3702 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 3703 return true; 3704 3705 // Make sure any conversions are pushed back into the call; this is 3706 // type safe since unordered compare builtins are declared as "_Bool 3707 // foo(...)". 3708 TheCall->setArg(0, OrigArg0.get()); 3709 TheCall->setArg(1, OrigArg1.get()); 3710 3711 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 3712 return false; 3713 3714 // If the common type isn't a real floating type, then the arguments were 3715 // invalid for this operation. 3716 if (Res.isNull() || !Res->isRealFloatingType()) 3717 return Diag(OrigArg0.get()->getLocStart(), 3718 diag::err_typecheck_call_invalid_ordered_compare) 3719 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 3720 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 3721 3722 return false; 3723 } 3724 3725 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 3726 /// __builtin_isnan and friends. This is declared to take (...), so we have 3727 /// to check everything. We expect the last argument to be a floating point 3728 /// value. 3729 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 3730 if (TheCall->getNumArgs() < NumArgs) 3731 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3732 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 3733 if (TheCall->getNumArgs() > NumArgs) 3734 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 3735 diag::err_typecheck_call_too_many_args) 3736 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 3737 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 3738 (*(TheCall->arg_end()-1))->getLocEnd()); 3739 3740 Expr *OrigArg = TheCall->getArg(NumArgs-1); 3741 3742 if (OrigArg->isTypeDependent()) 3743 return false; 3744 3745 // This operation requires a non-_Complex floating-point number. 3746 if (!OrigArg->getType()->isRealFloatingType()) 3747 return Diag(OrigArg->getLocStart(), 3748 diag::err_typecheck_call_invalid_unary_fp) 3749 << OrigArg->getType() << OrigArg->getSourceRange(); 3750 3751 // If this is an implicit conversion from float -> float or double, remove it. 3752 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 3753 // Only remove standard FloatCasts, leaving other casts inplace 3754 if (Cast->getCastKind() == CK_FloatingCast) { 3755 Expr *CastArg = Cast->getSubExpr(); 3756 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 3757 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 3758 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) && 3759 "promotion from float to either float or double is the only expected cast here"); 3760 Cast->setSubExpr(nullptr); 3761 TheCall->setArg(NumArgs-1, CastArg); 3762 } 3763 } 3764 } 3765 3766 return false; 3767 } 3768 3769 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 3770 // This is declared to take (...), so we have to check everything. 3771 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 3772 if (TheCall->getNumArgs() < 2) 3773 return ExprError(Diag(TheCall->getLocEnd(), 3774 diag::err_typecheck_call_too_few_args_at_least) 3775 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3776 << TheCall->getSourceRange()); 3777 3778 // Determine which of the following types of shufflevector we're checking: 3779 // 1) unary, vector mask: (lhs, mask) 3780 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 3781 QualType resType = TheCall->getArg(0)->getType(); 3782 unsigned numElements = 0; 3783 3784 if (!TheCall->getArg(0)->isTypeDependent() && 3785 !TheCall->getArg(1)->isTypeDependent()) { 3786 QualType LHSType = TheCall->getArg(0)->getType(); 3787 QualType RHSType = TheCall->getArg(1)->getType(); 3788 3789 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 3790 return ExprError(Diag(TheCall->getLocStart(), 3791 diag::err_shufflevector_non_vector) 3792 << SourceRange(TheCall->getArg(0)->getLocStart(), 3793 TheCall->getArg(1)->getLocEnd())); 3794 3795 numElements = LHSType->getAs<VectorType>()->getNumElements(); 3796 unsigned numResElements = TheCall->getNumArgs() - 2; 3797 3798 // Check to see if we have a call with 2 vector arguments, the unary shuffle 3799 // with mask. If so, verify that RHS is an integer vector type with the 3800 // same number of elts as lhs. 3801 if (TheCall->getNumArgs() == 2) { 3802 if (!RHSType->hasIntegerRepresentation() || 3803 RHSType->getAs<VectorType>()->getNumElements() != numElements) 3804 return ExprError(Diag(TheCall->getLocStart(), 3805 diag::err_shufflevector_incompatible_vector) 3806 << SourceRange(TheCall->getArg(1)->getLocStart(), 3807 TheCall->getArg(1)->getLocEnd())); 3808 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 3809 return ExprError(Diag(TheCall->getLocStart(), 3810 diag::err_shufflevector_incompatible_vector) 3811 << SourceRange(TheCall->getArg(0)->getLocStart(), 3812 TheCall->getArg(1)->getLocEnd())); 3813 } else if (numElements != numResElements) { 3814 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 3815 resType = Context.getVectorType(eltType, numResElements, 3816 VectorType::GenericVector); 3817 } 3818 } 3819 3820 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 3821 if (TheCall->getArg(i)->isTypeDependent() || 3822 TheCall->getArg(i)->isValueDependent()) 3823 continue; 3824 3825 llvm::APSInt Result(32); 3826 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 3827 return ExprError(Diag(TheCall->getLocStart(), 3828 diag::err_shufflevector_nonconstant_argument) 3829 << TheCall->getArg(i)->getSourceRange()); 3830 3831 // Allow -1 which will be translated to undef in the IR. 3832 if (Result.isSigned() && Result.isAllOnesValue()) 3833 continue; 3834 3835 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 3836 return ExprError(Diag(TheCall->getLocStart(), 3837 diag::err_shufflevector_argument_too_large) 3838 << TheCall->getArg(i)->getSourceRange()); 3839 } 3840 3841 SmallVector<Expr*, 32> exprs; 3842 3843 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 3844 exprs.push_back(TheCall->getArg(i)); 3845 TheCall->setArg(i, nullptr); 3846 } 3847 3848 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 3849 TheCall->getCallee()->getLocStart(), 3850 TheCall->getRParenLoc()); 3851 } 3852 3853 /// SemaConvertVectorExpr - Handle __builtin_convertvector 3854 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 3855 SourceLocation BuiltinLoc, 3856 SourceLocation RParenLoc) { 3857 ExprValueKind VK = VK_RValue; 3858 ExprObjectKind OK = OK_Ordinary; 3859 QualType DstTy = TInfo->getType(); 3860 QualType SrcTy = E->getType(); 3861 3862 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 3863 return ExprError(Diag(BuiltinLoc, 3864 diag::err_convertvector_non_vector) 3865 << E->getSourceRange()); 3866 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 3867 return ExprError(Diag(BuiltinLoc, 3868 diag::err_convertvector_non_vector_type)); 3869 3870 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 3871 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 3872 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 3873 if (SrcElts != DstElts) 3874 return ExprError(Diag(BuiltinLoc, 3875 diag::err_convertvector_incompatible_vector) 3876 << E->getSourceRange()); 3877 } 3878 3879 return new (Context) 3880 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 3881 } 3882 3883 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 3884 // This is declared to take (const void*, ...) and can take two 3885 // optional constant int args. 3886 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 3887 unsigned NumArgs = TheCall->getNumArgs(); 3888 3889 if (NumArgs > 3) 3890 return Diag(TheCall->getLocEnd(), 3891 diag::err_typecheck_call_too_many_args_at_most) 3892 << 0 /*function call*/ << 3 << NumArgs 3893 << TheCall->getSourceRange(); 3894 3895 // Argument 0 is checked for us and the remaining arguments must be 3896 // constant integers. 3897 for (unsigned i = 1; i != NumArgs; ++i) 3898 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 3899 return true; 3900 3901 return false; 3902 } 3903 3904 /// SemaBuiltinAssume - Handle __assume (MS Extension). 3905 // __assume does not evaluate its arguments, and should warn if its argument 3906 // has side effects. 3907 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 3908 Expr *Arg = TheCall->getArg(0); 3909 if (Arg->isInstantiationDependent()) return false; 3910 3911 if (Arg->HasSideEffects(Context)) 3912 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 3913 << Arg->getSourceRange() 3914 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 3915 3916 return false; 3917 } 3918 3919 /// Handle __builtin_alloca_with_align. This is declared 3920 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 3921 /// than 8. 3922 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 3923 // The alignment must be a constant integer. 3924 Expr *Arg = TheCall->getArg(1); 3925 3926 // We can't check the value of a dependent argument. 3927 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 3928 if (const auto *UE = 3929 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 3930 if (UE->getKind() == UETT_AlignOf) 3931 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 3932 << Arg->getSourceRange(); 3933 3934 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 3935 3936 if (!Result.isPowerOf2()) 3937 return Diag(TheCall->getLocStart(), 3938 diag::err_alignment_not_power_of_two) 3939 << Arg->getSourceRange(); 3940 3941 if (Result < Context.getCharWidth()) 3942 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 3943 << (unsigned)Context.getCharWidth() 3944 << Arg->getSourceRange(); 3945 3946 if (Result > INT32_MAX) 3947 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 3948 << INT32_MAX 3949 << Arg->getSourceRange(); 3950 } 3951 3952 return false; 3953 } 3954 3955 /// Handle __builtin_assume_aligned. This is declared 3956 /// as (const void*, size_t, ...) and can take one optional constant int arg. 3957 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 3958 unsigned NumArgs = TheCall->getNumArgs(); 3959 3960 if (NumArgs > 3) 3961 return Diag(TheCall->getLocEnd(), 3962 diag::err_typecheck_call_too_many_args_at_most) 3963 << 0 /*function call*/ << 3 << NumArgs 3964 << TheCall->getSourceRange(); 3965 3966 // The alignment must be a constant integer. 3967 Expr *Arg = TheCall->getArg(1); 3968 3969 // We can't check the value of a dependent argument. 3970 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 3971 llvm::APSInt Result; 3972 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 3973 return true; 3974 3975 if (!Result.isPowerOf2()) 3976 return Diag(TheCall->getLocStart(), 3977 diag::err_alignment_not_power_of_two) 3978 << Arg->getSourceRange(); 3979 } 3980 3981 if (NumArgs > 2) { 3982 ExprResult Arg(TheCall->getArg(2)); 3983 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3984 Context.getSizeType(), false); 3985 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3986 if (Arg.isInvalid()) return true; 3987 TheCall->setArg(2, Arg.get()); 3988 } 3989 3990 return false; 3991 } 3992 3993 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 3994 unsigned BuiltinID = 3995 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 3996 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 3997 3998 unsigned NumArgs = TheCall->getNumArgs(); 3999 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 4000 if (NumArgs < NumRequiredArgs) { 4001 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4002 << 0 /* function call */ << NumRequiredArgs << NumArgs 4003 << TheCall->getSourceRange(); 4004 } 4005 if (NumArgs >= NumRequiredArgs + 0x100) { 4006 return Diag(TheCall->getLocEnd(), 4007 diag::err_typecheck_call_too_many_args_at_most) 4008 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 4009 << TheCall->getSourceRange(); 4010 } 4011 unsigned i = 0; 4012 4013 // For formatting call, check buffer arg. 4014 if (!IsSizeCall) { 4015 ExprResult Arg(TheCall->getArg(i)); 4016 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4017 Context, Context.VoidPtrTy, false); 4018 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4019 if (Arg.isInvalid()) 4020 return true; 4021 TheCall->setArg(i, Arg.get()); 4022 i++; 4023 } 4024 4025 // Check string literal arg. 4026 unsigned FormatIdx = i; 4027 { 4028 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4029 if (Arg.isInvalid()) 4030 return true; 4031 TheCall->setArg(i, Arg.get()); 4032 i++; 4033 } 4034 4035 // Make sure variadic args are scalar. 4036 unsigned FirstDataArg = i; 4037 while (i < NumArgs) { 4038 ExprResult Arg = DefaultVariadicArgumentPromotion( 4039 TheCall->getArg(i), VariadicFunction, nullptr); 4040 if (Arg.isInvalid()) 4041 return true; 4042 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4043 if (ArgSize.getQuantity() >= 0x100) { 4044 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4045 << i << (int)ArgSize.getQuantity() << 0xff 4046 << TheCall->getSourceRange(); 4047 } 4048 TheCall->setArg(i, Arg.get()); 4049 i++; 4050 } 4051 4052 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4053 // call to avoid duplicate diagnostics. 4054 if (!IsSizeCall) { 4055 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4056 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4057 bool Success = CheckFormatArguments( 4058 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4059 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4060 CheckedVarArgs); 4061 if (!Success) 4062 return true; 4063 } 4064 4065 if (IsSizeCall) { 4066 TheCall->setType(Context.getSizeType()); 4067 } else { 4068 TheCall->setType(Context.VoidPtrTy); 4069 } 4070 return false; 4071 } 4072 4073 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4074 /// TheCall is a constant expression. 4075 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4076 llvm::APSInt &Result) { 4077 Expr *Arg = TheCall->getArg(ArgNum); 4078 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4079 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4080 4081 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4082 4083 if (!Arg->isIntegerConstantExpr(Result, Context)) 4084 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 4085 << FDecl->getDeclName() << Arg->getSourceRange(); 4086 4087 return false; 4088 } 4089 4090 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 4091 /// TheCall is a constant expression in the range [Low, High]. 4092 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 4093 int Low, int High) { 4094 llvm::APSInt Result; 4095 4096 // We can't check the value of a dependent argument. 4097 Expr *Arg = TheCall->getArg(ArgNum); 4098 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4099 return false; 4100 4101 // Check constant-ness first. 4102 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4103 return true; 4104 4105 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 4106 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 4107 << Low << High << Arg->getSourceRange(); 4108 4109 return false; 4110 } 4111 4112 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 4113 /// TheCall is a constant expression is a multiple of Num.. 4114 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 4115 unsigned Num) { 4116 llvm::APSInt Result; 4117 4118 // We can't check the value of a dependent argument. 4119 Expr *Arg = TheCall->getArg(ArgNum); 4120 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4121 return false; 4122 4123 // Check constant-ness first. 4124 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4125 return true; 4126 4127 if (Result.getSExtValue() % Num != 0) 4128 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 4129 << Num << Arg->getSourceRange(); 4130 4131 return false; 4132 } 4133 4134 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 4135 /// TheCall is an ARM/AArch64 special register string literal. 4136 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 4137 int ArgNum, unsigned ExpectedFieldNum, 4138 bool AllowName) { 4139 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 4140 BuiltinID == ARM::BI__builtin_arm_wsr64 || 4141 BuiltinID == ARM::BI__builtin_arm_rsr || 4142 BuiltinID == ARM::BI__builtin_arm_rsrp || 4143 BuiltinID == ARM::BI__builtin_arm_wsr || 4144 BuiltinID == ARM::BI__builtin_arm_wsrp; 4145 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 4146 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 4147 BuiltinID == AArch64::BI__builtin_arm_rsr || 4148 BuiltinID == AArch64::BI__builtin_arm_rsrp || 4149 BuiltinID == AArch64::BI__builtin_arm_wsr || 4150 BuiltinID == AArch64::BI__builtin_arm_wsrp; 4151 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 4152 4153 // We can't check the value of a dependent argument. 4154 Expr *Arg = TheCall->getArg(ArgNum); 4155 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4156 return false; 4157 4158 // Check if the argument is a string literal. 4159 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4160 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 4161 << Arg->getSourceRange(); 4162 4163 // Check the type of special register given. 4164 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4165 SmallVector<StringRef, 6> Fields; 4166 Reg.split(Fields, ":"); 4167 4168 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 4169 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4170 << Arg->getSourceRange(); 4171 4172 // If the string is the name of a register then we cannot check that it is 4173 // valid here but if the string is of one the forms described in ACLE then we 4174 // can check that the supplied fields are integers and within the valid 4175 // ranges. 4176 if (Fields.size() > 1) { 4177 bool FiveFields = Fields.size() == 5; 4178 4179 bool ValidString = true; 4180 if (IsARMBuiltin) { 4181 ValidString &= Fields[0].startswith_lower("cp") || 4182 Fields[0].startswith_lower("p"); 4183 if (ValidString) 4184 Fields[0] = 4185 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 4186 4187 ValidString &= Fields[2].startswith_lower("c"); 4188 if (ValidString) 4189 Fields[2] = Fields[2].drop_front(1); 4190 4191 if (FiveFields) { 4192 ValidString &= Fields[3].startswith_lower("c"); 4193 if (ValidString) 4194 Fields[3] = Fields[3].drop_front(1); 4195 } 4196 } 4197 4198 SmallVector<int, 5> Ranges; 4199 if (FiveFields) 4200 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 4201 else 4202 Ranges.append({15, 7, 15}); 4203 4204 for (unsigned i=0; i<Fields.size(); ++i) { 4205 int IntField; 4206 ValidString &= !Fields[i].getAsInteger(10, IntField); 4207 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 4208 } 4209 4210 if (!ValidString) 4211 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4212 << Arg->getSourceRange(); 4213 4214 } else if (IsAArch64Builtin && Fields.size() == 1) { 4215 // If the register name is one of those that appear in the condition below 4216 // and the special register builtin being used is one of the write builtins, 4217 // then we require that the argument provided for writing to the register 4218 // is an integer constant expression. This is because it will be lowered to 4219 // an MSR (immediate) instruction, so we need to know the immediate at 4220 // compile time. 4221 if (TheCall->getNumArgs() != 2) 4222 return false; 4223 4224 std::string RegLower = Reg.lower(); 4225 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 4226 RegLower != "pan" && RegLower != "uao") 4227 return false; 4228 4229 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4230 } 4231 4232 return false; 4233 } 4234 4235 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 4236 /// This checks that the target supports __builtin_longjmp and 4237 /// that val is a constant 1. 4238 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 4239 if (!Context.getTargetInfo().hasSjLjLowering()) 4240 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 4241 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4242 4243 Expr *Arg = TheCall->getArg(1); 4244 llvm::APSInt Result; 4245 4246 // TODO: This is less than ideal. Overload this to take a value. 4247 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4248 return true; 4249 4250 if (Result != 1) 4251 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 4252 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 4253 4254 return false; 4255 } 4256 4257 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 4258 /// This checks that the target supports __builtin_setjmp. 4259 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 4260 if (!Context.getTargetInfo().hasSjLjLowering()) 4261 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 4262 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4263 return false; 4264 } 4265 4266 namespace { 4267 class UncoveredArgHandler { 4268 enum { Unknown = -1, AllCovered = -2 }; 4269 signed FirstUncoveredArg; 4270 SmallVector<const Expr *, 4> DiagnosticExprs; 4271 4272 public: 4273 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { } 4274 4275 bool hasUncoveredArg() const { 4276 return (FirstUncoveredArg >= 0); 4277 } 4278 4279 unsigned getUncoveredArg() const { 4280 assert(hasUncoveredArg() && "no uncovered argument"); 4281 return FirstUncoveredArg; 4282 } 4283 4284 void setAllCovered() { 4285 // A string has been found with all arguments covered, so clear out 4286 // the diagnostics. 4287 DiagnosticExprs.clear(); 4288 FirstUncoveredArg = AllCovered; 4289 } 4290 4291 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 4292 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 4293 4294 // Don't update if a previous string covers all arguments. 4295 if (FirstUncoveredArg == AllCovered) 4296 return; 4297 4298 // UncoveredArgHandler tracks the highest uncovered argument index 4299 // and with it all the strings that match this index. 4300 if (NewFirstUncoveredArg == FirstUncoveredArg) 4301 DiagnosticExprs.push_back(StrExpr); 4302 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 4303 DiagnosticExprs.clear(); 4304 DiagnosticExprs.push_back(StrExpr); 4305 FirstUncoveredArg = NewFirstUncoveredArg; 4306 } 4307 } 4308 4309 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 4310 }; 4311 4312 enum StringLiteralCheckType { 4313 SLCT_NotALiteral, 4314 SLCT_UncheckedLiteral, 4315 SLCT_CheckedLiteral 4316 }; 4317 } // end anonymous namespace 4318 4319 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 4320 BinaryOperatorKind BinOpKind, 4321 bool AddendIsRight) { 4322 unsigned BitWidth = Offset.getBitWidth(); 4323 unsigned AddendBitWidth = Addend.getBitWidth(); 4324 // There might be negative interim results. 4325 if (Addend.isUnsigned()) { 4326 Addend = Addend.zext(++AddendBitWidth); 4327 Addend.setIsSigned(true); 4328 } 4329 // Adjust the bit width of the APSInts. 4330 if (AddendBitWidth > BitWidth) { 4331 Offset = Offset.sext(AddendBitWidth); 4332 BitWidth = AddendBitWidth; 4333 } else if (BitWidth > AddendBitWidth) { 4334 Addend = Addend.sext(BitWidth); 4335 } 4336 4337 bool Ov = false; 4338 llvm::APSInt ResOffset = Offset; 4339 if (BinOpKind == BO_Add) 4340 ResOffset = Offset.sadd_ov(Addend, Ov); 4341 else { 4342 assert(AddendIsRight && BinOpKind == BO_Sub && 4343 "operator must be add or sub with addend on the right"); 4344 ResOffset = Offset.ssub_ov(Addend, Ov); 4345 } 4346 4347 // We add an offset to a pointer here so we should support an offset as big as 4348 // possible. 4349 if (Ov) { 4350 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big"); 4351 Offset = Offset.sext(2 * BitWidth); 4352 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 4353 return; 4354 } 4355 4356 Offset = ResOffset; 4357 } 4358 4359 namespace { 4360 // This is a wrapper class around StringLiteral to support offsetted string 4361 // literals as format strings. It takes the offset into account when returning 4362 // the string and its length or the source locations to display notes correctly. 4363 class FormatStringLiteral { 4364 const StringLiteral *FExpr; 4365 int64_t Offset; 4366 4367 public: 4368 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 4369 : FExpr(fexpr), Offset(Offset) {} 4370 4371 StringRef getString() const { 4372 return FExpr->getString().drop_front(Offset); 4373 } 4374 4375 unsigned getByteLength() const { 4376 return FExpr->getByteLength() - getCharByteWidth() * Offset; 4377 } 4378 unsigned getLength() const { return FExpr->getLength() - Offset; } 4379 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 4380 4381 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 4382 4383 QualType getType() const { return FExpr->getType(); } 4384 4385 bool isAscii() const { return FExpr->isAscii(); } 4386 bool isWide() const { return FExpr->isWide(); } 4387 bool isUTF8() const { return FExpr->isUTF8(); } 4388 bool isUTF16() const { return FExpr->isUTF16(); } 4389 bool isUTF32() const { return FExpr->isUTF32(); } 4390 bool isPascal() const { return FExpr->isPascal(); } 4391 4392 SourceLocation getLocationOfByte( 4393 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 4394 const TargetInfo &Target, unsigned *StartToken = nullptr, 4395 unsigned *StartTokenByteOffset = nullptr) const { 4396 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 4397 StartToken, StartTokenByteOffset); 4398 } 4399 4400 SourceLocation getLocStart() const LLVM_READONLY { 4401 return FExpr->getLocStart().getLocWithOffset(Offset); 4402 } 4403 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 4404 }; 4405 } // end anonymous namespace 4406 4407 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 4408 const Expr *OrigFormatExpr, 4409 ArrayRef<const Expr *> Args, 4410 bool HasVAListArg, unsigned format_idx, 4411 unsigned firstDataArg, 4412 Sema::FormatStringType Type, 4413 bool inFunctionCall, 4414 Sema::VariadicCallType CallType, 4415 llvm::SmallBitVector &CheckedVarArgs, 4416 UncoveredArgHandler &UncoveredArg); 4417 4418 // Determine if an expression is a string literal or constant string. 4419 // If this function returns false on the arguments to a function expecting a 4420 // format string, we will usually need to emit a warning. 4421 // True string literals are then checked by CheckFormatString. 4422 static StringLiteralCheckType 4423 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 4424 bool HasVAListArg, unsigned format_idx, 4425 unsigned firstDataArg, Sema::FormatStringType Type, 4426 Sema::VariadicCallType CallType, bool InFunctionCall, 4427 llvm::SmallBitVector &CheckedVarArgs, 4428 UncoveredArgHandler &UncoveredArg, 4429 llvm::APSInt Offset) { 4430 tryAgain: 4431 assert(Offset.isSigned() && "invalid offset"); 4432 4433 if (E->isTypeDependent() || E->isValueDependent()) 4434 return SLCT_NotALiteral; 4435 4436 E = E->IgnoreParenCasts(); 4437 4438 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 4439 // Technically -Wformat-nonliteral does not warn about this case. 4440 // The behavior of printf and friends in this case is implementation 4441 // dependent. Ideally if the format string cannot be null then 4442 // it should have a 'nonnull' attribute in the function prototype. 4443 return SLCT_UncheckedLiteral; 4444 4445 switch (E->getStmtClass()) { 4446 case Stmt::BinaryConditionalOperatorClass: 4447 case Stmt::ConditionalOperatorClass: { 4448 // The expression is a literal if both sub-expressions were, and it was 4449 // completely checked only if both sub-expressions were checked. 4450 const AbstractConditionalOperator *C = 4451 cast<AbstractConditionalOperator>(E); 4452 4453 // Determine whether it is necessary to check both sub-expressions, for 4454 // example, because the condition expression is a constant that can be 4455 // evaluated at compile time. 4456 bool CheckLeft = true, CheckRight = true; 4457 4458 bool Cond; 4459 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 4460 if (Cond) 4461 CheckRight = false; 4462 else 4463 CheckLeft = false; 4464 } 4465 4466 // We need to maintain the offsets for the right and the left hand side 4467 // separately to check if every possible indexed expression is a valid 4468 // string literal. They might have different offsets for different string 4469 // literals in the end. 4470 StringLiteralCheckType Left; 4471 if (!CheckLeft) 4472 Left = SLCT_UncheckedLiteral; 4473 else { 4474 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 4475 HasVAListArg, format_idx, firstDataArg, 4476 Type, CallType, InFunctionCall, 4477 CheckedVarArgs, UncoveredArg, Offset); 4478 if (Left == SLCT_NotALiteral || !CheckRight) { 4479 return Left; 4480 } 4481 } 4482 4483 StringLiteralCheckType Right = 4484 checkFormatStringExpr(S, C->getFalseExpr(), Args, 4485 HasVAListArg, format_idx, firstDataArg, 4486 Type, CallType, InFunctionCall, CheckedVarArgs, 4487 UncoveredArg, Offset); 4488 4489 return (CheckLeft && Left < Right) ? Left : Right; 4490 } 4491 4492 case Stmt::ImplicitCastExprClass: { 4493 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4494 goto tryAgain; 4495 } 4496 4497 case Stmt::OpaqueValueExprClass: 4498 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 4499 E = src; 4500 goto tryAgain; 4501 } 4502 return SLCT_NotALiteral; 4503 4504 case Stmt::PredefinedExprClass: 4505 // While __func__, etc., are technically not string literals, they 4506 // cannot contain format specifiers and thus are not a security 4507 // liability. 4508 return SLCT_UncheckedLiteral; 4509 4510 case Stmt::DeclRefExprClass: { 4511 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 4512 4513 // As an exception, do not flag errors for variables binding to 4514 // const string literals. 4515 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 4516 bool isConstant = false; 4517 QualType T = DR->getType(); 4518 4519 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 4520 isConstant = AT->getElementType().isConstant(S.Context); 4521 } else if (const PointerType *PT = T->getAs<PointerType>()) { 4522 isConstant = T.isConstant(S.Context) && 4523 PT->getPointeeType().isConstant(S.Context); 4524 } else if (T->isObjCObjectPointerType()) { 4525 // In ObjC, there is usually no "const ObjectPointer" type, 4526 // so don't check if the pointee type is constant. 4527 isConstant = T.isConstant(S.Context); 4528 } 4529 4530 if (isConstant) { 4531 if (const Expr *Init = VD->getAnyInitializer()) { 4532 // Look through initializers like const char c[] = { "foo" } 4533 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4534 if (InitList->isStringLiteralInit()) 4535 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 4536 } 4537 return checkFormatStringExpr(S, Init, Args, 4538 HasVAListArg, format_idx, 4539 firstDataArg, Type, CallType, 4540 /*InFunctionCall*/ false, CheckedVarArgs, 4541 UncoveredArg, Offset); 4542 } 4543 } 4544 4545 // For vprintf* functions (i.e., HasVAListArg==true), we add a 4546 // special check to see if the format string is a function parameter 4547 // of the function calling the printf function. If the function 4548 // has an attribute indicating it is a printf-like function, then we 4549 // should suppress warnings concerning non-literals being used in a call 4550 // to a vprintf function. For example: 4551 // 4552 // void 4553 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 4554 // va_list ap; 4555 // va_start(ap, fmt); 4556 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 4557 // ... 4558 // } 4559 if (HasVAListArg) { 4560 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 4561 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 4562 int PVIndex = PV->getFunctionScopeIndex() + 1; 4563 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 4564 // adjust for implicit parameter 4565 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4566 if (MD->isInstance()) 4567 ++PVIndex; 4568 // We also check if the formats are compatible. 4569 // We can't pass a 'scanf' string to a 'printf' function. 4570 if (PVIndex == PVFormat->getFormatIdx() && 4571 Type == S.GetFormatStringType(PVFormat)) 4572 return SLCT_UncheckedLiteral; 4573 } 4574 } 4575 } 4576 } 4577 } 4578 4579 return SLCT_NotALiteral; 4580 } 4581 4582 case Stmt::CallExprClass: 4583 case Stmt::CXXMemberCallExprClass: { 4584 const CallExpr *CE = cast<CallExpr>(E); 4585 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 4586 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 4587 unsigned ArgIndex = FA->getFormatIdx(); 4588 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4589 if (MD->isInstance()) 4590 --ArgIndex; 4591 const Expr *Arg = CE->getArg(ArgIndex - 1); 4592 4593 return checkFormatStringExpr(S, Arg, Args, 4594 HasVAListArg, format_idx, firstDataArg, 4595 Type, CallType, InFunctionCall, 4596 CheckedVarArgs, UncoveredArg, Offset); 4597 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 4598 unsigned BuiltinID = FD->getBuiltinID(); 4599 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 4600 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 4601 const Expr *Arg = CE->getArg(0); 4602 return checkFormatStringExpr(S, Arg, Args, 4603 HasVAListArg, format_idx, 4604 firstDataArg, Type, CallType, 4605 InFunctionCall, CheckedVarArgs, 4606 UncoveredArg, Offset); 4607 } 4608 } 4609 } 4610 4611 return SLCT_NotALiteral; 4612 } 4613 case Stmt::ObjCMessageExprClass: { 4614 const auto *ME = cast<ObjCMessageExpr>(E); 4615 if (const auto *ND = ME->getMethodDecl()) { 4616 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 4617 unsigned ArgIndex = FA->getFormatIdx(); 4618 const Expr *Arg = ME->getArg(ArgIndex - 1); 4619 return checkFormatStringExpr( 4620 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 4621 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 4622 } 4623 } 4624 4625 return SLCT_NotALiteral; 4626 } 4627 case Stmt::ObjCStringLiteralClass: 4628 case Stmt::StringLiteralClass: { 4629 const StringLiteral *StrE = nullptr; 4630 4631 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 4632 StrE = ObjCFExpr->getString(); 4633 else 4634 StrE = cast<StringLiteral>(E); 4635 4636 if (StrE) { 4637 if (Offset.isNegative() || Offset > StrE->getLength()) { 4638 // TODO: It would be better to have an explicit warning for out of 4639 // bounds literals. 4640 return SLCT_NotALiteral; 4641 } 4642 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 4643 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 4644 firstDataArg, Type, InFunctionCall, CallType, 4645 CheckedVarArgs, UncoveredArg); 4646 return SLCT_CheckedLiteral; 4647 } 4648 4649 return SLCT_NotALiteral; 4650 } 4651 case Stmt::BinaryOperatorClass: { 4652 llvm::APSInt LResult; 4653 llvm::APSInt RResult; 4654 4655 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 4656 4657 // A string literal + an int offset is still a string literal. 4658 if (BinOp->isAdditiveOp()) { 4659 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 4660 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 4661 4662 if (LIsInt != RIsInt) { 4663 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 4664 4665 if (LIsInt) { 4666 if (BinOpKind == BO_Add) { 4667 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 4668 E = BinOp->getRHS(); 4669 goto tryAgain; 4670 } 4671 } else { 4672 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 4673 E = BinOp->getLHS(); 4674 goto tryAgain; 4675 } 4676 } 4677 } 4678 4679 return SLCT_NotALiteral; 4680 } 4681 case Stmt::UnaryOperatorClass: { 4682 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 4683 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 4684 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) { 4685 llvm::APSInt IndexResult; 4686 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 4687 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 4688 E = ASE->getBase(); 4689 goto tryAgain; 4690 } 4691 } 4692 4693 return SLCT_NotALiteral; 4694 } 4695 4696 default: 4697 return SLCT_NotALiteral; 4698 } 4699 } 4700 4701 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 4702 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 4703 .Case("scanf", FST_Scanf) 4704 .Cases("printf", "printf0", FST_Printf) 4705 .Cases("NSString", "CFString", FST_NSString) 4706 .Case("strftime", FST_Strftime) 4707 .Case("strfmon", FST_Strfmon) 4708 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 4709 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 4710 .Case("os_trace", FST_OSLog) 4711 .Case("os_log", FST_OSLog) 4712 .Default(FST_Unknown); 4713 } 4714 4715 /// CheckFormatArguments - Check calls to printf and scanf (and similar 4716 /// functions) for correct use of format strings. 4717 /// Returns true if a format string has been fully checked. 4718 bool Sema::CheckFormatArguments(const FormatAttr *Format, 4719 ArrayRef<const Expr *> Args, 4720 bool IsCXXMember, 4721 VariadicCallType CallType, 4722 SourceLocation Loc, SourceRange Range, 4723 llvm::SmallBitVector &CheckedVarArgs) { 4724 FormatStringInfo FSI; 4725 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 4726 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 4727 FSI.FirstDataArg, GetFormatStringType(Format), 4728 CallType, Loc, Range, CheckedVarArgs); 4729 return false; 4730 } 4731 4732 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 4733 bool HasVAListArg, unsigned format_idx, 4734 unsigned firstDataArg, FormatStringType Type, 4735 VariadicCallType CallType, 4736 SourceLocation Loc, SourceRange Range, 4737 llvm::SmallBitVector &CheckedVarArgs) { 4738 // CHECK: printf/scanf-like function is called with no format string. 4739 if (format_idx >= Args.size()) { 4740 Diag(Loc, diag::warn_missing_format_string) << Range; 4741 return false; 4742 } 4743 4744 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 4745 4746 // CHECK: format string is not a string literal. 4747 // 4748 // Dynamically generated format strings are difficult to 4749 // automatically vet at compile time. Requiring that format strings 4750 // are string literals: (1) permits the checking of format strings by 4751 // the compiler and thereby (2) can practically remove the source of 4752 // many format string exploits. 4753 4754 // Format string can be either ObjC string (e.g. @"%d") or 4755 // C string (e.g. "%d") 4756 // ObjC string uses the same format specifiers as C string, so we can use 4757 // the same format string checking logic for both ObjC and C strings. 4758 UncoveredArgHandler UncoveredArg; 4759 StringLiteralCheckType CT = 4760 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 4761 format_idx, firstDataArg, Type, CallType, 4762 /*IsFunctionCall*/ true, CheckedVarArgs, 4763 UncoveredArg, 4764 /*no string offset*/ llvm::APSInt(64, false) = 0); 4765 4766 // Generate a diagnostic where an uncovered argument is detected. 4767 if (UncoveredArg.hasUncoveredArg()) { 4768 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 4769 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 4770 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 4771 } 4772 4773 if (CT != SLCT_NotALiteral) 4774 // Literal format string found, check done! 4775 return CT == SLCT_CheckedLiteral; 4776 4777 // Strftime is particular as it always uses a single 'time' argument, 4778 // so it is safe to pass a non-literal string. 4779 if (Type == FST_Strftime) 4780 return false; 4781 4782 // Do not emit diag when the string param is a macro expansion and the 4783 // format is either NSString or CFString. This is a hack to prevent 4784 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 4785 // which are usually used in place of NS and CF string literals. 4786 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 4787 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 4788 return false; 4789 4790 // If there are no arguments specified, warn with -Wformat-security, otherwise 4791 // warn only with -Wformat-nonliteral. 4792 if (Args.size() == firstDataArg) { 4793 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 4794 << OrigFormatExpr->getSourceRange(); 4795 switch (Type) { 4796 default: 4797 break; 4798 case FST_Kprintf: 4799 case FST_FreeBSDKPrintf: 4800 case FST_Printf: 4801 Diag(FormatLoc, diag::note_format_security_fixit) 4802 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 4803 break; 4804 case FST_NSString: 4805 Diag(FormatLoc, diag::note_format_security_fixit) 4806 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 4807 break; 4808 } 4809 } else { 4810 Diag(FormatLoc, diag::warn_format_nonliteral) 4811 << OrigFormatExpr->getSourceRange(); 4812 } 4813 return false; 4814 } 4815 4816 namespace { 4817 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 4818 protected: 4819 Sema &S; 4820 const FormatStringLiteral *FExpr; 4821 const Expr *OrigFormatExpr; 4822 const Sema::FormatStringType FSType; 4823 const unsigned FirstDataArg; 4824 const unsigned NumDataArgs; 4825 const char *Beg; // Start of format string. 4826 const bool HasVAListArg; 4827 ArrayRef<const Expr *> Args; 4828 unsigned FormatIdx; 4829 llvm::SmallBitVector CoveredArgs; 4830 bool usesPositionalArgs; 4831 bool atFirstArg; 4832 bool inFunctionCall; 4833 Sema::VariadicCallType CallType; 4834 llvm::SmallBitVector &CheckedVarArgs; 4835 UncoveredArgHandler &UncoveredArg; 4836 4837 public: 4838 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 4839 const Expr *origFormatExpr, 4840 const Sema::FormatStringType type, unsigned firstDataArg, 4841 unsigned numDataArgs, const char *beg, bool hasVAListArg, 4842 ArrayRef<const Expr *> Args, unsigned formatIdx, 4843 bool inFunctionCall, Sema::VariadicCallType callType, 4844 llvm::SmallBitVector &CheckedVarArgs, 4845 UncoveredArgHandler &UncoveredArg) 4846 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 4847 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 4848 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 4849 usesPositionalArgs(false), atFirstArg(true), 4850 inFunctionCall(inFunctionCall), CallType(callType), 4851 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 4852 CoveredArgs.resize(numDataArgs); 4853 CoveredArgs.reset(); 4854 } 4855 4856 void DoneProcessing(); 4857 4858 void HandleIncompleteSpecifier(const char *startSpecifier, 4859 unsigned specifierLen) override; 4860 4861 void HandleInvalidLengthModifier( 4862 const analyze_format_string::FormatSpecifier &FS, 4863 const analyze_format_string::ConversionSpecifier &CS, 4864 const char *startSpecifier, unsigned specifierLen, 4865 unsigned DiagID); 4866 4867 void HandleNonStandardLengthModifier( 4868 const analyze_format_string::FormatSpecifier &FS, 4869 const char *startSpecifier, unsigned specifierLen); 4870 4871 void HandleNonStandardConversionSpecifier( 4872 const analyze_format_string::ConversionSpecifier &CS, 4873 const char *startSpecifier, unsigned specifierLen); 4874 4875 void HandlePosition(const char *startPos, unsigned posLen) override; 4876 4877 void HandleInvalidPosition(const char *startSpecifier, 4878 unsigned specifierLen, 4879 analyze_format_string::PositionContext p) override; 4880 4881 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 4882 4883 void HandleNullChar(const char *nullCharacter) override; 4884 4885 template <typename Range> 4886 static void 4887 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 4888 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 4889 bool IsStringLocation, Range StringRange, 4890 ArrayRef<FixItHint> Fixit = None); 4891 4892 protected: 4893 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 4894 const char *startSpec, 4895 unsigned specifierLen, 4896 const char *csStart, unsigned csLen); 4897 4898 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 4899 const char *startSpec, 4900 unsigned specifierLen); 4901 4902 SourceRange getFormatStringRange(); 4903 CharSourceRange getSpecifierRange(const char *startSpecifier, 4904 unsigned specifierLen); 4905 SourceLocation getLocationOfByte(const char *x); 4906 4907 const Expr *getDataArg(unsigned i) const; 4908 4909 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 4910 const analyze_format_string::ConversionSpecifier &CS, 4911 const char *startSpecifier, unsigned specifierLen, 4912 unsigned argIndex); 4913 4914 template <typename Range> 4915 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 4916 bool IsStringLocation, Range StringRange, 4917 ArrayRef<FixItHint> Fixit = None); 4918 }; 4919 } // end anonymous namespace 4920 4921 SourceRange CheckFormatHandler::getFormatStringRange() { 4922 return OrigFormatExpr->getSourceRange(); 4923 } 4924 4925 CharSourceRange CheckFormatHandler:: 4926 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 4927 SourceLocation Start = getLocationOfByte(startSpecifier); 4928 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 4929 4930 // Advance the end SourceLocation by one due to half-open ranges. 4931 End = End.getLocWithOffset(1); 4932 4933 return CharSourceRange::getCharRange(Start, End); 4934 } 4935 4936 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 4937 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 4938 S.getLangOpts(), S.Context.getTargetInfo()); 4939 } 4940 4941 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 4942 unsigned specifierLen){ 4943 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 4944 getLocationOfByte(startSpecifier), 4945 /*IsStringLocation*/true, 4946 getSpecifierRange(startSpecifier, specifierLen)); 4947 } 4948 4949 void CheckFormatHandler::HandleInvalidLengthModifier( 4950 const analyze_format_string::FormatSpecifier &FS, 4951 const analyze_format_string::ConversionSpecifier &CS, 4952 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 4953 using namespace analyze_format_string; 4954 4955 const LengthModifier &LM = FS.getLengthModifier(); 4956 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 4957 4958 // See if we know how to fix this length modifier. 4959 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 4960 if (FixedLM) { 4961 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 4962 getLocationOfByte(LM.getStart()), 4963 /*IsStringLocation*/true, 4964 getSpecifierRange(startSpecifier, specifierLen)); 4965 4966 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 4967 << FixedLM->toString() 4968 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 4969 4970 } else { 4971 FixItHint Hint; 4972 if (DiagID == diag::warn_format_nonsensical_length) 4973 Hint = FixItHint::CreateRemoval(LMRange); 4974 4975 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 4976 getLocationOfByte(LM.getStart()), 4977 /*IsStringLocation*/true, 4978 getSpecifierRange(startSpecifier, specifierLen), 4979 Hint); 4980 } 4981 } 4982 4983 void CheckFormatHandler::HandleNonStandardLengthModifier( 4984 const analyze_format_string::FormatSpecifier &FS, 4985 const char *startSpecifier, unsigned specifierLen) { 4986 using namespace analyze_format_string; 4987 4988 const LengthModifier &LM = FS.getLengthModifier(); 4989 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 4990 4991 // See if we know how to fix this length modifier. 4992 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 4993 if (FixedLM) { 4994 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4995 << LM.toString() << 0, 4996 getLocationOfByte(LM.getStart()), 4997 /*IsStringLocation*/true, 4998 getSpecifierRange(startSpecifier, specifierLen)); 4999 5000 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5001 << FixedLM->toString() 5002 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5003 5004 } else { 5005 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5006 << LM.toString() << 0, 5007 getLocationOfByte(LM.getStart()), 5008 /*IsStringLocation*/true, 5009 getSpecifierRange(startSpecifier, specifierLen)); 5010 } 5011 } 5012 5013 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5014 const analyze_format_string::ConversionSpecifier &CS, 5015 const char *startSpecifier, unsigned specifierLen) { 5016 using namespace analyze_format_string; 5017 5018 // See if we know how to fix this conversion specifier. 5019 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5020 if (FixedCS) { 5021 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5022 << CS.toString() << /*conversion specifier*/1, 5023 getLocationOfByte(CS.getStart()), 5024 /*IsStringLocation*/true, 5025 getSpecifierRange(startSpecifier, specifierLen)); 5026 5027 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5028 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5029 << FixedCS->toString() 5030 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5031 } else { 5032 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5033 << CS.toString() << /*conversion specifier*/1, 5034 getLocationOfByte(CS.getStart()), 5035 /*IsStringLocation*/true, 5036 getSpecifierRange(startSpecifier, specifierLen)); 5037 } 5038 } 5039 5040 void CheckFormatHandler::HandlePosition(const char *startPos, 5041 unsigned posLen) { 5042 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5043 getLocationOfByte(startPos), 5044 /*IsStringLocation*/true, 5045 getSpecifierRange(startPos, posLen)); 5046 } 5047 5048 void 5049 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5050 analyze_format_string::PositionContext p) { 5051 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5052 << (unsigned) p, 5053 getLocationOfByte(startPos), /*IsStringLocation*/true, 5054 getSpecifierRange(startPos, posLen)); 5055 } 5056 5057 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5058 unsigned posLen) { 5059 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5060 getLocationOfByte(startPos), 5061 /*IsStringLocation*/true, 5062 getSpecifierRange(startPos, posLen)); 5063 } 5064 5065 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5066 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5067 // The presence of a null character is likely an error. 5068 EmitFormatDiagnostic( 5069 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5070 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5071 getFormatStringRange()); 5072 } 5073 } 5074 5075 // Note that this may return NULL if there was an error parsing or building 5076 // one of the argument expressions. 5077 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5078 return Args[FirstDataArg + i]; 5079 } 5080 5081 void CheckFormatHandler::DoneProcessing() { 5082 // Does the number of data arguments exceed the number of 5083 // format conversions in the format string? 5084 if (!HasVAListArg) { 5085 // Find any arguments that weren't covered. 5086 CoveredArgs.flip(); 5087 signed notCoveredArg = CoveredArgs.find_first(); 5088 if (notCoveredArg >= 0) { 5089 assert((unsigned)notCoveredArg < NumDataArgs); 5090 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 5091 } else { 5092 UncoveredArg.setAllCovered(); 5093 } 5094 } 5095 } 5096 5097 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 5098 const Expr *ArgExpr) { 5099 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 5100 "Invalid state"); 5101 5102 if (!ArgExpr) 5103 return; 5104 5105 SourceLocation Loc = ArgExpr->getLocStart(); 5106 5107 if (S.getSourceManager().isInSystemMacro(Loc)) 5108 return; 5109 5110 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 5111 for (auto E : DiagnosticExprs) 5112 PDiag << E->getSourceRange(); 5113 5114 CheckFormatHandler::EmitFormatDiagnostic( 5115 S, IsFunctionCall, DiagnosticExprs[0], 5116 PDiag, Loc, /*IsStringLocation*/false, 5117 DiagnosticExprs[0]->getSourceRange()); 5118 } 5119 5120 bool 5121 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 5122 SourceLocation Loc, 5123 const char *startSpec, 5124 unsigned specifierLen, 5125 const char *csStart, 5126 unsigned csLen) { 5127 bool keepGoing = true; 5128 if (argIndex < NumDataArgs) { 5129 // Consider the argument coverered, even though the specifier doesn't 5130 // make sense. 5131 CoveredArgs.set(argIndex); 5132 } 5133 else { 5134 // If argIndex exceeds the number of data arguments we 5135 // don't issue a warning because that is just a cascade of warnings (and 5136 // they may have intended '%%' anyway). We don't want to continue processing 5137 // the format string after this point, however, as we will like just get 5138 // gibberish when trying to match arguments. 5139 keepGoing = false; 5140 } 5141 5142 StringRef Specifier(csStart, csLen); 5143 5144 // If the specifier in non-printable, it could be the first byte of a UTF-8 5145 // sequence. In that case, print the UTF-8 code point. If not, print the byte 5146 // hex value. 5147 std::string CodePointStr; 5148 if (!llvm::sys::locale::isPrint(*csStart)) { 5149 llvm::UTF32 CodePoint; 5150 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 5151 const llvm::UTF8 *E = 5152 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 5153 llvm::ConversionResult Result = 5154 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 5155 5156 if (Result != llvm::conversionOK) { 5157 unsigned char FirstChar = *csStart; 5158 CodePoint = (llvm::UTF32)FirstChar; 5159 } 5160 5161 llvm::raw_string_ostream OS(CodePointStr); 5162 if (CodePoint < 256) 5163 OS << "\\x" << llvm::format("%02x", CodePoint); 5164 else if (CodePoint <= 0xFFFF) 5165 OS << "\\u" << llvm::format("%04x", CodePoint); 5166 else 5167 OS << "\\U" << llvm::format("%08x", CodePoint); 5168 OS.flush(); 5169 Specifier = CodePointStr; 5170 } 5171 5172 EmitFormatDiagnostic( 5173 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 5174 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 5175 5176 return keepGoing; 5177 } 5178 5179 void 5180 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 5181 const char *startSpec, 5182 unsigned specifierLen) { 5183 EmitFormatDiagnostic( 5184 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 5185 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 5186 } 5187 5188 bool 5189 CheckFormatHandler::CheckNumArgs( 5190 const analyze_format_string::FormatSpecifier &FS, 5191 const analyze_format_string::ConversionSpecifier &CS, 5192 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 5193 5194 if (argIndex >= NumDataArgs) { 5195 PartialDiagnostic PDiag = FS.usesPositionalArg() 5196 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 5197 << (argIndex+1) << NumDataArgs) 5198 : S.PDiag(diag::warn_printf_insufficient_data_args); 5199 EmitFormatDiagnostic( 5200 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 5201 getSpecifierRange(startSpecifier, specifierLen)); 5202 5203 // Since more arguments than conversion tokens are given, by extension 5204 // all arguments are covered, so mark this as so. 5205 UncoveredArg.setAllCovered(); 5206 return false; 5207 } 5208 return true; 5209 } 5210 5211 template<typename Range> 5212 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 5213 SourceLocation Loc, 5214 bool IsStringLocation, 5215 Range StringRange, 5216 ArrayRef<FixItHint> FixIt) { 5217 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 5218 Loc, IsStringLocation, StringRange, FixIt); 5219 } 5220 5221 /// \brief If the format string is not within the funcion call, emit a note 5222 /// so that the function call and string are in diagnostic messages. 5223 /// 5224 /// \param InFunctionCall if true, the format string is within the function 5225 /// call and only one diagnostic message will be produced. Otherwise, an 5226 /// extra note will be emitted pointing to location of the format string. 5227 /// 5228 /// \param ArgumentExpr the expression that is passed as the format string 5229 /// argument in the function call. Used for getting locations when two 5230 /// diagnostics are emitted. 5231 /// 5232 /// \param PDiag the callee should already have provided any strings for the 5233 /// diagnostic message. This function only adds locations and fixits 5234 /// to diagnostics. 5235 /// 5236 /// \param Loc primary location for diagnostic. If two diagnostics are 5237 /// required, one will be at Loc and a new SourceLocation will be created for 5238 /// the other one. 5239 /// 5240 /// \param IsStringLocation if true, Loc points to the format string should be 5241 /// used for the note. Otherwise, Loc points to the argument list and will 5242 /// be used with PDiag. 5243 /// 5244 /// \param StringRange some or all of the string to highlight. This is 5245 /// templated so it can accept either a CharSourceRange or a SourceRange. 5246 /// 5247 /// \param FixIt optional fix it hint for the format string. 5248 template <typename Range> 5249 void CheckFormatHandler::EmitFormatDiagnostic( 5250 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 5251 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 5252 Range StringRange, ArrayRef<FixItHint> FixIt) { 5253 if (InFunctionCall) { 5254 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 5255 D << StringRange; 5256 D << FixIt; 5257 } else { 5258 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 5259 << ArgumentExpr->getSourceRange(); 5260 5261 const Sema::SemaDiagnosticBuilder &Note = 5262 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 5263 diag::note_format_string_defined); 5264 5265 Note << StringRange; 5266 Note << FixIt; 5267 } 5268 } 5269 5270 //===--- CHECK: Printf format string checking ------------------------------===// 5271 5272 namespace { 5273 class CheckPrintfHandler : public CheckFormatHandler { 5274 public: 5275 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 5276 const Expr *origFormatExpr, 5277 const Sema::FormatStringType type, unsigned firstDataArg, 5278 unsigned numDataArgs, bool isObjC, const char *beg, 5279 bool hasVAListArg, ArrayRef<const Expr *> Args, 5280 unsigned formatIdx, bool inFunctionCall, 5281 Sema::VariadicCallType CallType, 5282 llvm::SmallBitVector &CheckedVarArgs, 5283 UncoveredArgHandler &UncoveredArg) 5284 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 5285 numDataArgs, beg, hasVAListArg, Args, formatIdx, 5286 inFunctionCall, CallType, CheckedVarArgs, 5287 UncoveredArg) {} 5288 5289 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 5290 5291 /// Returns true if '%@' specifiers are allowed in the format string. 5292 bool allowsObjCArg() const { 5293 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 5294 FSType == Sema::FST_OSTrace; 5295 } 5296 5297 bool HandleInvalidPrintfConversionSpecifier( 5298 const analyze_printf::PrintfSpecifier &FS, 5299 const char *startSpecifier, 5300 unsigned specifierLen) override; 5301 5302 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 5303 const char *startSpecifier, 5304 unsigned specifierLen) override; 5305 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5306 const char *StartSpecifier, 5307 unsigned SpecifierLen, 5308 const Expr *E); 5309 5310 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 5311 const char *startSpecifier, unsigned specifierLen); 5312 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 5313 const analyze_printf::OptionalAmount &Amt, 5314 unsigned type, 5315 const char *startSpecifier, unsigned specifierLen); 5316 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5317 const analyze_printf::OptionalFlag &flag, 5318 const char *startSpecifier, unsigned specifierLen); 5319 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 5320 const analyze_printf::OptionalFlag &ignoredFlag, 5321 const analyze_printf::OptionalFlag &flag, 5322 const char *startSpecifier, unsigned specifierLen); 5323 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 5324 const Expr *E); 5325 5326 void HandleEmptyObjCModifierFlag(const char *startFlag, 5327 unsigned flagLen) override; 5328 5329 void HandleInvalidObjCModifierFlag(const char *startFlag, 5330 unsigned flagLen) override; 5331 5332 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 5333 const char *flagsEnd, 5334 const char *conversionPosition) 5335 override; 5336 }; 5337 } // end anonymous namespace 5338 5339 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 5340 const analyze_printf::PrintfSpecifier &FS, 5341 const char *startSpecifier, 5342 unsigned specifierLen) { 5343 const analyze_printf::PrintfConversionSpecifier &CS = 5344 FS.getConversionSpecifier(); 5345 5346 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5347 getLocationOfByte(CS.getStart()), 5348 startSpecifier, specifierLen, 5349 CS.getStart(), CS.getLength()); 5350 } 5351 5352 bool CheckPrintfHandler::HandleAmount( 5353 const analyze_format_string::OptionalAmount &Amt, 5354 unsigned k, const char *startSpecifier, 5355 unsigned specifierLen) { 5356 if (Amt.hasDataArgument()) { 5357 if (!HasVAListArg) { 5358 unsigned argIndex = Amt.getArgIndex(); 5359 if (argIndex >= NumDataArgs) { 5360 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 5361 << k, 5362 getLocationOfByte(Amt.getStart()), 5363 /*IsStringLocation*/true, 5364 getSpecifierRange(startSpecifier, specifierLen)); 5365 // Don't do any more checking. We will just emit 5366 // spurious errors. 5367 return false; 5368 } 5369 5370 // Type check the data argument. It should be an 'int'. 5371 // Although not in conformance with C99, we also allow the argument to be 5372 // an 'unsigned int' as that is a reasonably safe case. GCC also 5373 // doesn't emit a warning for that case. 5374 CoveredArgs.set(argIndex); 5375 const Expr *Arg = getDataArg(argIndex); 5376 if (!Arg) 5377 return false; 5378 5379 QualType T = Arg->getType(); 5380 5381 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 5382 assert(AT.isValid()); 5383 5384 if (!AT.matchesType(S.Context, T)) { 5385 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 5386 << k << AT.getRepresentativeTypeName(S.Context) 5387 << T << Arg->getSourceRange(), 5388 getLocationOfByte(Amt.getStart()), 5389 /*IsStringLocation*/true, 5390 getSpecifierRange(startSpecifier, specifierLen)); 5391 // Don't do any more checking. We will just emit 5392 // spurious errors. 5393 return false; 5394 } 5395 } 5396 } 5397 return true; 5398 } 5399 5400 void CheckPrintfHandler::HandleInvalidAmount( 5401 const analyze_printf::PrintfSpecifier &FS, 5402 const analyze_printf::OptionalAmount &Amt, 5403 unsigned type, 5404 const char *startSpecifier, 5405 unsigned specifierLen) { 5406 const analyze_printf::PrintfConversionSpecifier &CS = 5407 FS.getConversionSpecifier(); 5408 5409 FixItHint fixit = 5410 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 5411 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 5412 Amt.getConstantLength())) 5413 : FixItHint(); 5414 5415 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 5416 << type << CS.toString(), 5417 getLocationOfByte(Amt.getStart()), 5418 /*IsStringLocation*/true, 5419 getSpecifierRange(startSpecifier, specifierLen), 5420 fixit); 5421 } 5422 5423 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5424 const analyze_printf::OptionalFlag &flag, 5425 const char *startSpecifier, 5426 unsigned specifierLen) { 5427 // Warn about pointless flag with a fixit removal. 5428 const analyze_printf::PrintfConversionSpecifier &CS = 5429 FS.getConversionSpecifier(); 5430 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 5431 << flag.toString() << CS.toString(), 5432 getLocationOfByte(flag.getPosition()), 5433 /*IsStringLocation*/true, 5434 getSpecifierRange(startSpecifier, specifierLen), 5435 FixItHint::CreateRemoval( 5436 getSpecifierRange(flag.getPosition(), 1))); 5437 } 5438 5439 void CheckPrintfHandler::HandleIgnoredFlag( 5440 const analyze_printf::PrintfSpecifier &FS, 5441 const analyze_printf::OptionalFlag &ignoredFlag, 5442 const analyze_printf::OptionalFlag &flag, 5443 const char *startSpecifier, 5444 unsigned specifierLen) { 5445 // Warn about ignored flag with a fixit removal. 5446 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 5447 << ignoredFlag.toString() << flag.toString(), 5448 getLocationOfByte(ignoredFlag.getPosition()), 5449 /*IsStringLocation*/true, 5450 getSpecifierRange(startSpecifier, specifierLen), 5451 FixItHint::CreateRemoval( 5452 getSpecifierRange(ignoredFlag.getPosition(), 1))); 5453 } 5454 5455 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5456 // bool IsStringLocation, Range StringRange, 5457 // ArrayRef<FixItHint> Fixit = None); 5458 5459 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 5460 unsigned flagLen) { 5461 // Warn about an empty flag. 5462 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 5463 getLocationOfByte(startFlag), 5464 /*IsStringLocation*/true, 5465 getSpecifierRange(startFlag, flagLen)); 5466 } 5467 5468 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 5469 unsigned flagLen) { 5470 // Warn about an invalid flag. 5471 auto Range = getSpecifierRange(startFlag, flagLen); 5472 StringRef flag(startFlag, flagLen); 5473 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 5474 getLocationOfByte(startFlag), 5475 /*IsStringLocation*/true, 5476 Range, FixItHint::CreateRemoval(Range)); 5477 } 5478 5479 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 5480 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 5481 // Warn about using '[...]' without a '@' conversion. 5482 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 5483 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 5484 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 5485 getLocationOfByte(conversionPosition), 5486 /*IsStringLocation*/true, 5487 Range, FixItHint::CreateRemoval(Range)); 5488 } 5489 5490 // Determines if the specified is a C++ class or struct containing 5491 // a member with the specified name and kind (e.g. a CXXMethodDecl named 5492 // "c_str()"). 5493 template<typename MemberKind> 5494 static llvm::SmallPtrSet<MemberKind*, 1> 5495 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 5496 const RecordType *RT = Ty->getAs<RecordType>(); 5497 llvm::SmallPtrSet<MemberKind*, 1> Results; 5498 5499 if (!RT) 5500 return Results; 5501 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 5502 if (!RD || !RD->getDefinition()) 5503 return Results; 5504 5505 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 5506 Sema::LookupMemberName); 5507 R.suppressDiagnostics(); 5508 5509 // We just need to include all members of the right kind turned up by the 5510 // filter, at this point. 5511 if (S.LookupQualifiedName(R, RT->getDecl())) 5512 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 5513 NamedDecl *decl = (*I)->getUnderlyingDecl(); 5514 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 5515 Results.insert(FK); 5516 } 5517 return Results; 5518 } 5519 5520 /// Check if we could call '.c_str()' on an object. 5521 /// 5522 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 5523 /// allow the call, or if it would be ambiguous). 5524 bool Sema::hasCStrMethod(const Expr *E) { 5525 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5526 MethodSet Results = 5527 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 5528 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5529 MI != ME; ++MI) 5530 if ((*MI)->getMinRequiredArguments() == 0) 5531 return true; 5532 return false; 5533 } 5534 5535 // Check if a (w)string was passed when a (w)char* was needed, and offer a 5536 // better diagnostic if so. AT is assumed to be valid. 5537 // Returns true when a c_str() conversion method is found. 5538 bool CheckPrintfHandler::checkForCStrMembers( 5539 const analyze_printf::ArgType &AT, const Expr *E) { 5540 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5541 5542 MethodSet Results = 5543 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 5544 5545 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5546 MI != ME; ++MI) { 5547 const CXXMethodDecl *Method = *MI; 5548 if (Method->getMinRequiredArguments() == 0 && 5549 AT.matchesType(S.Context, Method->getReturnType())) { 5550 // FIXME: Suggest parens if the expression needs them. 5551 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 5552 S.Diag(E->getLocStart(), diag::note_printf_c_str) 5553 << "c_str()" 5554 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 5555 return true; 5556 } 5557 } 5558 5559 return false; 5560 } 5561 5562 bool 5563 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 5564 &FS, 5565 const char *startSpecifier, 5566 unsigned specifierLen) { 5567 using namespace analyze_format_string; 5568 using namespace analyze_printf; 5569 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 5570 5571 if (FS.consumesDataArgument()) { 5572 if (atFirstArg) { 5573 atFirstArg = false; 5574 usesPositionalArgs = FS.usesPositionalArg(); 5575 } 5576 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5577 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5578 startSpecifier, specifierLen); 5579 return false; 5580 } 5581 } 5582 5583 // First check if the field width, precision, and conversion specifier 5584 // have matching data arguments. 5585 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 5586 startSpecifier, specifierLen)) { 5587 return false; 5588 } 5589 5590 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 5591 startSpecifier, specifierLen)) { 5592 return false; 5593 } 5594 5595 if (!CS.consumesDataArgument()) { 5596 // FIXME: Technically specifying a precision or field width here 5597 // makes no sense. Worth issuing a warning at some point. 5598 return true; 5599 } 5600 5601 // Consume the argument. 5602 unsigned argIndex = FS.getArgIndex(); 5603 if (argIndex < NumDataArgs) { 5604 // The check to see if the argIndex is valid will come later. 5605 // We set the bit here because we may exit early from this 5606 // function if we encounter some other error. 5607 CoveredArgs.set(argIndex); 5608 } 5609 5610 // FreeBSD kernel extensions. 5611 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 5612 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 5613 // We need at least two arguments. 5614 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 5615 return false; 5616 5617 // Claim the second argument. 5618 CoveredArgs.set(argIndex + 1); 5619 5620 // Type check the first argument (int for %b, pointer for %D) 5621 const Expr *Ex = getDataArg(argIndex); 5622 const analyze_printf::ArgType &AT = 5623 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 5624 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 5625 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 5626 EmitFormatDiagnostic( 5627 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5628 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 5629 << false << Ex->getSourceRange(), 5630 Ex->getLocStart(), /*IsStringLocation*/false, 5631 getSpecifierRange(startSpecifier, specifierLen)); 5632 5633 // Type check the second argument (char * for both %b and %D) 5634 Ex = getDataArg(argIndex + 1); 5635 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 5636 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 5637 EmitFormatDiagnostic( 5638 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5639 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 5640 << false << Ex->getSourceRange(), 5641 Ex->getLocStart(), /*IsStringLocation*/false, 5642 getSpecifierRange(startSpecifier, specifierLen)); 5643 5644 return true; 5645 } 5646 5647 // Check for using an Objective-C specific conversion specifier 5648 // in a non-ObjC literal. 5649 if (!allowsObjCArg() && CS.isObjCArg()) { 5650 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5651 specifierLen); 5652 } 5653 5654 // %P can only be used with os_log. 5655 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 5656 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5657 specifierLen); 5658 } 5659 5660 // %n is not allowed with os_log. 5661 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 5662 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 5663 getLocationOfByte(CS.getStart()), 5664 /*IsStringLocation*/ false, 5665 getSpecifierRange(startSpecifier, specifierLen)); 5666 5667 return true; 5668 } 5669 5670 // Only scalars are allowed for os_trace. 5671 if (FSType == Sema::FST_OSTrace && 5672 (CS.getKind() == ConversionSpecifier::PArg || 5673 CS.getKind() == ConversionSpecifier::sArg || 5674 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 5675 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5676 specifierLen); 5677 } 5678 5679 // Check for use of public/private annotation outside of os_log(). 5680 if (FSType != Sema::FST_OSLog) { 5681 if (FS.isPublic().isSet()) { 5682 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 5683 << "public", 5684 getLocationOfByte(FS.isPublic().getPosition()), 5685 /*IsStringLocation*/ false, 5686 getSpecifierRange(startSpecifier, specifierLen)); 5687 } 5688 if (FS.isPrivate().isSet()) { 5689 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 5690 << "private", 5691 getLocationOfByte(FS.isPrivate().getPosition()), 5692 /*IsStringLocation*/ false, 5693 getSpecifierRange(startSpecifier, specifierLen)); 5694 } 5695 } 5696 5697 // Check for invalid use of field width 5698 if (!FS.hasValidFieldWidth()) { 5699 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 5700 startSpecifier, specifierLen); 5701 } 5702 5703 // Check for invalid use of precision 5704 if (!FS.hasValidPrecision()) { 5705 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 5706 startSpecifier, specifierLen); 5707 } 5708 5709 // Precision is mandatory for %P specifier. 5710 if (CS.getKind() == ConversionSpecifier::PArg && 5711 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 5712 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 5713 getLocationOfByte(startSpecifier), 5714 /*IsStringLocation*/ false, 5715 getSpecifierRange(startSpecifier, specifierLen)); 5716 } 5717 5718 // Check each flag does not conflict with any other component. 5719 if (!FS.hasValidThousandsGroupingPrefix()) 5720 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 5721 if (!FS.hasValidLeadingZeros()) 5722 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 5723 if (!FS.hasValidPlusPrefix()) 5724 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 5725 if (!FS.hasValidSpacePrefix()) 5726 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 5727 if (!FS.hasValidAlternativeForm()) 5728 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 5729 if (!FS.hasValidLeftJustified()) 5730 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 5731 5732 // Check that flags are not ignored by another flag 5733 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 5734 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 5735 startSpecifier, specifierLen); 5736 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 5737 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 5738 startSpecifier, specifierLen); 5739 5740 // Check the length modifier is valid with the given conversion specifier. 5741 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 5742 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5743 diag::warn_format_nonsensical_length); 5744 else if (!FS.hasStandardLengthModifier()) 5745 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 5746 else if (!FS.hasStandardLengthConversionCombination()) 5747 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5748 diag::warn_format_non_standard_conversion_spec); 5749 5750 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 5751 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 5752 5753 // The remaining checks depend on the data arguments. 5754 if (HasVAListArg) 5755 return true; 5756 5757 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 5758 return false; 5759 5760 const Expr *Arg = getDataArg(argIndex); 5761 if (!Arg) 5762 return true; 5763 5764 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 5765 } 5766 5767 static bool requiresParensToAddCast(const Expr *E) { 5768 // FIXME: We should have a general way to reason about operator 5769 // precedence and whether parens are actually needed here. 5770 // Take care of a few common cases where they aren't. 5771 const Expr *Inside = E->IgnoreImpCasts(); 5772 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 5773 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 5774 5775 switch (Inside->getStmtClass()) { 5776 case Stmt::ArraySubscriptExprClass: 5777 case Stmt::CallExprClass: 5778 case Stmt::CharacterLiteralClass: 5779 case Stmt::CXXBoolLiteralExprClass: 5780 case Stmt::DeclRefExprClass: 5781 case Stmt::FloatingLiteralClass: 5782 case Stmt::IntegerLiteralClass: 5783 case Stmt::MemberExprClass: 5784 case Stmt::ObjCArrayLiteralClass: 5785 case Stmt::ObjCBoolLiteralExprClass: 5786 case Stmt::ObjCBoxedExprClass: 5787 case Stmt::ObjCDictionaryLiteralClass: 5788 case Stmt::ObjCEncodeExprClass: 5789 case Stmt::ObjCIvarRefExprClass: 5790 case Stmt::ObjCMessageExprClass: 5791 case Stmt::ObjCPropertyRefExprClass: 5792 case Stmt::ObjCStringLiteralClass: 5793 case Stmt::ObjCSubscriptRefExprClass: 5794 case Stmt::ParenExprClass: 5795 case Stmt::StringLiteralClass: 5796 case Stmt::UnaryOperatorClass: 5797 return false; 5798 default: 5799 return true; 5800 } 5801 } 5802 5803 static std::pair<QualType, StringRef> 5804 shouldNotPrintDirectly(const ASTContext &Context, 5805 QualType IntendedTy, 5806 const Expr *E) { 5807 // Use a 'while' to peel off layers of typedefs. 5808 QualType TyTy = IntendedTy; 5809 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 5810 StringRef Name = UserTy->getDecl()->getName(); 5811 QualType CastTy = llvm::StringSwitch<QualType>(Name) 5812 .Case("NSInteger", Context.LongTy) 5813 .Case("NSUInteger", Context.UnsignedLongTy) 5814 .Case("SInt32", Context.IntTy) 5815 .Case("UInt32", Context.UnsignedIntTy) 5816 .Default(QualType()); 5817 5818 if (!CastTy.isNull()) 5819 return std::make_pair(CastTy, Name); 5820 5821 TyTy = UserTy->desugar(); 5822 } 5823 5824 // Strip parens if necessary. 5825 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 5826 return shouldNotPrintDirectly(Context, 5827 PE->getSubExpr()->getType(), 5828 PE->getSubExpr()); 5829 5830 // If this is a conditional expression, then its result type is constructed 5831 // via usual arithmetic conversions and thus there might be no necessary 5832 // typedef sugar there. Recurse to operands to check for NSInteger & 5833 // Co. usage condition. 5834 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 5835 QualType TrueTy, FalseTy; 5836 StringRef TrueName, FalseName; 5837 5838 std::tie(TrueTy, TrueName) = 5839 shouldNotPrintDirectly(Context, 5840 CO->getTrueExpr()->getType(), 5841 CO->getTrueExpr()); 5842 std::tie(FalseTy, FalseName) = 5843 shouldNotPrintDirectly(Context, 5844 CO->getFalseExpr()->getType(), 5845 CO->getFalseExpr()); 5846 5847 if (TrueTy == FalseTy) 5848 return std::make_pair(TrueTy, TrueName); 5849 else if (TrueTy.isNull()) 5850 return std::make_pair(FalseTy, FalseName); 5851 else if (FalseTy.isNull()) 5852 return std::make_pair(TrueTy, TrueName); 5853 } 5854 5855 return std::make_pair(QualType(), StringRef()); 5856 } 5857 5858 bool 5859 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5860 const char *StartSpecifier, 5861 unsigned SpecifierLen, 5862 const Expr *E) { 5863 using namespace analyze_format_string; 5864 using namespace analyze_printf; 5865 // Now type check the data expression that matches the 5866 // format specifier. 5867 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 5868 if (!AT.isValid()) 5869 return true; 5870 5871 QualType ExprTy = E->getType(); 5872 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 5873 ExprTy = TET->getUnderlyingExpr()->getType(); 5874 } 5875 5876 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 5877 5878 if (match == analyze_printf::ArgType::Match) { 5879 return true; 5880 } 5881 5882 // Look through argument promotions for our error message's reported type. 5883 // This includes the integral and floating promotions, but excludes array 5884 // and function pointer decay; seeing that an argument intended to be a 5885 // string has type 'char [6]' is probably more confusing than 'char *'. 5886 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5887 if (ICE->getCastKind() == CK_IntegralCast || 5888 ICE->getCastKind() == CK_FloatingCast) { 5889 E = ICE->getSubExpr(); 5890 ExprTy = E->getType(); 5891 5892 // Check if we didn't match because of an implicit cast from a 'char' 5893 // or 'short' to an 'int'. This is done because printf is a varargs 5894 // function. 5895 if (ICE->getType() == S.Context.IntTy || 5896 ICE->getType() == S.Context.UnsignedIntTy) { 5897 // All further checking is done on the subexpression. 5898 if (AT.matchesType(S.Context, ExprTy)) 5899 return true; 5900 } 5901 } 5902 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 5903 // Special case for 'a', which has type 'int' in C. 5904 // Note, however, that we do /not/ want to treat multibyte constants like 5905 // 'MooV' as characters! This form is deprecated but still exists. 5906 if (ExprTy == S.Context.IntTy) 5907 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 5908 ExprTy = S.Context.CharTy; 5909 } 5910 5911 // Look through enums to their underlying type. 5912 bool IsEnum = false; 5913 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 5914 ExprTy = EnumTy->getDecl()->getIntegerType(); 5915 IsEnum = true; 5916 } 5917 5918 // %C in an Objective-C context prints a unichar, not a wchar_t. 5919 // If the argument is an integer of some kind, believe the %C and suggest 5920 // a cast instead of changing the conversion specifier. 5921 QualType IntendedTy = ExprTy; 5922 if (isObjCContext() && 5923 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 5924 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 5925 !ExprTy->isCharType()) { 5926 // 'unichar' is defined as a typedef of unsigned short, but we should 5927 // prefer using the typedef if it is visible. 5928 IntendedTy = S.Context.UnsignedShortTy; 5929 5930 // While we are here, check if the value is an IntegerLiteral that happens 5931 // to be within the valid range. 5932 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 5933 const llvm::APInt &V = IL->getValue(); 5934 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 5935 return true; 5936 } 5937 5938 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 5939 Sema::LookupOrdinaryName); 5940 if (S.LookupName(Result, S.getCurScope())) { 5941 NamedDecl *ND = Result.getFoundDecl(); 5942 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 5943 if (TD->getUnderlyingType() == IntendedTy) 5944 IntendedTy = S.Context.getTypedefType(TD); 5945 } 5946 } 5947 } 5948 5949 // Special-case some of Darwin's platform-independence types by suggesting 5950 // casts to primitive types that are known to be large enough. 5951 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 5952 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 5953 QualType CastTy; 5954 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 5955 if (!CastTy.isNull()) { 5956 IntendedTy = CastTy; 5957 ShouldNotPrintDirectly = true; 5958 } 5959 } 5960 5961 // We may be able to offer a FixItHint if it is a supported type. 5962 PrintfSpecifier fixedFS = FS; 5963 bool success = 5964 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 5965 5966 if (success) { 5967 // Get the fix string from the fixed format specifier 5968 SmallString<16> buf; 5969 llvm::raw_svector_ostream os(buf); 5970 fixedFS.toString(os); 5971 5972 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 5973 5974 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 5975 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 5976 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 5977 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 5978 } 5979 // In this case, the specifier is wrong and should be changed to match 5980 // the argument. 5981 EmitFormatDiagnostic(S.PDiag(diag) 5982 << AT.getRepresentativeTypeName(S.Context) 5983 << IntendedTy << IsEnum << E->getSourceRange(), 5984 E->getLocStart(), 5985 /*IsStringLocation*/ false, SpecRange, 5986 FixItHint::CreateReplacement(SpecRange, os.str())); 5987 } else { 5988 // The canonical type for formatting this value is different from the 5989 // actual type of the expression. (This occurs, for example, with Darwin's 5990 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 5991 // should be printed as 'long' for 64-bit compatibility.) 5992 // Rather than emitting a normal format/argument mismatch, we want to 5993 // add a cast to the recommended type (and correct the format string 5994 // if necessary). 5995 SmallString<16> CastBuf; 5996 llvm::raw_svector_ostream CastFix(CastBuf); 5997 CastFix << "("; 5998 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 5999 CastFix << ")"; 6000 6001 SmallVector<FixItHint,4> Hints; 6002 if (!AT.matchesType(S.Context, IntendedTy)) 6003 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 6004 6005 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 6006 // If there's already a cast present, just replace it. 6007 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 6008 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 6009 6010 } else if (!requiresParensToAddCast(E)) { 6011 // If the expression has high enough precedence, 6012 // just write the C-style cast. 6013 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6014 CastFix.str())); 6015 } else { 6016 // Otherwise, add parens around the expression as well as the cast. 6017 CastFix << "("; 6018 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6019 CastFix.str())); 6020 6021 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6022 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6023 } 6024 6025 if (ShouldNotPrintDirectly) { 6026 // The expression has a type that should not be printed directly. 6027 // We extract the name from the typedef because we don't want to show 6028 // the underlying type in the diagnostic. 6029 StringRef Name; 6030 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6031 Name = TypedefTy->getDecl()->getName(); 6032 else 6033 Name = CastTyName; 6034 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6035 << Name << IntendedTy << IsEnum 6036 << E->getSourceRange(), 6037 E->getLocStart(), /*IsStringLocation=*/false, 6038 SpecRange, Hints); 6039 } else { 6040 // In this case, the expression could be printed using a different 6041 // specifier, but we've decided that the specifier is probably correct 6042 // and we should cast instead. Just use the normal warning message. 6043 EmitFormatDiagnostic( 6044 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6045 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6046 << E->getSourceRange(), 6047 E->getLocStart(), /*IsStringLocation*/false, 6048 SpecRange, Hints); 6049 } 6050 } 6051 } else { 6052 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6053 SpecifierLen); 6054 // Since the warning for passing non-POD types to variadic functions 6055 // was deferred until now, we emit a warning for non-POD 6056 // arguments here. 6057 switch (S.isValidVarArgType(ExprTy)) { 6058 case Sema::VAK_Valid: 6059 case Sema::VAK_ValidInCXX11: { 6060 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6061 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6062 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6063 } 6064 6065 EmitFormatDiagnostic( 6066 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6067 << IsEnum << CSR << E->getSourceRange(), 6068 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6069 break; 6070 } 6071 case Sema::VAK_Undefined: 6072 case Sema::VAK_MSVCUndefined: 6073 EmitFormatDiagnostic( 6074 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6075 << S.getLangOpts().CPlusPlus11 6076 << ExprTy 6077 << CallType 6078 << AT.getRepresentativeTypeName(S.Context) 6079 << CSR 6080 << E->getSourceRange(), 6081 E->getLocStart(), /*IsStringLocation*/false, CSR); 6082 checkForCStrMembers(AT, E); 6083 break; 6084 6085 case Sema::VAK_Invalid: 6086 if (ExprTy->isObjCObjectType()) 6087 EmitFormatDiagnostic( 6088 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 6089 << S.getLangOpts().CPlusPlus11 6090 << ExprTy 6091 << CallType 6092 << AT.getRepresentativeTypeName(S.Context) 6093 << CSR 6094 << E->getSourceRange(), 6095 E->getLocStart(), /*IsStringLocation*/false, CSR); 6096 else 6097 // FIXME: If this is an initializer list, suggest removing the braces 6098 // or inserting a cast to the target type. 6099 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 6100 << isa<InitListExpr>(E) << ExprTy << CallType 6101 << AT.getRepresentativeTypeName(S.Context) 6102 << E->getSourceRange(); 6103 break; 6104 } 6105 6106 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 6107 "format string specifier index out of range"); 6108 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 6109 } 6110 6111 return true; 6112 } 6113 6114 //===--- CHECK: Scanf format string checking ------------------------------===// 6115 6116 namespace { 6117 class CheckScanfHandler : public CheckFormatHandler { 6118 public: 6119 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 6120 const Expr *origFormatExpr, Sema::FormatStringType type, 6121 unsigned firstDataArg, unsigned numDataArgs, 6122 const char *beg, bool hasVAListArg, 6123 ArrayRef<const Expr *> Args, unsigned formatIdx, 6124 bool inFunctionCall, Sema::VariadicCallType CallType, 6125 llvm::SmallBitVector &CheckedVarArgs, 6126 UncoveredArgHandler &UncoveredArg) 6127 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6128 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6129 inFunctionCall, CallType, CheckedVarArgs, 6130 UncoveredArg) {} 6131 6132 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 6133 const char *startSpecifier, 6134 unsigned specifierLen) override; 6135 6136 bool HandleInvalidScanfConversionSpecifier( 6137 const analyze_scanf::ScanfSpecifier &FS, 6138 const char *startSpecifier, 6139 unsigned specifierLen) override; 6140 6141 void HandleIncompleteScanList(const char *start, const char *end) override; 6142 }; 6143 } // end anonymous namespace 6144 6145 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 6146 const char *end) { 6147 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 6148 getLocationOfByte(end), /*IsStringLocation*/true, 6149 getSpecifierRange(start, end - start)); 6150 } 6151 6152 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 6153 const analyze_scanf::ScanfSpecifier &FS, 6154 const char *startSpecifier, 6155 unsigned specifierLen) { 6156 6157 const analyze_scanf::ScanfConversionSpecifier &CS = 6158 FS.getConversionSpecifier(); 6159 6160 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6161 getLocationOfByte(CS.getStart()), 6162 startSpecifier, specifierLen, 6163 CS.getStart(), CS.getLength()); 6164 } 6165 6166 bool CheckScanfHandler::HandleScanfSpecifier( 6167 const analyze_scanf::ScanfSpecifier &FS, 6168 const char *startSpecifier, 6169 unsigned specifierLen) { 6170 using namespace analyze_scanf; 6171 using namespace analyze_format_string; 6172 6173 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 6174 6175 // Handle case where '%' and '*' don't consume an argument. These shouldn't 6176 // be used to decide if we are using positional arguments consistently. 6177 if (FS.consumesDataArgument()) { 6178 if (atFirstArg) { 6179 atFirstArg = false; 6180 usesPositionalArgs = FS.usesPositionalArg(); 6181 } 6182 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6183 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6184 startSpecifier, specifierLen); 6185 return false; 6186 } 6187 } 6188 6189 // Check if the field with is non-zero. 6190 const OptionalAmount &Amt = FS.getFieldWidth(); 6191 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 6192 if (Amt.getConstantAmount() == 0) { 6193 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 6194 Amt.getConstantLength()); 6195 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 6196 getLocationOfByte(Amt.getStart()), 6197 /*IsStringLocation*/true, R, 6198 FixItHint::CreateRemoval(R)); 6199 } 6200 } 6201 6202 if (!FS.consumesDataArgument()) { 6203 // FIXME: Technically specifying a precision or field width here 6204 // makes no sense. Worth issuing a warning at some point. 6205 return true; 6206 } 6207 6208 // Consume the argument. 6209 unsigned argIndex = FS.getArgIndex(); 6210 if (argIndex < NumDataArgs) { 6211 // The check to see if the argIndex is valid will come later. 6212 // We set the bit here because we may exit early from this 6213 // function if we encounter some other error. 6214 CoveredArgs.set(argIndex); 6215 } 6216 6217 // Check the length modifier is valid with the given conversion specifier. 6218 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6219 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6220 diag::warn_format_nonsensical_length); 6221 else if (!FS.hasStandardLengthModifier()) 6222 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6223 else if (!FS.hasStandardLengthConversionCombination()) 6224 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6225 diag::warn_format_non_standard_conversion_spec); 6226 6227 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6228 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6229 6230 // The remaining checks depend on the data arguments. 6231 if (HasVAListArg) 6232 return true; 6233 6234 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6235 return false; 6236 6237 // Check that the argument type matches the format specifier. 6238 const Expr *Ex = getDataArg(argIndex); 6239 if (!Ex) 6240 return true; 6241 6242 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 6243 6244 if (!AT.isValid()) { 6245 return true; 6246 } 6247 6248 analyze_format_string::ArgType::MatchKind match = 6249 AT.matchesType(S.Context, Ex->getType()); 6250 if (match == analyze_format_string::ArgType::Match) { 6251 return true; 6252 } 6253 6254 ScanfSpecifier fixedFS = FS; 6255 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 6256 S.getLangOpts(), S.Context); 6257 6258 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6259 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6260 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6261 } 6262 6263 if (success) { 6264 // Get the fix string from the fixed format specifier. 6265 SmallString<128> buf; 6266 llvm::raw_svector_ostream os(buf); 6267 fixedFS.toString(os); 6268 6269 EmitFormatDiagnostic( 6270 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 6271 << Ex->getType() << false << Ex->getSourceRange(), 6272 Ex->getLocStart(), 6273 /*IsStringLocation*/ false, 6274 getSpecifierRange(startSpecifier, specifierLen), 6275 FixItHint::CreateReplacement( 6276 getSpecifierRange(startSpecifier, specifierLen), os.str())); 6277 } else { 6278 EmitFormatDiagnostic(S.PDiag(diag) 6279 << AT.getRepresentativeTypeName(S.Context) 6280 << Ex->getType() << false << Ex->getSourceRange(), 6281 Ex->getLocStart(), 6282 /*IsStringLocation*/ false, 6283 getSpecifierRange(startSpecifier, specifierLen)); 6284 } 6285 6286 return true; 6287 } 6288 6289 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6290 const Expr *OrigFormatExpr, 6291 ArrayRef<const Expr *> Args, 6292 bool HasVAListArg, unsigned format_idx, 6293 unsigned firstDataArg, 6294 Sema::FormatStringType Type, 6295 bool inFunctionCall, 6296 Sema::VariadicCallType CallType, 6297 llvm::SmallBitVector &CheckedVarArgs, 6298 UncoveredArgHandler &UncoveredArg) { 6299 // CHECK: is the format string a wide literal? 6300 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 6301 CheckFormatHandler::EmitFormatDiagnostic( 6302 S, inFunctionCall, Args[format_idx], 6303 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 6304 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6305 return; 6306 } 6307 6308 // Str - The format string. NOTE: this is NOT null-terminated! 6309 StringRef StrRef = FExpr->getString(); 6310 const char *Str = StrRef.data(); 6311 // Account for cases where the string literal is truncated in a declaration. 6312 const ConstantArrayType *T = 6313 S.Context.getAsConstantArrayType(FExpr->getType()); 6314 assert(T && "String literal not of constant array type!"); 6315 size_t TypeSize = T->getSize().getZExtValue(); 6316 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6317 const unsigned numDataArgs = Args.size() - firstDataArg; 6318 6319 // Emit a warning if the string literal is truncated and does not contain an 6320 // embedded null character. 6321 if (TypeSize <= StrRef.size() && 6322 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 6323 CheckFormatHandler::EmitFormatDiagnostic( 6324 S, inFunctionCall, Args[format_idx], 6325 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 6326 FExpr->getLocStart(), 6327 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 6328 return; 6329 } 6330 6331 // CHECK: empty format string? 6332 if (StrLen == 0 && numDataArgs > 0) { 6333 CheckFormatHandler::EmitFormatDiagnostic( 6334 S, inFunctionCall, Args[format_idx], 6335 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 6336 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6337 return; 6338 } 6339 6340 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 6341 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 6342 Type == Sema::FST_OSTrace) { 6343 CheckPrintfHandler H( 6344 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 6345 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 6346 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 6347 CheckedVarArgs, UncoveredArg); 6348 6349 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 6350 S.getLangOpts(), 6351 S.Context.getTargetInfo(), 6352 Type == Sema::FST_FreeBSDKPrintf)) 6353 H.DoneProcessing(); 6354 } else if (Type == Sema::FST_Scanf) { 6355 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 6356 numDataArgs, Str, HasVAListArg, Args, format_idx, 6357 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 6358 6359 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 6360 S.getLangOpts(), 6361 S.Context.getTargetInfo())) 6362 H.DoneProcessing(); 6363 } // TODO: handle other formats 6364 } 6365 6366 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 6367 // Str - The format string. NOTE: this is NOT null-terminated! 6368 StringRef StrRef = FExpr->getString(); 6369 const char *Str = StrRef.data(); 6370 // Account for cases where the string literal is truncated in a declaration. 6371 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 6372 assert(T && "String literal not of constant array type!"); 6373 size_t TypeSize = T->getSize().getZExtValue(); 6374 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6375 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 6376 getLangOpts(), 6377 Context.getTargetInfo()); 6378 } 6379 6380 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 6381 6382 // Returns the related absolute value function that is larger, of 0 if one 6383 // does not exist. 6384 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 6385 switch (AbsFunction) { 6386 default: 6387 return 0; 6388 6389 case Builtin::BI__builtin_abs: 6390 return Builtin::BI__builtin_labs; 6391 case Builtin::BI__builtin_labs: 6392 return Builtin::BI__builtin_llabs; 6393 case Builtin::BI__builtin_llabs: 6394 return 0; 6395 6396 case Builtin::BI__builtin_fabsf: 6397 return Builtin::BI__builtin_fabs; 6398 case Builtin::BI__builtin_fabs: 6399 return Builtin::BI__builtin_fabsl; 6400 case Builtin::BI__builtin_fabsl: 6401 return 0; 6402 6403 case Builtin::BI__builtin_cabsf: 6404 return Builtin::BI__builtin_cabs; 6405 case Builtin::BI__builtin_cabs: 6406 return Builtin::BI__builtin_cabsl; 6407 case Builtin::BI__builtin_cabsl: 6408 return 0; 6409 6410 case Builtin::BIabs: 6411 return Builtin::BIlabs; 6412 case Builtin::BIlabs: 6413 return Builtin::BIllabs; 6414 case Builtin::BIllabs: 6415 return 0; 6416 6417 case Builtin::BIfabsf: 6418 return Builtin::BIfabs; 6419 case Builtin::BIfabs: 6420 return Builtin::BIfabsl; 6421 case Builtin::BIfabsl: 6422 return 0; 6423 6424 case Builtin::BIcabsf: 6425 return Builtin::BIcabs; 6426 case Builtin::BIcabs: 6427 return Builtin::BIcabsl; 6428 case Builtin::BIcabsl: 6429 return 0; 6430 } 6431 } 6432 6433 // Returns the argument type of the absolute value function. 6434 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 6435 unsigned AbsType) { 6436 if (AbsType == 0) 6437 return QualType(); 6438 6439 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 6440 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 6441 if (Error != ASTContext::GE_None) 6442 return QualType(); 6443 6444 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 6445 if (!FT) 6446 return QualType(); 6447 6448 if (FT->getNumParams() != 1) 6449 return QualType(); 6450 6451 return FT->getParamType(0); 6452 } 6453 6454 // Returns the best absolute value function, or zero, based on type and 6455 // current absolute value function. 6456 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 6457 unsigned AbsFunctionKind) { 6458 unsigned BestKind = 0; 6459 uint64_t ArgSize = Context.getTypeSize(ArgType); 6460 for (unsigned Kind = AbsFunctionKind; Kind != 0; 6461 Kind = getLargerAbsoluteValueFunction(Kind)) { 6462 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 6463 if (Context.getTypeSize(ParamType) >= ArgSize) { 6464 if (BestKind == 0) 6465 BestKind = Kind; 6466 else if (Context.hasSameType(ParamType, ArgType)) { 6467 BestKind = Kind; 6468 break; 6469 } 6470 } 6471 } 6472 return BestKind; 6473 } 6474 6475 enum AbsoluteValueKind { 6476 AVK_Integer, 6477 AVK_Floating, 6478 AVK_Complex 6479 }; 6480 6481 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 6482 if (T->isIntegralOrEnumerationType()) 6483 return AVK_Integer; 6484 if (T->isRealFloatingType()) 6485 return AVK_Floating; 6486 if (T->isAnyComplexType()) 6487 return AVK_Complex; 6488 6489 llvm_unreachable("Type not integer, floating, or complex"); 6490 } 6491 6492 // Changes the absolute value function to a different type. Preserves whether 6493 // the function is a builtin. 6494 static unsigned changeAbsFunction(unsigned AbsKind, 6495 AbsoluteValueKind ValueKind) { 6496 switch (ValueKind) { 6497 case AVK_Integer: 6498 switch (AbsKind) { 6499 default: 6500 return 0; 6501 case Builtin::BI__builtin_fabsf: 6502 case Builtin::BI__builtin_fabs: 6503 case Builtin::BI__builtin_fabsl: 6504 case Builtin::BI__builtin_cabsf: 6505 case Builtin::BI__builtin_cabs: 6506 case Builtin::BI__builtin_cabsl: 6507 return Builtin::BI__builtin_abs; 6508 case Builtin::BIfabsf: 6509 case Builtin::BIfabs: 6510 case Builtin::BIfabsl: 6511 case Builtin::BIcabsf: 6512 case Builtin::BIcabs: 6513 case Builtin::BIcabsl: 6514 return Builtin::BIabs; 6515 } 6516 case AVK_Floating: 6517 switch (AbsKind) { 6518 default: 6519 return 0; 6520 case Builtin::BI__builtin_abs: 6521 case Builtin::BI__builtin_labs: 6522 case Builtin::BI__builtin_llabs: 6523 case Builtin::BI__builtin_cabsf: 6524 case Builtin::BI__builtin_cabs: 6525 case Builtin::BI__builtin_cabsl: 6526 return Builtin::BI__builtin_fabsf; 6527 case Builtin::BIabs: 6528 case Builtin::BIlabs: 6529 case Builtin::BIllabs: 6530 case Builtin::BIcabsf: 6531 case Builtin::BIcabs: 6532 case Builtin::BIcabsl: 6533 return Builtin::BIfabsf; 6534 } 6535 case AVK_Complex: 6536 switch (AbsKind) { 6537 default: 6538 return 0; 6539 case Builtin::BI__builtin_abs: 6540 case Builtin::BI__builtin_labs: 6541 case Builtin::BI__builtin_llabs: 6542 case Builtin::BI__builtin_fabsf: 6543 case Builtin::BI__builtin_fabs: 6544 case Builtin::BI__builtin_fabsl: 6545 return Builtin::BI__builtin_cabsf; 6546 case Builtin::BIabs: 6547 case Builtin::BIlabs: 6548 case Builtin::BIllabs: 6549 case Builtin::BIfabsf: 6550 case Builtin::BIfabs: 6551 case Builtin::BIfabsl: 6552 return Builtin::BIcabsf; 6553 } 6554 } 6555 llvm_unreachable("Unable to convert function"); 6556 } 6557 6558 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 6559 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 6560 if (!FnInfo) 6561 return 0; 6562 6563 switch (FDecl->getBuiltinID()) { 6564 default: 6565 return 0; 6566 case Builtin::BI__builtin_abs: 6567 case Builtin::BI__builtin_fabs: 6568 case Builtin::BI__builtin_fabsf: 6569 case Builtin::BI__builtin_fabsl: 6570 case Builtin::BI__builtin_labs: 6571 case Builtin::BI__builtin_llabs: 6572 case Builtin::BI__builtin_cabs: 6573 case Builtin::BI__builtin_cabsf: 6574 case Builtin::BI__builtin_cabsl: 6575 case Builtin::BIabs: 6576 case Builtin::BIlabs: 6577 case Builtin::BIllabs: 6578 case Builtin::BIfabs: 6579 case Builtin::BIfabsf: 6580 case Builtin::BIfabsl: 6581 case Builtin::BIcabs: 6582 case Builtin::BIcabsf: 6583 case Builtin::BIcabsl: 6584 return FDecl->getBuiltinID(); 6585 } 6586 llvm_unreachable("Unknown Builtin type"); 6587 } 6588 6589 // If the replacement is valid, emit a note with replacement function. 6590 // Additionally, suggest including the proper header if not already included. 6591 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 6592 unsigned AbsKind, QualType ArgType) { 6593 bool EmitHeaderHint = true; 6594 const char *HeaderName = nullptr; 6595 const char *FunctionName = nullptr; 6596 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 6597 FunctionName = "std::abs"; 6598 if (ArgType->isIntegralOrEnumerationType()) { 6599 HeaderName = "cstdlib"; 6600 } else if (ArgType->isRealFloatingType()) { 6601 HeaderName = "cmath"; 6602 } else { 6603 llvm_unreachable("Invalid Type"); 6604 } 6605 6606 // Lookup all std::abs 6607 if (NamespaceDecl *Std = S.getStdNamespace()) { 6608 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 6609 R.suppressDiagnostics(); 6610 S.LookupQualifiedName(R, Std); 6611 6612 for (const auto *I : R) { 6613 const FunctionDecl *FDecl = nullptr; 6614 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 6615 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 6616 } else { 6617 FDecl = dyn_cast<FunctionDecl>(I); 6618 } 6619 if (!FDecl) 6620 continue; 6621 6622 // Found std::abs(), check that they are the right ones. 6623 if (FDecl->getNumParams() != 1) 6624 continue; 6625 6626 // Check that the parameter type can handle the argument. 6627 QualType ParamType = FDecl->getParamDecl(0)->getType(); 6628 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 6629 S.Context.getTypeSize(ArgType) <= 6630 S.Context.getTypeSize(ParamType)) { 6631 // Found a function, don't need the header hint. 6632 EmitHeaderHint = false; 6633 break; 6634 } 6635 } 6636 } 6637 } else { 6638 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 6639 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 6640 6641 if (HeaderName) { 6642 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 6643 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 6644 R.suppressDiagnostics(); 6645 S.LookupName(R, S.getCurScope()); 6646 6647 if (R.isSingleResult()) { 6648 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 6649 if (FD && FD->getBuiltinID() == AbsKind) { 6650 EmitHeaderHint = false; 6651 } else { 6652 return; 6653 } 6654 } else if (!R.empty()) { 6655 return; 6656 } 6657 } 6658 } 6659 6660 S.Diag(Loc, diag::note_replace_abs_function) 6661 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 6662 6663 if (!HeaderName) 6664 return; 6665 6666 if (!EmitHeaderHint) 6667 return; 6668 6669 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 6670 << FunctionName; 6671 } 6672 6673 template <std::size_t StrLen> 6674 static bool IsStdFunction(const FunctionDecl *FDecl, 6675 const char (&Str)[StrLen]) { 6676 if (!FDecl) 6677 return false; 6678 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 6679 return false; 6680 if (!FDecl->isInStdNamespace()) 6681 return false; 6682 6683 return true; 6684 } 6685 6686 // Warn when using the wrong abs() function. 6687 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 6688 const FunctionDecl *FDecl) { 6689 if (Call->getNumArgs() != 1) 6690 return; 6691 6692 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 6693 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 6694 if (AbsKind == 0 && !IsStdAbs) 6695 return; 6696 6697 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 6698 QualType ParamType = Call->getArg(0)->getType(); 6699 6700 // Unsigned types cannot be negative. Suggest removing the absolute value 6701 // function call. 6702 if (ArgType->isUnsignedIntegerType()) { 6703 const char *FunctionName = 6704 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 6705 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 6706 Diag(Call->getExprLoc(), diag::note_remove_abs) 6707 << FunctionName 6708 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 6709 return; 6710 } 6711 6712 // Taking the absolute value of a pointer is very suspicious, they probably 6713 // wanted to index into an array, dereference a pointer, call a function, etc. 6714 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 6715 unsigned DiagType = 0; 6716 if (ArgType->isFunctionType()) 6717 DiagType = 1; 6718 else if (ArgType->isArrayType()) 6719 DiagType = 2; 6720 6721 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 6722 return; 6723 } 6724 6725 // std::abs has overloads which prevent most of the absolute value problems 6726 // from occurring. 6727 if (IsStdAbs) 6728 return; 6729 6730 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 6731 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 6732 6733 // The argument and parameter are the same kind. Check if they are the right 6734 // size. 6735 if (ArgValueKind == ParamValueKind) { 6736 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 6737 return; 6738 6739 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 6740 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 6741 << FDecl << ArgType << ParamType; 6742 6743 if (NewAbsKind == 0) 6744 return; 6745 6746 emitReplacement(*this, Call->getExprLoc(), 6747 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6748 return; 6749 } 6750 6751 // ArgValueKind != ParamValueKind 6752 // The wrong type of absolute value function was used. Attempt to find the 6753 // proper one. 6754 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 6755 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 6756 if (NewAbsKind == 0) 6757 return; 6758 6759 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 6760 << FDecl << ParamValueKind << ArgValueKind; 6761 6762 emitReplacement(*this, Call->getExprLoc(), 6763 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6764 } 6765 6766 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 6767 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 6768 const FunctionDecl *FDecl) { 6769 if (!Call || !FDecl) return; 6770 6771 // Ignore template specializations and macros. 6772 if (!ActiveTemplateInstantiations.empty()) return; 6773 if (Call->getExprLoc().isMacroID()) return; 6774 6775 // Only care about the one template argument, two function parameter std::max 6776 if (Call->getNumArgs() != 2) return; 6777 if (!IsStdFunction(FDecl, "max")) return; 6778 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 6779 if (!ArgList) return; 6780 if (ArgList->size() != 1) return; 6781 6782 // Check that template type argument is unsigned integer. 6783 const auto& TA = ArgList->get(0); 6784 if (TA.getKind() != TemplateArgument::Type) return; 6785 QualType ArgType = TA.getAsType(); 6786 if (!ArgType->isUnsignedIntegerType()) return; 6787 6788 // See if either argument is a literal zero. 6789 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 6790 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 6791 if (!MTE) return false; 6792 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 6793 if (!Num) return false; 6794 if (Num->getValue() != 0) return false; 6795 return true; 6796 }; 6797 6798 const Expr *FirstArg = Call->getArg(0); 6799 const Expr *SecondArg = Call->getArg(1); 6800 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 6801 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 6802 6803 // Only warn when exactly one argument is zero. 6804 if (IsFirstArgZero == IsSecondArgZero) return; 6805 6806 SourceRange FirstRange = FirstArg->getSourceRange(); 6807 SourceRange SecondRange = SecondArg->getSourceRange(); 6808 6809 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 6810 6811 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 6812 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 6813 6814 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 6815 SourceRange RemovalRange; 6816 if (IsFirstArgZero) { 6817 RemovalRange = SourceRange(FirstRange.getBegin(), 6818 SecondRange.getBegin().getLocWithOffset(-1)); 6819 } else { 6820 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 6821 SecondRange.getEnd()); 6822 } 6823 6824 Diag(Call->getExprLoc(), diag::note_remove_max_call) 6825 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 6826 << FixItHint::CreateRemoval(RemovalRange); 6827 } 6828 6829 //===--- CHECK: Standard memory functions ---------------------------------===// 6830 6831 /// \brief Takes the expression passed to the size_t parameter of functions 6832 /// such as memcmp, strncat, etc and warns if it's a comparison. 6833 /// 6834 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 6835 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 6836 IdentifierInfo *FnName, 6837 SourceLocation FnLoc, 6838 SourceLocation RParenLoc) { 6839 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 6840 if (!Size) 6841 return false; 6842 6843 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 6844 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 6845 return false; 6846 6847 SourceRange SizeRange = Size->getSourceRange(); 6848 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 6849 << SizeRange << FnName; 6850 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 6851 << FnName << FixItHint::CreateInsertion( 6852 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 6853 << FixItHint::CreateRemoval(RParenLoc); 6854 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 6855 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 6856 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 6857 ")"); 6858 6859 return true; 6860 } 6861 6862 /// \brief Determine whether the given type is or contains a dynamic class type 6863 /// (e.g., whether it has a vtable). 6864 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 6865 bool &IsContained) { 6866 // Look through array types while ignoring qualifiers. 6867 const Type *Ty = T->getBaseElementTypeUnsafe(); 6868 IsContained = false; 6869 6870 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 6871 RD = RD ? RD->getDefinition() : nullptr; 6872 if (!RD || RD->isInvalidDecl()) 6873 return nullptr; 6874 6875 if (RD->isDynamicClass()) 6876 return RD; 6877 6878 // Check all the fields. If any bases were dynamic, the class is dynamic. 6879 // It's impossible for a class to transitively contain itself by value, so 6880 // infinite recursion is impossible. 6881 for (auto *FD : RD->fields()) { 6882 bool SubContained; 6883 if (const CXXRecordDecl *ContainedRD = 6884 getContainedDynamicClass(FD->getType(), SubContained)) { 6885 IsContained = true; 6886 return ContainedRD; 6887 } 6888 } 6889 6890 return nullptr; 6891 } 6892 6893 /// \brief If E is a sizeof expression, returns its argument expression, 6894 /// otherwise returns NULL. 6895 static const Expr *getSizeOfExprArg(const Expr *E) { 6896 if (const UnaryExprOrTypeTraitExpr *SizeOf = 6897 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 6898 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 6899 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 6900 6901 return nullptr; 6902 } 6903 6904 /// \brief If E is a sizeof expression, returns its argument type. 6905 static QualType getSizeOfArgType(const Expr *E) { 6906 if (const UnaryExprOrTypeTraitExpr *SizeOf = 6907 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 6908 if (SizeOf->getKind() == clang::UETT_SizeOf) 6909 return SizeOf->getTypeOfArgument(); 6910 6911 return QualType(); 6912 } 6913 6914 /// \brief Check for dangerous or invalid arguments to memset(). 6915 /// 6916 /// This issues warnings on known problematic, dangerous or unspecified 6917 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 6918 /// function calls. 6919 /// 6920 /// \param Call The call expression to diagnose. 6921 void Sema::CheckMemaccessArguments(const CallExpr *Call, 6922 unsigned BId, 6923 IdentifierInfo *FnName) { 6924 assert(BId != 0); 6925 6926 // It is possible to have a non-standard definition of memset. Validate 6927 // we have enough arguments, and if not, abort further checking. 6928 unsigned ExpectedNumArgs = 6929 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 6930 if (Call->getNumArgs() < ExpectedNumArgs) 6931 return; 6932 6933 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 6934 BId == Builtin::BIstrndup ? 1 : 2); 6935 unsigned LenArg = 6936 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 6937 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 6938 6939 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 6940 Call->getLocStart(), Call->getRParenLoc())) 6941 return; 6942 6943 // We have special checking when the length is a sizeof expression. 6944 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 6945 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 6946 llvm::FoldingSetNodeID SizeOfArgID; 6947 6948 // Although widely used, 'bzero' is not a standard function. Be more strict 6949 // with the argument types before allowing diagnostics and only allow the 6950 // form bzero(ptr, sizeof(...)). 6951 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 6952 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 6953 return; 6954 6955 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 6956 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 6957 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 6958 6959 QualType DestTy = Dest->getType(); 6960 QualType PointeeTy; 6961 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 6962 PointeeTy = DestPtrTy->getPointeeType(); 6963 6964 // Never warn about void type pointers. This can be used to suppress 6965 // false positives. 6966 if (PointeeTy->isVoidType()) 6967 continue; 6968 6969 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 6970 // actually comparing the expressions for equality. Because computing the 6971 // expression IDs can be expensive, we only do this if the diagnostic is 6972 // enabled. 6973 if (SizeOfArg && 6974 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 6975 SizeOfArg->getExprLoc())) { 6976 // We only compute IDs for expressions if the warning is enabled, and 6977 // cache the sizeof arg's ID. 6978 if (SizeOfArgID == llvm::FoldingSetNodeID()) 6979 SizeOfArg->Profile(SizeOfArgID, Context, true); 6980 llvm::FoldingSetNodeID DestID; 6981 Dest->Profile(DestID, Context, true); 6982 if (DestID == SizeOfArgID) { 6983 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 6984 // over sizeof(src) as well. 6985 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 6986 StringRef ReadableName = FnName->getName(); 6987 6988 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 6989 if (UnaryOp->getOpcode() == UO_AddrOf) 6990 ActionIdx = 1; // If its an address-of operator, just remove it. 6991 if (!PointeeTy->isIncompleteType() && 6992 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 6993 ActionIdx = 2; // If the pointee's size is sizeof(char), 6994 // suggest an explicit length. 6995 6996 // If the function is defined as a builtin macro, do not show macro 6997 // expansion. 6998 SourceLocation SL = SizeOfArg->getExprLoc(); 6999 SourceRange DSR = Dest->getSourceRange(); 7000 SourceRange SSR = SizeOfArg->getSourceRange(); 7001 SourceManager &SM = getSourceManager(); 7002 7003 if (SM.isMacroArgExpansion(SL)) { 7004 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 7005 SL = SM.getSpellingLoc(SL); 7006 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 7007 SM.getSpellingLoc(DSR.getEnd())); 7008 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 7009 SM.getSpellingLoc(SSR.getEnd())); 7010 } 7011 7012 DiagRuntimeBehavior(SL, SizeOfArg, 7013 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 7014 << ReadableName 7015 << PointeeTy 7016 << DestTy 7017 << DSR 7018 << SSR); 7019 DiagRuntimeBehavior(SL, SizeOfArg, 7020 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 7021 << ActionIdx 7022 << SSR); 7023 7024 break; 7025 } 7026 } 7027 7028 // Also check for cases where the sizeof argument is the exact same 7029 // type as the memory argument, and where it points to a user-defined 7030 // record type. 7031 if (SizeOfArgTy != QualType()) { 7032 if (PointeeTy->isRecordType() && 7033 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 7034 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 7035 PDiag(diag::warn_sizeof_pointer_type_memaccess) 7036 << FnName << SizeOfArgTy << ArgIdx 7037 << PointeeTy << Dest->getSourceRange() 7038 << LenExpr->getSourceRange()); 7039 break; 7040 } 7041 } 7042 } else if (DestTy->isArrayType()) { 7043 PointeeTy = DestTy; 7044 } 7045 7046 if (PointeeTy == QualType()) 7047 continue; 7048 7049 // Always complain about dynamic classes. 7050 bool IsContained; 7051 if (const CXXRecordDecl *ContainedRD = 7052 getContainedDynamicClass(PointeeTy, IsContained)) { 7053 7054 unsigned OperationType = 0; 7055 // "overwritten" if we're warning about the destination for any call 7056 // but memcmp; otherwise a verb appropriate to the call. 7057 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 7058 if (BId == Builtin::BImemcpy) 7059 OperationType = 1; 7060 else if(BId == Builtin::BImemmove) 7061 OperationType = 2; 7062 else if (BId == Builtin::BImemcmp) 7063 OperationType = 3; 7064 } 7065 7066 DiagRuntimeBehavior( 7067 Dest->getExprLoc(), Dest, 7068 PDiag(diag::warn_dyn_class_memaccess) 7069 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 7070 << FnName << IsContained << ContainedRD << OperationType 7071 << Call->getCallee()->getSourceRange()); 7072 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 7073 BId != Builtin::BImemset) 7074 DiagRuntimeBehavior( 7075 Dest->getExprLoc(), Dest, 7076 PDiag(diag::warn_arc_object_memaccess) 7077 << ArgIdx << FnName << PointeeTy 7078 << Call->getCallee()->getSourceRange()); 7079 else 7080 continue; 7081 7082 DiagRuntimeBehavior( 7083 Dest->getExprLoc(), Dest, 7084 PDiag(diag::note_bad_memaccess_silence) 7085 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 7086 break; 7087 } 7088 } 7089 7090 // A little helper routine: ignore addition and subtraction of integer literals. 7091 // This intentionally does not ignore all integer constant expressions because 7092 // we don't want to remove sizeof(). 7093 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 7094 Ex = Ex->IgnoreParenCasts(); 7095 7096 for (;;) { 7097 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 7098 if (!BO || !BO->isAdditiveOp()) 7099 break; 7100 7101 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 7102 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 7103 7104 if (isa<IntegerLiteral>(RHS)) 7105 Ex = LHS; 7106 else if (isa<IntegerLiteral>(LHS)) 7107 Ex = RHS; 7108 else 7109 break; 7110 } 7111 7112 return Ex; 7113 } 7114 7115 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 7116 ASTContext &Context) { 7117 // Only handle constant-sized or VLAs, but not flexible members. 7118 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 7119 // Only issue the FIXIT for arrays of size > 1. 7120 if (CAT->getSize().getSExtValue() <= 1) 7121 return false; 7122 } else if (!Ty->isVariableArrayType()) { 7123 return false; 7124 } 7125 return true; 7126 } 7127 7128 // Warn if the user has made the 'size' argument to strlcpy or strlcat 7129 // be the size of the source, instead of the destination. 7130 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 7131 IdentifierInfo *FnName) { 7132 7133 // Don't crash if the user has the wrong number of arguments 7134 unsigned NumArgs = Call->getNumArgs(); 7135 if ((NumArgs != 3) && (NumArgs != 4)) 7136 return; 7137 7138 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 7139 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 7140 const Expr *CompareWithSrc = nullptr; 7141 7142 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 7143 Call->getLocStart(), Call->getRParenLoc())) 7144 return; 7145 7146 // Look for 'strlcpy(dst, x, sizeof(x))' 7147 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 7148 CompareWithSrc = Ex; 7149 else { 7150 // Look for 'strlcpy(dst, x, strlen(x))' 7151 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 7152 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 7153 SizeCall->getNumArgs() == 1) 7154 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 7155 } 7156 } 7157 7158 if (!CompareWithSrc) 7159 return; 7160 7161 // Determine if the argument to sizeof/strlen is equal to the source 7162 // argument. In principle there's all kinds of things you could do 7163 // here, for instance creating an == expression and evaluating it with 7164 // EvaluateAsBooleanCondition, but this uses a more direct technique: 7165 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 7166 if (!SrcArgDRE) 7167 return; 7168 7169 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 7170 if (!CompareWithSrcDRE || 7171 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 7172 return; 7173 7174 const Expr *OriginalSizeArg = Call->getArg(2); 7175 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 7176 << OriginalSizeArg->getSourceRange() << FnName; 7177 7178 // Output a FIXIT hint if the destination is an array (rather than a 7179 // pointer to an array). This could be enhanced to handle some 7180 // pointers if we know the actual size, like if DstArg is 'array+2' 7181 // we could say 'sizeof(array)-2'. 7182 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 7183 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 7184 return; 7185 7186 SmallString<128> sizeString; 7187 llvm::raw_svector_ostream OS(sizeString); 7188 OS << "sizeof("; 7189 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7190 OS << ")"; 7191 7192 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 7193 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 7194 OS.str()); 7195 } 7196 7197 /// Check if two expressions refer to the same declaration. 7198 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 7199 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 7200 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 7201 return D1->getDecl() == D2->getDecl(); 7202 return false; 7203 } 7204 7205 static const Expr *getStrlenExprArg(const Expr *E) { 7206 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7207 const FunctionDecl *FD = CE->getDirectCallee(); 7208 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 7209 return nullptr; 7210 return CE->getArg(0)->IgnoreParenCasts(); 7211 } 7212 return nullptr; 7213 } 7214 7215 // Warn on anti-patterns as the 'size' argument to strncat. 7216 // The correct size argument should look like following: 7217 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 7218 void Sema::CheckStrncatArguments(const CallExpr *CE, 7219 IdentifierInfo *FnName) { 7220 // Don't crash if the user has the wrong number of arguments. 7221 if (CE->getNumArgs() < 3) 7222 return; 7223 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 7224 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 7225 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 7226 7227 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 7228 CE->getRParenLoc())) 7229 return; 7230 7231 // Identify common expressions, which are wrongly used as the size argument 7232 // to strncat and may lead to buffer overflows. 7233 unsigned PatternType = 0; 7234 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 7235 // - sizeof(dst) 7236 if (referToTheSameDecl(SizeOfArg, DstArg)) 7237 PatternType = 1; 7238 // - sizeof(src) 7239 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 7240 PatternType = 2; 7241 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 7242 if (BE->getOpcode() == BO_Sub) { 7243 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 7244 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 7245 // - sizeof(dst) - strlen(dst) 7246 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 7247 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 7248 PatternType = 1; 7249 // - sizeof(src) - (anything) 7250 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 7251 PatternType = 2; 7252 } 7253 } 7254 7255 if (PatternType == 0) 7256 return; 7257 7258 // Generate the diagnostic. 7259 SourceLocation SL = LenArg->getLocStart(); 7260 SourceRange SR = LenArg->getSourceRange(); 7261 SourceManager &SM = getSourceManager(); 7262 7263 // If the function is defined as a builtin macro, do not show macro expansion. 7264 if (SM.isMacroArgExpansion(SL)) { 7265 SL = SM.getSpellingLoc(SL); 7266 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 7267 SM.getSpellingLoc(SR.getEnd())); 7268 } 7269 7270 // Check if the destination is an array (rather than a pointer to an array). 7271 QualType DstTy = DstArg->getType(); 7272 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 7273 Context); 7274 if (!isKnownSizeArray) { 7275 if (PatternType == 1) 7276 Diag(SL, diag::warn_strncat_wrong_size) << SR; 7277 else 7278 Diag(SL, diag::warn_strncat_src_size) << SR; 7279 return; 7280 } 7281 7282 if (PatternType == 1) 7283 Diag(SL, diag::warn_strncat_large_size) << SR; 7284 else 7285 Diag(SL, diag::warn_strncat_src_size) << SR; 7286 7287 SmallString<128> sizeString; 7288 llvm::raw_svector_ostream OS(sizeString); 7289 OS << "sizeof("; 7290 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7291 OS << ") - "; 7292 OS << "strlen("; 7293 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7294 OS << ") - 1"; 7295 7296 Diag(SL, diag::note_strncat_wrong_size) 7297 << FixItHint::CreateReplacement(SR, OS.str()); 7298 } 7299 7300 //===--- CHECK: Return Address of Stack Variable --------------------------===// 7301 7302 static const Expr *EvalVal(const Expr *E, 7303 SmallVectorImpl<const DeclRefExpr *> &refVars, 7304 const Decl *ParentDecl); 7305 static const Expr *EvalAddr(const Expr *E, 7306 SmallVectorImpl<const DeclRefExpr *> &refVars, 7307 const Decl *ParentDecl); 7308 7309 /// CheckReturnStackAddr - Check if a return statement returns the address 7310 /// of a stack variable. 7311 static void 7312 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 7313 SourceLocation ReturnLoc) { 7314 7315 const Expr *stackE = nullptr; 7316 SmallVector<const DeclRefExpr *, 8> refVars; 7317 7318 // Perform checking for returned stack addresses, local blocks, 7319 // label addresses or references to temporaries. 7320 if (lhsType->isPointerType() || 7321 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 7322 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 7323 } else if (lhsType->isReferenceType()) { 7324 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 7325 } 7326 7327 if (!stackE) 7328 return; // Nothing suspicious was found. 7329 7330 // Parameters are initalized in the calling scope, so taking the address 7331 // of a parameter reference doesn't need a warning. 7332 for (auto *DRE : refVars) 7333 if (isa<ParmVarDecl>(DRE->getDecl())) 7334 return; 7335 7336 SourceLocation diagLoc; 7337 SourceRange diagRange; 7338 if (refVars.empty()) { 7339 diagLoc = stackE->getLocStart(); 7340 diagRange = stackE->getSourceRange(); 7341 } else { 7342 // We followed through a reference variable. 'stackE' contains the 7343 // problematic expression but we will warn at the return statement pointing 7344 // at the reference variable. We will later display the "trail" of 7345 // reference variables using notes. 7346 diagLoc = refVars[0]->getLocStart(); 7347 diagRange = refVars[0]->getSourceRange(); 7348 } 7349 7350 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 7351 // address of local var 7352 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 7353 << DR->getDecl()->getDeclName() << diagRange; 7354 } else if (isa<BlockExpr>(stackE)) { // local block. 7355 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 7356 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 7357 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 7358 } else { // local temporary. 7359 // If there is an LValue->RValue conversion, then the value of the 7360 // reference type is used, not the reference. 7361 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 7362 if (ICE->getCastKind() == CK_LValueToRValue) { 7363 return; 7364 } 7365 } 7366 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 7367 << lhsType->isReferenceType() << diagRange; 7368 } 7369 7370 // Display the "trail" of reference variables that we followed until we 7371 // found the problematic expression using notes. 7372 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 7373 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 7374 // If this var binds to another reference var, show the range of the next 7375 // var, otherwise the var binds to the problematic expression, in which case 7376 // show the range of the expression. 7377 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 7378 : stackE->getSourceRange(); 7379 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 7380 << VD->getDeclName() << range; 7381 } 7382 } 7383 7384 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 7385 /// check if the expression in a return statement evaluates to an address 7386 /// to a location on the stack, a local block, an address of a label, or a 7387 /// reference to local temporary. The recursion is used to traverse the 7388 /// AST of the return expression, with recursion backtracking when we 7389 /// encounter a subexpression that (1) clearly does not lead to one of the 7390 /// above problematic expressions (2) is something we cannot determine leads to 7391 /// a problematic expression based on such local checking. 7392 /// 7393 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 7394 /// the expression that they point to. Such variables are added to the 7395 /// 'refVars' vector so that we know what the reference variable "trail" was. 7396 /// 7397 /// EvalAddr processes expressions that are pointers that are used as 7398 /// references (and not L-values). EvalVal handles all other values. 7399 /// At the base case of the recursion is a check for the above problematic 7400 /// expressions. 7401 /// 7402 /// This implementation handles: 7403 /// 7404 /// * pointer-to-pointer casts 7405 /// * implicit conversions from array references to pointers 7406 /// * taking the address of fields 7407 /// * arbitrary interplay between "&" and "*" operators 7408 /// * pointer arithmetic from an address of a stack variable 7409 /// * taking the address of an array element where the array is on the stack 7410 static const Expr *EvalAddr(const Expr *E, 7411 SmallVectorImpl<const DeclRefExpr *> &refVars, 7412 const Decl *ParentDecl) { 7413 if (E->isTypeDependent()) 7414 return nullptr; 7415 7416 // We should only be called for evaluating pointer expressions. 7417 assert((E->getType()->isAnyPointerType() || 7418 E->getType()->isBlockPointerType() || 7419 E->getType()->isObjCQualifiedIdType()) && 7420 "EvalAddr only works on pointers"); 7421 7422 E = E->IgnoreParens(); 7423 7424 // Our "symbolic interpreter" is just a dispatch off the currently 7425 // viewed AST node. We then recursively traverse the AST by calling 7426 // EvalAddr and EvalVal appropriately. 7427 switch (E->getStmtClass()) { 7428 case Stmt::DeclRefExprClass: { 7429 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7430 7431 // If we leave the immediate function, the lifetime isn't about to end. 7432 if (DR->refersToEnclosingVariableOrCapture()) 7433 return nullptr; 7434 7435 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 7436 // If this is a reference variable, follow through to the expression that 7437 // it points to. 7438 if (V->hasLocalStorage() && 7439 V->getType()->isReferenceType() && V->hasInit()) { 7440 // Add the reference variable to the "trail". 7441 refVars.push_back(DR); 7442 return EvalAddr(V->getInit(), refVars, ParentDecl); 7443 } 7444 7445 return nullptr; 7446 } 7447 7448 case Stmt::UnaryOperatorClass: { 7449 // The only unary operator that make sense to handle here 7450 // is AddrOf. All others don't make sense as pointers. 7451 const UnaryOperator *U = cast<UnaryOperator>(E); 7452 7453 if (U->getOpcode() == UO_AddrOf) 7454 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 7455 return nullptr; 7456 } 7457 7458 case Stmt::BinaryOperatorClass: { 7459 // Handle pointer arithmetic. All other binary operators are not valid 7460 // in this context. 7461 const BinaryOperator *B = cast<BinaryOperator>(E); 7462 BinaryOperatorKind op = B->getOpcode(); 7463 7464 if (op != BO_Add && op != BO_Sub) 7465 return nullptr; 7466 7467 const Expr *Base = B->getLHS(); 7468 7469 // Determine which argument is the real pointer base. It could be 7470 // the RHS argument instead of the LHS. 7471 if (!Base->getType()->isPointerType()) 7472 Base = B->getRHS(); 7473 7474 assert(Base->getType()->isPointerType()); 7475 return EvalAddr(Base, refVars, ParentDecl); 7476 } 7477 7478 // For conditional operators we need to see if either the LHS or RHS are 7479 // valid DeclRefExpr*s. If one of them is valid, we return it. 7480 case Stmt::ConditionalOperatorClass: { 7481 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7482 7483 // Handle the GNU extension for missing LHS. 7484 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 7485 if (const Expr *LHSExpr = C->getLHS()) { 7486 // In C++, we can have a throw-expression, which has 'void' type. 7487 if (!LHSExpr->getType()->isVoidType()) 7488 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 7489 return LHS; 7490 } 7491 7492 // In C++, we can have a throw-expression, which has 'void' type. 7493 if (C->getRHS()->getType()->isVoidType()) 7494 return nullptr; 7495 7496 return EvalAddr(C->getRHS(), refVars, ParentDecl); 7497 } 7498 7499 case Stmt::BlockExprClass: 7500 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 7501 return E; // local block. 7502 return nullptr; 7503 7504 case Stmt::AddrLabelExprClass: 7505 return E; // address of label. 7506 7507 case Stmt::ExprWithCleanupsClass: 7508 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7509 ParentDecl); 7510 7511 // For casts, we need to handle conversions from arrays to 7512 // pointer values, and pointer-to-pointer conversions. 7513 case Stmt::ImplicitCastExprClass: 7514 case Stmt::CStyleCastExprClass: 7515 case Stmt::CXXFunctionalCastExprClass: 7516 case Stmt::ObjCBridgedCastExprClass: 7517 case Stmt::CXXStaticCastExprClass: 7518 case Stmt::CXXDynamicCastExprClass: 7519 case Stmt::CXXConstCastExprClass: 7520 case Stmt::CXXReinterpretCastExprClass: { 7521 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 7522 switch (cast<CastExpr>(E)->getCastKind()) { 7523 case CK_LValueToRValue: 7524 case CK_NoOp: 7525 case CK_BaseToDerived: 7526 case CK_DerivedToBase: 7527 case CK_UncheckedDerivedToBase: 7528 case CK_Dynamic: 7529 case CK_CPointerToObjCPointerCast: 7530 case CK_BlockPointerToObjCPointerCast: 7531 case CK_AnyPointerToBlockPointerCast: 7532 return EvalAddr(SubExpr, refVars, ParentDecl); 7533 7534 case CK_ArrayToPointerDecay: 7535 return EvalVal(SubExpr, refVars, ParentDecl); 7536 7537 case CK_BitCast: 7538 if (SubExpr->getType()->isAnyPointerType() || 7539 SubExpr->getType()->isBlockPointerType() || 7540 SubExpr->getType()->isObjCQualifiedIdType()) 7541 return EvalAddr(SubExpr, refVars, ParentDecl); 7542 else 7543 return nullptr; 7544 7545 default: 7546 return nullptr; 7547 } 7548 } 7549 7550 case Stmt::MaterializeTemporaryExprClass: 7551 if (const Expr *Result = 7552 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7553 refVars, ParentDecl)) 7554 return Result; 7555 return E; 7556 7557 // Everything else: we simply don't reason about them. 7558 default: 7559 return nullptr; 7560 } 7561 } 7562 7563 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 7564 /// See the comments for EvalAddr for more details. 7565 static const Expr *EvalVal(const Expr *E, 7566 SmallVectorImpl<const DeclRefExpr *> &refVars, 7567 const Decl *ParentDecl) { 7568 do { 7569 // We should only be called for evaluating non-pointer expressions, or 7570 // expressions with a pointer type that are not used as references but 7571 // instead 7572 // are l-values (e.g., DeclRefExpr with a pointer type). 7573 7574 // Our "symbolic interpreter" is just a dispatch off the currently 7575 // viewed AST node. We then recursively traverse the AST by calling 7576 // EvalAddr and EvalVal appropriately. 7577 7578 E = E->IgnoreParens(); 7579 switch (E->getStmtClass()) { 7580 case Stmt::ImplicitCastExprClass: { 7581 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 7582 if (IE->getValueKind() == VK_LValue) { 7583 E = IE->getSubExpr(); 7584 continue; 7585 } 7586 return nullptr; 7587 } 7588 7589 case Stmt::ExprWithCleanupsClass: 7590 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7591 ParentDecl); 7592 7593 case Stmt::DeclRefExprClass: { 7594 // When we hit a DeclRefExpr we are looking at code that refers to a 7595 // variable's name. If it's not a reference variable we check if it has 7596 // local storage within the function, and if so, return the expression. 7597 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7598 7599 // If we leave the immediate function, the lifetime isn't about to end. 7600 if (DR->refersToEnclosingVariableOrCapture()) 7601 return nullptr; 7602 7603 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 7604 // Check if it refers to itself, e.g. "int& i = i;". 7605 if (V == ParentDecl) 7606 return DR; 7607 7608 if (V->hasLocalStorage()) { 7609 if (!V->getType()->isReferenceType()) 7610 return DR; 7611 7612 // Reference variable, follow through to the expression that 7613 // it points to. 7614 if (V->hasInit()) { 7615 // Add the reference variable to the "trail". 7616 refVars.push_back(DR); 7617 return EvalVal(V->getInit(), refVars, V); 7618 } 7619 } 7620 } 7621 7622 return nullptr; 7623 } 7624 7625 case Stmt::UnaryOperatorClass: { 7626 // The only unary operator that make sense to handle here 7627 // is Deref. All others don't resolve to a "name." This includes 7628 // handling all sorts of rvalues passed to a unary operator. 7629 const UnaryOperator *U = cast<UnaryOperator>(E); 7630 7631 if (U->getOpcode() == UO_Deref) 7632 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 7633 7634 return nullptr; 7635 } 7636 7637 case Stmt::ArraySubscriptExprClass: { 7638 // Array subscripts are potential references to data on the stack. We 7639 // retrieve the DeclRefExpr* for the array variable if it indeed 7640 // has local storage. 7641 const auto *ASE = cast<ArraySubscriptExpr>(E); 7642 if (ASE->isTypeDependent()) 7643 return nullptr; 7644 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 7645 } 7646 7647 case Stmt::OMPArraySectionExprClass: { 7648 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 7649 ParentDecl); 7650 } 7651 7652 case Stmt::ConditionalOperatorClass: { 7653 // For conditional operators we need to see if either the LHS or RHS are 7654 // non-NULL Expr's. If one is non-NULL, we return it. 7655 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7656 7657 // Handle the GNU extension for missing LHS. 7658 if (const Expr *LHSExpr = C->getLHS()) { 7659 // In C++, we can have a throw-expression, which has 'void' type. 7660 if (!LHSExpr->getType()->isVoidType()) 7661 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 7662 return LHS; 7663 } 7664 7665 // In C++, we can have a throw-expression, which has 'void' type. 7666 if (C->getRHS()->getType()->isVoidType()) 7667 return nullptr; 7668 7669 return EvalVal(C->getRHS(), refVars, ParentDecl); 7670 } 7671 7672 // Accesses to members are potential references to data on the stack. 7673 case Stmt::MemberExprClass: { 7674 const MemberExpr *M = cast<MemberExpr>(E); 7675 7676 // Check for indirect access. We only want direct field accesses. 7677 if (M->isArrow()) 7678 return nullptr; 7679 7680 // Check whether the member type is itself a reference, in which case 7681 // we're not going to refer to the member, but to what the member refers 7682 // to. 7683 if (M->getMemberDecl()->getType()->isReferenceType()) 7684 return nullptr; 7685 7686 return EvalVal(M->getBase(), refVars, ParentDecl); 7687 } 7688 7689 case Stmt::MaterializeTemporaryExprClass: 7690 if (const Expr *Result = 7691 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7692 refVars, ParentDecl)) 7693 return Result; 7694 return E; 7695 7696 default: 7697 // Check that we don't return or take the address of a reference to a 7698 // temporary. This is only useful in C++. 7699 if (!E->isTypeDependent() && E->isRValue()) 7700 return E; 7701 7702 // Everything else: we simply don't reason about them. 7703 return nullptr; 7704 } 7705 } while (true); 7706 } 7707 7708 void 7709 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 7710 SourceLocation ReturnLoc, 7711 bool isObjCMethod, 7712 const AttrVec *Attrs, 7713 const FunctionDecl *FD) { 7714 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 7715 7716 // Check if the return value is null but should not be. 7717 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 7718 (!isObjCMethod && isNonNullType(Context, lhsType))) && 7719 CheckNonNullExpr(*this, RetValExp)) 7720 Diag(ReturnLoc, diag::warn_null_ret) 7721 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 7722 7723 // C++11 [basic.stc.dynamic.allocation]p4: 7724 // If an allocation function declared with a non-throwing 7725 // exception-specification fails to allocate storage, it shall return 7726 // a null pointer. Any other allocation function that fails to allocate 7727 // storage shall indicate failure only by throwing an exception [...] 7728 if (FD) { 7729 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 7730 if (Op == OO_New || Op == OO_Array_New) { 7731 const FunctionProtoType *Proto 7732 = FD->getType()->castAs<FunctionProtoType>(); 7733 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 7734 CheckNonNullExpr(*this, RetValExp)) 7735 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 7736 << FD << getLangOpts().CPlusPlus11; 7737 } 7738 } 7739 } 7740 7741 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 7742 7743 /// Check for comparisons of floating point operands using != and ==. 7744 /// Issue a warning if these are no self-comparisons, as they are not likely 7745 /// to do what the programmer intended. 7746 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 7747 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 7748 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 7749 7750 // Special case: check for x == x (which is OK). 7751 // Do not emit warnings for such cases. 7752 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 7753 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 7754 if (DRL->getDecl() == DRR->getDecl()) 7755 return; 7756 7757 // Special case: check for comparisons against literals that can be exactly 7758 // represented by APFloat. In such cases, do not emit a warning. This 7759 // is a heuristic: often comparison against such literals are used to 7760 // detect if a value in a variable has not changed. This clearly can 7761 // lead to false negatives. 7762 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 7763 if (FLL->isExact()) 7764 return; 7765 } else 7766 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 7767 if (FLR->isExact()) 7768 return; 7769 7770 // Check for comparisons with builtin types. 7771 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 7772 if (CL->getBuiltinCallee()) 7773 return; 7774 7775 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 7776 if (CR->getBuiltinCallee()) 7777 return; 7778 7779 // Emit the diagnostic. 7780 Diag(Loc, diag::warn_floatingpoint_eq) 7781 << LHS->getSourceRange() << RHS->getSourceRange(); 7782 } 7783 7784 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 7785 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 7786 7787 namespace { 7788 7789 /// Structure recording the 'active' range of an integer-valued 7790 /// expression. 7791 struct IntRange { 7792 /// The number of bits active in the int. 7793 unsigned Width; 7794 7795 /// True if the int is known not to have negative values. 7796 bool NonNegative; 7797 7798 IntRange(unsigned Width, bool NonNegative) 7799 : Width(Width), NonNegative(NonNegative) 7800 {} 7801 7802 /// Returns the range of the bool type. 7803 static IntRange forBoolType() { 7804 return IntRange(1, true); 7805 } 7806 7807 /// Returns the range of an opaque value of the given integral type. 7808 static IntRange forValueOfType(ASTContext &C, QualType T) { 7809 return forValueOfCanonicalType(C, 7810 T->getCanonicalTypeInternal().getTypePtr()); 7811 } 7812 7813 /// Returns the range of an opaque value of a canonical integral type. 7814 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 7815 assert(T->isCanonicalUnqualified()); 7816 7817 if (const VectorType *VT = dyn_cast<VectorType>(T)) 7818 T = VT->getElementType().getTypePtr(); 7819 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 7820 T = CT->getElementType().getTypePtr(); 7821 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 7822 T = AT->getValueType().getTypePtr(); 7823 7824 // For enum types, use the known bit width of the enumerators. 7825 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 7826 EnumDecl *Enum = ET->getDecl(); 7827 if (!Enum->isCompleteDefinition()) 7828 return IntRange(C.getIntWidth(QualType(T, 0)), false); 7829 7830 unsigned NumPositive = Enum->getNumPositiveBits(); 7831 unsigned NumNegative = Enum->getNumNegativeBits(); 7832 7833 if (NumNegative == 0) 7834 return IntRange(NumPositive, true/*NonNegative*/); 7835 else 7836 return IntRange(std::max(NumPositive + 1, NumNegative), 7837 false/*NonNegative*/); 7838 } 7839 7840 const BuiltinType *BT = cast<BuiltinType>(T); 7841 assert(BT->isInteger()); 7842 7843 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 7844 } 7845 7846 /// Returns the "target" range of a canonical integral type, i.e. 7847 /// the range of values expressible in the type. 7848 /// 7849 /// This matches forValueOfCanonicalType except that enums have the 7850 /// full range of their type, not the range of their enumerators. 7851 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 7852 assert(T->isCanonicalUnqualified()); 7853 7854 if (const VectorType *VT = dyn_cast<VectorType>(T)) 7855 T = VT->getElementType().getTypePtr(); 7856 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 7857 T = CT->getElementType().getTypePtr(); 7858 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 7859 T = AT->getValueType().getTypePtr(); 7860 if (const EnumType *ET = dyn_cast<EnumType>(T)) 7861 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 7862 7863 const BuiltinType *BT = cast<BuiltinType>(T); 7864 assert(BT->isInteger()); 7865 7866 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 7867 } 7868 7869 /// Returns the supremum of two ranges: i.e. their conservative merge. 7870 static IntRange join(IntRange L, IntRange R) { 7871 return IntRange(std::max(L.Width, R.Width), 7872 L.NonNegative && R.NonNegative); 7873 } 7874 7875 /// Returns the infinum of two ranges: i.e. their aggressive merge. 7876 static IntRange meet(IntRange L, IntRange R) { 7877 return IntRange(std::min(L.Width, R.Width), 7878 L.NonNegative || R.NonNegative); 7879 } 7880 }; 7881 7882 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 7883 if (value.isSigned() && value.isNegative()) 7884 return IntRange(value.getMinSignedBits(), false); 7885 7886 if (value.getBitWidth() > MaxWidth) 7887 value = value.trunc(MaxWidth); 7888 7889 // isNonNegative() just checks the sign bit without considering 7890 // signedness. 7891 return IntRange(value.getActiveBits(), true); 7892 } 7893 7894 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 7895 unsigned MaxWidth) { 7896 if (result.isInt()) 7897 return GetValueRange(C, result.getInt(), MaxWidth); 7898 7899 if (result.isVector()) { 7900 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 7901 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 7902 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 7903 R = IntRange::join(R, El); 7904 } 7905 return R; 7906 } 7907 7908 if (result.isComplexInt()) { 7909 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 7910 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 7911 return IntRange::join(R, I); 7912 } 7913 7914 // This can happen with lossless casts to intptr_t of "based" lvalues. 7915 // Assume it might use arbitrary bits. 7916 // FIXME: The only reason we need to pass the type in here is to get 7917 // the sign right on this one case. It would be nice if APValue 7918 // preserved this. 7919 assert(result.isLValue() || result.isAddrLabelDiff()); 7920 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 7921 } 7922 7923 QualType GetExprType(const Expr *E) { 7924 QualType Ty = E->getType(); 7925 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 7926 Ty = AtomicRHS->getValueType(); 7927 return Ty; 7928 } 7929 7930 /// Pseudo-evaluate the given integer expression, estimating the 7931 /// range of values it might take. 7932 /// 7933 /// \param MaxWidth - the width to which the value will be truncated 7934 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 7935 E = E->IgnoreParens(); 7936 7937 // Try a full evaluation first. 7938 Expr::EvalResult result; 7939 if (E->EvaluateAsRValue(result, C)) 7940 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 7941 7942 // I think we only want to look through implicit casts here; if the 7943 // user has an explicit widening cast, we should treat the value as 7944 // being of the new, wider type. 7945 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 7946 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 7947 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 7948 7949 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 7950 7951 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 7952 CE->getCastKind() == CK_BooleanToSignedIntegral; 7953 7954 // Assume that non-integer casts can span the full range of the type. 7955 if (!isIntegerCast) 7956 return OutputTypeRange; 7957 7958 IntRange SubRange 7959 = GetExprRange(C, CE->getSubExpr(), 7960 std::min(MaxWidth, OutputTypeRange.Width)); 7961 7962 // Bail out if the subexpr's range is as wide as the cast type. 7963 if (SubRange.Width >= OutputTypeRange.Width) 7964 return OutputTypeRange; 7965 7966 // Otherwise, we take the smaller width, and we're non-negative if 7967 // either the output type or the subexpr is. 7968 return IntRange(SubRange.Width, 7969 SubRange.NonNegative || OutputTypeRange.NonNegative); 7970 } 7971 7972 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 7973 // If we can fold the condition, just take that operand. 7974 bool CondResult; 7975 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 7976 return GetExprRange(C, CondResult ? CO->getTrueExpr() 7977 : CO->getFalseExpr(), 7978 MaxWidth); 7979 7980 // Otherwise, conservatively merge. 7981 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 7982 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 7983 return IntRange::join(L, R); 7984 } 7985 7986 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 7987 switch (BO->getOpcode()) { 7988 7989 // Boolean-valued operations are single-bit and positive. 7990 case BO_LAnd: 7991 case BO_LOr: 7992 case BO_LT: 7993 case BO_GT: 7994 case BO_LE: 7995 case BO_GE: 7996 case BO_EQ: 7997 case BO_NE: 7998 return IntRange::forBoolType(); 7999 8000 // The type of the assignments is the type of the LHS, so the RHS 8001 // is not necessarily the same type. 8002 case BO_MulAssign: 8003 case BO_DivAssign: 8004 case BO_RemAssign: 8005 case BO_AddAssign: 8006 case BO_SubAssign: 8007 case BO_XorAssign: 8008 case BO_OrAssign: 8009 // TODO: bitfields? 8010 return IntRange::forValueOfType(C, GetExprType(E)); 8011 8012 // Simple assignments just pass through the RHS, which will have 8013 // been coerced to the LHS type. 8014 case BO_Assign: 8015 // TODO: bitfields? 8016 return GetExprRange(C, BO->getRHS(), MaxWidth); 8017 8018 // Operations with opaque sources are black-listed. 8019 case BO_PtrMemD: 8020 case BO_PtrMemI: 8021 return IntRange::forValueOfType(C, GetExprType(E)); 8022 8023 // Bitwise-and uses the *infinum* of the two source ranges. 8024 case BO_And: 8025 case BO_AndAssign: 8026 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 8027 GetExprRange(C, BO->getRHS(), MaxWidth)); 8028 8029 // Left shift gets black-listed based on a judgement call. 8030 case BO_Shl: 8031 // ...except that we want to treat '1 << (blah)' as logically 8032 // positive. It's an important idiom. 8033 if (IntegerLiteral *I 8034 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 8035 if (I->getValue() == 1) { 8036 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 8037 return IntRange(R.Width, /*NonNegative*/ true); 8038 } 8039 } 8040 // fallthrough 8041 8042 case BO_ShlAssign: 8043 return IntRange::forValueOfType(C, GetExprType(E)); 8044 8045 // Right shift by a constant can narrow its left argument. 8046 case BO_Shr: 8047 case BO_ShrAssign: { 8048 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8049 8050 // If the shift amount is a positive constant, drop the width by 8051 // that much. 8052 llvm::APSInt shift; 8053 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 8054 shift.isNonNegative()) { 8055 unsigned zext = shift.getZExtValue(); 8056 if (zext >= L.Width) 8057 L.Width = (L.NonNegative ? 0 : 1); 8058 else 8059 L.Width -= zext; 8060 } 8061 8062 return L; 8063 } 8064 8065 // Comma acts as its right operand. 8066 case BO_Comma: 8067 return GetExprRange(C, BO->getRHS(), MaxWidth); 8068 8069 // Black-list pointer subtractions. 8070 case BO_Sub: 8071 if (BO->getLHS()->getType()->isPointerType()) 8072 return IntRange::forValueOfType(C, GetExprType(E)); 8073 break; 8074 8075 // The width of a division result is mostly determined by the size 8076 // of the LHS. 8077 case BO_Div: { 8078 // Don't 'pre-truncate' the operands. 8079 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8080 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8081 8082 // If the divisor is constant, use that. 8083 llvm::APSInt divisor; 8084 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 8085 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 8086 if (log2 >= L.Width) 8087 L.Width = (L.NonNegative ? 0 : 1); 8088 else 8089 L.Width = std::min(L.Width - log2, MaxWidth); 8090 return L; 8091 } 8092 8093 // Otherwise, just use the LHS's width. 8094 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8095 return IntRange(L.Width, L.NonNegative && R.NonNegative); 8096 } 8097 8098 // The result of a remainder can't be larger than the result of 8099 // either side. 8100 case BO_Rem: { 8101 // Don't 'pre-truncate' the operands. 8102 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8103 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8104 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8105 8106 IntRange meet = IntRange::meet(L, R); 8107 meet.Width = std::min(meet.Width, MaxWidth); 8108 return meet; 8109 } 8110 8111 // The default behavior is okay for these. 8112 case BO_Mul: 8113 case BO_Add: 8114 case BO_Xor: 8115 case BO_Or: 8116 break; 8117 } 8118 8119 // The default case is to treat the operation as if it were closed 8120 // on the narrowest type that encompasses both operands. 8121 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8122 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 8123 return IntRange::join(L, R); 8124 } 8125 8126 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 8127 switch (UO->getOpcode()) { 8128 // Boolean-valued operations are white-listed. 8129 case UO_LNot: 8130 return IntRange::forBoolType(); 8131 8132 // Operations with opaque sources are black-listed. 8133 case UO_Deref: 8134 case UO_AddrOf: // should be impossible 8135 return IntRange::forValueOfType(C, GetExprType(E)); 8136 8137 default: 8138 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 8139 } 8140 } 8141 8142 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 8143 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 8144 8145 if (const auto *BitField = E->getSourceBitField()) 8146 return IntRange(BitField->getBitWidthValue(C), 8147 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 8148 8149 return IntRange::forValueOfType(C, GetExprType(E)); 8150 } 8151 8152 IntRange GetExprRange(ASTContext &C, const Expr *E) { 8153 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 8154 } 8155 8156 /// Checks whether the given value, which currently has the given 8157 /// source semantics, has the same value when coerced through the 8158 /// target semantics. 8159 bool IsSameFloatAfterCast(const llvm::APFloat &value, 8160 const llvm::fltSemantics &Src, 8161 const llvm::fltSemantics &Tgt) { 8162 llvm::APFloat truncated = value; 8163 8164 bool ignored; 8165 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 8166 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 8167 8168 return truncated.bitwiseIsEqual(value); 8169 } 8170 8171 /// Checks whether the given value, which currently has the given 8172 /// source semantics, has the same value when coerced through the 8173 /// target semantics. 8174 /// 8175 /// The value might be a vector of floats (or a complex number). 8176 bool IsSameFloatAfterCast(const APValue &value, 8177 const llvm::fltSemantics &Src, 8178 const llvm::fltSemantics &Tgt) { 8179 if (value.isFloat()) 8180 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 8181 8182 if (value.isVector()) { 8183 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 8184 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 8185 return false; 8186 return true; 8187 } 8188 8189 assert(value.isComplexFloat()); 8190 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 8191 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 8192 } 8193 8194 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 8195 8196 bool IsZero(Sema &S, Expr *E) { 8197 // Suppress cases where we are comparing against an enum constant. 8198 if (const DeclRefExpr *DR = 8199 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 8200 if (isa<EnumConstantDecl>(DR->getDecl())) 8201 return false; 8202 8203 // Suppress cases where the '0' value is expanded from a macro. 8204 if (E->getLocStart().isMacroID()) 8205 return false; 8206 8207 llvm::APSInt Value; 8208 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 8209 } 8210 8211 bool HasEnumType(Expr *E) { 8212 // Strip off implicit integral promotions. 8213 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8214 if (ICE->getCastKind() != CK_IntegralCast && 8215 ICE->getCastKind() != CK_NoOp) 8216 break; 8217 E = ICE->getSubExpr(); 8218 } 8219 8220 return E->getType()->isEnumeralType(); 8221 } 8222 8223 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 8224 // Disable warning in template instantiations. 8225 if (!S.ActiveTemplateInstantiations.empty()) 8226 return; 8227 8228 BinaryOperatorKind op = E->getOpcode(); 8229 if (E->isValueDependent()) 8230 return; 8231 8232 if (op == BO_LT && IsZero(S, E->getRHS())) { 8233 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8234 << "< 0" << "false" << HasEnumType(E->getLHS()) 8235 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8236 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 8237 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8238 << ">= 0" << "true" << HasEnumType(E->getLHS()) 8239 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8240 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 8241 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8242 << "0 >" << "false" << HasEnumType(E->getRHS()) 8243 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8244 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 8245 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8246 << "0 <=" << "true" << HasEnumType(E->getRHS()) 8247 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8248 } 8249 } 8250 8251 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant, 8252 Expr *Other, const llvm::APSInt &Value, 8253 bool RhsConstant) { 8254 // Disable warning in template instantiations. 8255 if (!S.ActiveTemplateInstantiations.empty()) 8256 return; 8257 8258 // TODO: Investigate using GetExprRange() to get tighter bounds 8259 // on the bit ranges. 8260 QualType OtherT = Other->getType(); 8261 if (const auto *AT = OtherT->getAs<AtomicType>()) 8262 OtherT = AT->getValueType(); 8263 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 8264 unsigned OtherWidth = OtherRange.Width; 8265 8266 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 8267 8268 // 0 values are handled later by CheckTrivialUnsignedComparison(). 8269 if ((Value == 0) && (!OtherIsBooleanType)) 8270 return; 8271 8272 BinaryOperatorKind op = E->getOpcode(); 8273 bool IsTrue = true; 8274 8275 // Used for diagnostic printout. 8276 enum { 8277 LiteralConstant = 0, 8278 CXXBoolLiteralTrue, 8279 CXXBoolLiteralFalse 8280 } LiteralOrBoolConstant = LiteralConstant; 8281 8282 if (!OtherIsBooleanType) { 8283 QualType ConstantT = Constant->getType(); 8284 QualType CommonT = E->getLHS()->getType(); 8285 8286 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 8287 return; 8288 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 8289 "comparison with non-integer type"); 8290 8291 bool ConstantSigned = ConstantT->isSignedIntegerType(); 8292 bool CommonSigned = CommonT->isSignedIntegerType(); 8293 8294 bool EqualityOnly = false; 8295 8296 if (CommonSigned) { 8297 // The common type is signed, therefore no signed to unsigned conversion. 8298 if (!OtherRange.NonNegative) { 8299 // Check that the constant is representable in type OtherT. 8300 if (ConstantSigned) { 8301 if (OtherWidth >= Value.getMinSignedBits()) 8302 return; 8303 } else { // !ConstantSigned 8304 if (OtherWidth >= Value.getActiveBits() + 1) 8305 return; 8306 } 8307 } else { // !OtherSigned 8308 // Check that the constant is representable in type OtherT. 8309 // Negative values are out of range. 8310 if (ConstantSigned) { 8311 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 8312 return; 8313 } else { // !ConstantSigned 8314 if (OtherWidth >= Value.getActiveBits()) 8315 return; 8316 } 8317 } 8318 } else { // !CommonSigned 8319 if (OtherRange.NonNegative) { 8320 if (OtherWidth >= Value.getActiveBits()) 8321 return; 8322 } else { // OtherSigned 8323 assert(!ConstantSigned && 8324 "Two signed types converted to unsigned types."); 8325 // Check to see if the constant is representable in OtherT. 8326 if (OtherWidth > Value.getActiveBits()) 8327 return; 8328 // Check to see if the constant is equivalent to a negative value 8329 // cast to CommonT. 8330 if (S.Context.getIntWidth(ConstantT) == 8331 S.Context.getIntWidth(CommonT) && 8332 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 8333 return; 8334 // The constant value rests between values that OtherT can represent 8335 // after conversion. Relational comparison still works, but equality 8336 // comparisons will be tautological. 8337 EqualityOnly = true; 8338 } 8339 } 8340 8341 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 8342 8343 if (op == BO_EQ || op == BO_NE) { 8344 IsTrue = op == BO_NE; 8345 } else if (EqualityOnly) { 8346 return; 8347 } else if (RhsConstant) { 8348 if (op == BO_GT || op == BO_GE) 8349 IsTrue = !PositiveConstant; 8350 else // op == BO_LT || op == BO_LE 8351 IsTrue = PositiveConstant; 8352 } else { 8353 if (op == BO_LT || op == BO_LE) 8354 IsTrue = !PositiveConstant; 8355 else // op == BO_GT || op == BO_GE 8356 IsTrue = PositiveConstant; 8357 } 8358 } else { 8359 // Other isKnownToHaveBooleanValue 8360 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 8361 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 8362 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 8363 8364 static const struct LinkedConditions { 8365 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 8366 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 8367 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 8368 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 8369 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 8370 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 8371 8372 } TruthTable = { 8373 // Constant on LHS. | Constant on RHS. | 8374 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 8375 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 8376 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 8377 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 8378 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 8379 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 8380 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 8381 }; 8382 8383 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 8384 8385 enum ConstantValue ConstVal = Zero; 8386 if (Value.isUnsigned() || Value.isNonNegative()) { 8387 if (Value == 0) { 8388 LiteralOrBoolConstant = 8389 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 8390 ConstVal = Zero; 8391 } else if (Value == 1) { 8392 LiteralOrBoolConstant = 8393 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 8394 ConstVal = One; 8395 } else { 8396 LiteralOrBoolConstant = LiteralConstant; 8397 ConstVal = GT_One; 8398 } 8399 } else { 8400 ConstVal = LT_Zero; 8401 } 8402 8403 CompareBoolWithConstantResult CmpRes; 8404 8405 switch (op) { 8406 case BO_LT: 8407 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 8408 break; 8409 case BO_GT: 8410 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 8411 break; 8412 case BO_LE: 8413 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 8414 break; 8415 case BO_GE: 8416 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 8417 break; 8418 case BO_EQ: 8419 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 8420 break; 8421 case BO_NE: 8422 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 8423 break; 8424 default: 8425 CmpRes = Unkwn; 8426 break; 8427 } 8428 8429 if (CmpRes == AFals) { 8430 IsTrue = false; 8431 } else if (CmpRes == ATrue) { 8432 IsTrue = true; 8433 } else { 8434 return; 8435 } 8436 } 8437 8438 // If this is a comparison to an enum constant, include that 8439 // constant in the diagnostic. 8440 const EnumConstantDecl *ED = nullptr; 8441 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 8442 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 8443 8444 SmallString<64> PrettySourceValue; 8445 llvm::raw_svector_ostream OS(PrettySourceValue); 8446 if (ED) 8447 OS << '\'' << *ED << "' (" << Value << ")"; 8448 else 8449 OS << Value; 8450 8451 S.DiagRuntimeBehavior( 8452 E->getOperatorLoc(), E, 8453 S.PDiag(diag::warn_out_of_range_compare) 8454 << OS.str() << LiteralOrBoolConstant 8455 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 8456 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 8457 } 8458 8459 /// Analyze the operands of the given comparison. Implements the 8460 /// fallback case from AnalyzeComparison. 8461 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 8462 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8463 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8464 } 8465 8466 /// \brief Implements -Wsign-compare. 8467 /// 8468 /// \param E the binary operator to check for warnings 8469 void AnalyzeComparison(Sema &S, BinaryOperator *E) { 8470 // The type the comparison is being performed in. 8471 QualType T = E->getLHS()->getType(); 8472 8473 // Only analyze comparison operators where both sides have been converted to 8474 // the same type. 8475 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 8476 return AnalyzeImpConvsInComparison(S, E); 8477 8478 // Don't analyze value-dependent comparisons directly. 8479 if (E->isValueDependent()) 8480 return AnalyzeImpConvsInComparison(S, E); 8481 8482 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 8483 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 8484 8485 bool IsComparisonConstant = false; 8486 8487 // Check whether an integer constant comparison results in a value 8488 // of 'true' or 'false'. 8489 if (T->isIntegralType(S.Context)) { 8490 llvm::APSInt RHSValue; 8491 bool IsRHSIntegralLiteral = 8492 RHS->isIntegerConstantExpr(RHSValue, S.Context); 8493 llvm::APSInt LHSValue; 8494 bool IsLHSIntegralLiteral = 8495 LHS->isIntegerConstantExpr(LHSValue, S.Context); 8496 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 8497 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 8498 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 8499 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 8500 else 8501 IsComparisonConstant = 8502 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 8503 } else if (!T->hasUnsignedIntegerRepresentation()) 8504 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 8505 8506 // We don't do anything special if this isn't an unsigned integral 8507 // comparison: we're only interested in integral comparisons, and 8508 // signed comparisons only happen in cases we don't care to warn about. 8509 // 8510 // We also don't care about value-dependent expressions or expressions 8511 // whose result is a constant. 8512 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 8513 return AnalyzeImpConvsInComparison(S, E); 8514 8515 // Check to see if one of the (unmodified) operands is of different 8516 // signedness. 8517 Expr *signedOperand, *unsignedOperand; 8518 if (LHS->getType()->hasSignedIntegerRepresentation()) { 8519 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 8520 "unsigned comparison between two signed integer expressions?"); 8521 signedOperand = LHS; 8522 unsignedOperand = RHS; 8523 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 8524 signedOperand = RHS; 8525 unsignedOperand = LHS; 8526 } else { 8527 CheckTrivialUnsignedComparison(S, E); 8528 return AnalyzeImpConvsInComparison(S, E); 8529 } 8530 8531 // Otherwise, calculate the effective range of the signed operand. 8532 IntRange signedRange = GetExprRange(S.Context, signedOperand); 8533 8534 // Go ahead and analyze implicit conversions in the operands. Note 8535 // that we skip the implicit conversions on both sides. 8536 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 8537 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 8538 8539 // If the signed range is non-negative, -Wsign-compare won't fire, 8540 // but we should still check for comparisons which are always true 8541 // or false. 8542 if (signedRange.NonNegative) 8543 return CheckTrivialUnsignedComparison(S, E); 8544 8545 // For (in)equality comparisons, if the unsigned operand is a 8546 // constant which cannot collide with a overflowed signed operand, 8547 // then reinterpreting the signed operand as unsigned will not 8548 // change the result of the comparison. 8549 if (E->isEqualityOp()) { 8550 unsigned comparisonWidth = S.Context.getIntWidth(T); 8551 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 8552 8553 // We should never be unable to prove that the unsigned operand is 8554 // non-negative. 8555 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 8556 8557 if (unsignedRange.Width < comparisonWidth) 8558 return; 8559 } 8560 8561 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 8562 S.PDiag(diag::warn_mixed_sign_comparison) 8563 << LHS->getType() << RHS->getType() 8564 << LHS->getSourceRange() << RHS->getSourceRange()); 8565 } 8566 8567 /// Analyzes an attempt to assign the given value to a bitfield. 8568 /// 8569 /// Returns true if there was something fishy about the attempt. 8570 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 8571 SourceLocation InitLoc) { 8572 assert(Bitfield->isBitField()); 8573 if (Bitfield->isInvalidDecl()) 8574 return false; 8575 8576 // White-list bool bitfields. 8577 QualType BitfieldType = Bitfield->getType(); 8578 if (BitfieldType->isBooleanType()) 8579 return false; 8580 8581 if (BitfieldType->isEnumeralType()) { 8582 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 8583 // If the underlying enum type was not explicitly specified as an unsigned 8584 // type and the enum contain only positive values, MSVC++ will cause an 8585 // inconsistency by storing this as a signed type. 8586 if (S.getLangOpts().CPlusPlus11 && 8587 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 8588 BitfieldEnumDecl->getNumPositiveBits() > 0 && 8589 BitfieldEnumDecl->getNumNegativeBits() == 0) { 8590 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 8591 << BitfieldEnumDecl->getNameAsString(); 8592 } 8593 } 8594 8595 if (Bitfield->getType()->isBooleanType()) 8596 return false; 8597 8598 // Ignore value- or type-dependent expressions. 8599 if (Bitfield->getBitWidth()->isValueDependent() || 8600 Bitfield->getBitWidth()->isTypeDependent() || 8601 Init->isValueDependent() || 8602 Init->isTypeDependent()) 8603 return false; 8604 8605 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 8606 8607 llvm::APSInt Value; 8608 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 8609 return false; 8610 8611 unsigned OriginalWidth = Value.getBitWidth(); 8612 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 8613 8614 if (!Value.isSigned() || Value.isNegative()) 8615 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 8616 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 8617 OriginalWidth = Value.getMinSignedBits(); 8618 8619 if (OriginalWidth <= FieldWidth) 8620 return false; 8621 8622 // Compute the value which the bitfield will contain. 8623 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 8624 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 8625 8626 // Check whether the stored value is equal to the original value. 8627 TruncatedValue = TruncatedValue.extend(OriginalWidth); 8628 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 8629 return false; 8630 8631 // Special-case bitfields of width 1: booleans are naturally 0/1, and 8632 // therefore don't strictly fit into a signed bitfield of width 1. 8633 if (FieldWidth == 1 && Value == 1) 8634 return false; 8635 8636 std::string PrettyValue = Value.toString(10); 8637 std::string PrettyTrunc = TruncatedValue.toString(10); 8638 8639 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 8640 << PrettyValue << PrettyTrunc << OriginalInit->getType() 8641 << Init->getSourceRange(); 8642 8643 return true; 8644 } 8645 8646 /// Analyze the given simple or compound assignment for warning-worthy 8647 /// operations. 8648 void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 8649 // Just recurse on the LHS. 8650 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8651 8652 // We want to recurse on the RHS as normal unless we're assigning to 8653 // a bitfield. 8654 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 8655 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 8656 E->getOperatorLoc())) { 8657 // Recurse, ignoring any implicit conversions on the RHS. 8658 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 8659 E->getOperatorLoc()); 8660 } 8661 } 8662 8663 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8664 } 8665 8666 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 8667 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 8668 SourceLocation CContext, unsigned diag, 8669 bool pruneControlFlow = false) { 8670 if (pruneControlFlow) { 8671 S.DiagRuntimeBehavior(E->getExprLoc(), E, 8672 S.PDiag(diag) 8673 << SourceType << T << E->getSourceRange() 8674 << SourceRange(CContext)); 8675 return; 8676 } 8677 S.Diag(E->getExprLoc(), diag) 8678 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 8679 } 8680 8681 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 8682 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 8683 unsigned diag, bool pruneControlFlow = false) { 8684 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 8685 } 8686 8687 8688 /// Diagnose an implicit cast from a floating point value to an integer value. 8689 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 8690 8691 SourceLocation CContext) { 8692 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 8693 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty(); 8694 8695 Expr *InnerE = E->IgnoreParenImpCasts(); 8696 // We also want to warn on, e.g., "int i = -1.234" 8697 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 8698 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 8699 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 8700 8701 const bool IsLiteral = 8702 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 8703 8704 llvm::APFloat Value(0.0); 8705 bool IsConstant = 8706 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 8707 if (!IsConstant) { 8708 return DiagnoseImpCast(S, E, T, CContext, 8709 diag::warn_impcast_float_integer, PruneWarnings); 8710 } 8711 8712 bool isExact = false; 8713 8714 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 8715 T->hasUnsignedIntegerRepresentation()); 8716 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 8717 &isExact) == llvm::APFloat::opOK && 8718 isExact) { 8719 if (IsLiteral) return; 8720 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 8721 PruneWarnings); 8722 } 8723 8724 unsigned DiagID = 0; 8725 if (IsLiteral) { 8726 // Warn on floating point literal to integer. 8727 DiagID = diag::warn_impcast_literal_float_to_integer; 8728 } else if (IntegerValue == 0) { 8729 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 8730 return DiagnoseImpCast(S, E, T, CContext, 8731 diag::warn_impcast_float_integer, PruneWarnings); 8732 } 8733 // Warn on non-zero to zero conversion. 8734 DiagID = diag::warn_impcast_float_to_integer_zero; 8735 } else { 8736 if (IntegerValue.isUnsigned()) { 8737 if (!IntegerValue.isMaxValue()) { 8738 return DiagnoseImpCast(S, E, T, CContext, 8739 diag::warn_impcast_float_integer, PruneWarnings); 8740 } 8741 } else { // IntegerValue.isSigned() 8742 if (!IntegerValue.isMaxSignedValue() && 8743 !IntegerValue.isMinSignedValue()) { 8744 return DiagnoseImpCast(S, E, T, CContext, 8745 diag::warn_impcast_float_integer, PruneWarnings); 8746 } 8747 } 8748 // Warn on evaluatable floating point expression to integer conversion. 8749 DiagID = diag::warn_impcast_float_to_integer; 8750 } 8751 8752 // FIXME: Force the precision of the source value down so we don't print 8753 // digits which are usually useless (we don't really care here if we 8754 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 8755 // would automatically print the shortest representation, but it's a bit 8756 // tricky to implement. 8757 SmallString<16> PrettySourceValue; 8758 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 8759 precision = (precision * 59 + 195) / 196; 8760 Value.toString(PrettySourceValue, precision); 8761 8762 SmallString<16> PrettyTargetValue; 8763 if (IsBool) 8764 PrettyTargetValue = Value.isZero() ? "false" : "true"; 8765 else 8766 IntegerValue.toString(PrettyTargetValue); 8767 8768 if (PruneWarnings) { 8769 S.DiagRuntimeBehavior(E->getExprLoc(), E, 8770 S.PDiag(DiagID) 8771 << E->getType() << T.getUnqualifiedType() 8772 << PrettySourceValue << PrettyTargetValue 8773 << E->getSourceRange() << SourceRange(CContext)); 8774 } else { 8775 S.Diag(E->getExprLoc(), DiagID) 8776 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 8777 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 8778 } 8779 } 8780 8781 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 8782 if (!Range.Width) return "0"; 8783 8784 llvm::APSInt ValueInRange = Value; 8785 ValueInRange.setIsSigned(!Range.NonNegative); 8786 ValueInRange = ValueInRange.trunc(Range.Width); 8787 return ValueInRange.toString(10); 8788 } 8789 8790 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 8791 if (!isa<ImplicitCastExpr>(Ex)) 8792 return false; 8793 8794 Expr *InnerE = Ex->IgnoreParenImpCasts(); 8795 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 8796 const Type *Source = 8797 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 8798 if (Target->isDependentType()) 8799 return false; 8800 8801 const BuiltinType *FloatCandidateBT = 8802 dyn_cast<BuiltinType>(ToBool ? Source : Target); 8803 const Type *BoolCandidateType = ToBool ? Target : Source; 8804 8805 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 8806 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 8807 } 8808 8809 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 8810 SourceLocation CC) { 8811 unsigned NumArgs = TheCall->getNumArgs(); 8812 for (unsigned i = 0; i < NumArgs; ++i) { 8813 Expr *CurrA = TheCall->getArg(i); 8814 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 8815 continue; 8816 8817 bool IsSwapped = ((i > 0) && 8818 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 8819 IsSwapped |= ((i < (NumArgs - 1)) && 8820 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 8821 if (IsSwapped) { 8822 // Warn on this floating-point to bool conversion. 8823 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 8824 CurrA->getType(), CC, 8825 diag::warn_impcast_floating_point_to_bool); 8826 } 8827 } 8828 } 8829 8830 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) { 8831 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 8832 E->getExprLoc())) 8833 return; 8834 8835 // Don't warn on functions which have return type nullptr_t. 8836 if (isa<CallExpr>(E)) 8837 return; 8838 8839 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 8840 const Expr::NullPointerConstantKind NullKind = 8841 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 8842 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 8843 return; 8844 8845 // Return if target type is a safe conversion. 8846 if (T->isAnyPointerType() || T->isBlockPointerType() || 8847 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 8848 return; 8849 8850 SourceLocation Loc = E->getSourceRange().getBegin(); 8851 8852 // Venture through the macro stacks to get to the source of macro arguments. 8853 // The new location is a better location than the complete location that was 8854 // passed in. 8855 while (S.SourceMgr.isMacroArgExpansion(Loc)) 8856 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); 8857 8858 while (S.SourceMgr.isMacroArgExpansion(CC)) 8859 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); 8860 8861 // __null is usually wrapped in a macro. Go up a macro if that is the case. 8862 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 8863 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 8864 Loc, S.SourceMgr, S.getLangOpts()); 8865 if (MacroName == "NULL") 8866 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 8867 } 8868 8869 // Only warn if the null and context location are in the same macro expansion. 8870 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 8871 return; 8872 8873 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 8874 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) 8875 << FixItHint::CreateReplacement(Loc, 8876 S.getFixItZeroLiteralForType(T, Loc)); 8877 } 8878 8879 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 8880 ObjCArrayLiteral *ArrayLiteral); 8881 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 8882 ObjCDictionaryLiteral *DictionaryLiteral); 8883 8884 /// Check a single element within a collection literal against the 8885 /// target element type. 8886 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, 8887 Expr *Element, unsigned ElementKind) { 8888 // Skip a bitcast to 'id' or qualified 'id'. 8889 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 8890 if (ICE->getCastKind() == CK_BitCast && 8891 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 8892 Element = ICE->getSubExpr(); 8893 } 8894 8895 QualType ElementType = Element->getType(); 8896 ExprResult ElementResult(Element); 8897 if (ElementType->getAs<ObjCObjectPointerType>() && 8898 S.CheckSingleAssignmentConstraints(TargetElementType, 8899 ElementResult, 8900 false, false) 8901 != Sema::Compatible) { 8902 S.Diag(Element->getLocStart(), 8903 diag::warn_objc_collection_literal_element) 8904 << ElementType << ElementKind << TargetElementType 8905 << Element->getSourceRange(); 8906 } 8907 8908 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 8909 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 8910 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 8911 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 8912 } 8913 8914 /// Check an Objective-C array literal being converted to the given 8915 /// target type. 8916 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 8917 ObjCArrayLiteral *ArrayLiteral) { 8918 if (!S.NSArrayDecl) 8919 return; 8920 8921 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 8922 if (!TargetObjCPtr) 8923 return; 8924 8925 if (TargetObjCPtr->isUnspecialized() || 8926 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 8927 != S.NSArrayDecl->getCanonicalDecl()) 8928 return; 8929 8930 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 8931 if (TypeArgs.size() != 1) 8932 return; 8933 8934 QualType TargetElementType = TypeArgs[0]; 8935 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 8936 checkObjCCollectionLiteralElement(S, TargetElementType, 8937 ArrayLiteral->getElement(I), 8938 0); 8939 } 8940 } 8941 8942 /// Check an Objective-C dictionary literal being converted to the given 8943 /// target type. 8944 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 8945 ObjCDictionaryLiteral *DictionaryLiteral) { 8946 if (!S.NSDictionaryDecl) 8947 return; 8948 8949 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 8950 if (!TargetObjCPtr) 8951 return; 8952 8953 if (TargetObjCPtr->isUnspecialized() || 8954 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 8955 != S.NSDictionaryDecl->getCanonicalDecl()) 8956 return; 8957 8958 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 8959 if (TypeArgs.size() != 2) 8960 return; 8961 8962 QualType TargetKeyType = TypeArgs[0]; 8963 QualType TargetObjectType = TypeArgs[1]; 8964 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 8965 auto Element = DictionaryLiteral->getKeyValueElement(I); 8966 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 8967 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 8968 } 8969 } 8970 8971 // Helper function to filter out cases for constant width constant conversion. 8972 // Don't warn on char array initialization or for non-decimal values. 8973 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 8974 SourceLocation CC) { 8975 // If initializing from a constant, and the constant starts with '0', 8976 // then it is a binary, octal, or hexadecimal. Allow these constants 8977 // to fill all the bits, even if there is a sign change. 8978 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 8979 const char FirstLiteralCharacter = 8980 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 8981 if (FirstLiteralCharacter == '0') 8982 return false; 8983 } 8984 8985 // If the CC location points to a '{', and the type is char, then assume 8986 // assume it is an array initialization. 8987 if (CC.isValid() && T->isCharType()) { 8988 const char FirstContextCharacter = 8989 S.getSourceManager().getCharacterData(CC)[0]; 8990 if (FirstContextCharacter == '{') 8991 return false; 8992 } 8993 8994 return true; 8995 } 8996 8997 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 8998 SourceLocation CC, bool *ICContext = nullptr) { 8999 if (E->isTypeDependent() || E->isValueDependent()) return; 9000 9001 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 9002 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 9003 if (Source == Target) return; 9004 if (Target->isDependentType()) return; 9005 9006 // If the conversion context location is invalid don't complain. We also 9007 // don't want to emit a warning if the issue occurs from the expansion of 9008 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 9009 // delay this check as long as possible. Once we detect we are in that 9010 // scenario, we just return. 9011 if (CC.isInvalid()) 9012 return; 9013 9014 // Diagnose implicit casts to bool. 9015 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 9016 if (isa<StringLiteral>(E)) 9017 // Warn on string literal to bool. Checks for string literals in logical 9018 // and expressions, for instance, assert(0 && "error here"), are 9019 // prevented by a check in AnalyzeImplicitConversions(). 9020 return DiagnoseImpCast(S, E, T, CC, 9021 diag::warn_impcast_string_literal_to_bool); 9022 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 9023 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 9024 // This covers the literal expressions that evaluate to Objective-C 9025 // objects. 9026 return DiagnoseImpCast(S, E, T, CC, 9027 diag::warn_impcast_objective_c_literal_to_bool); 9028 } 9029 if (Source->isPointerType() || Source->canDecayToPointerType()) { 9030 // Warn on pointer to bool conversion that is always true. 9031 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 9032 SourceRange(CC)); 9033 } 9034 } 9035 9036 // Check implicit casts from Objective-C collection literals to specialized 9037 // collection types, e.g., NSArray<NSString *> *. 9038 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 9039 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 9040 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 9041 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 9042 9043 // Strip vector types. 9044 if (isa<VectorType>(Source)) { 9045 if (!isa<VectorType>(Target)) { 9046 if (S.SourceMgr.isInSystemMacro(CC)) 9047 return; 9048 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 9049 } 9050 9051 // If the vector cast is cast between two vectors of the same size, it is 9052 // a bitcast, not a conversion. 9053 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 9054 return; 9055 9056 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 9057 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 9058 } 9059 if (auto VecTy = dyn_cast<VectorType>(Target)) 9060 Target = VecTy->getElementType().getTypePtr(); 9061 9062 // Strip complex types. 9063 if (isa<ComplexType>(Source)) { 9064 if (!isa<ComplexType>(Target)) { 9065 if (S.SourceMgr.isInSystemMacro(CC)) 9066 return; 9067 9068 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 9069 } 9070 9071 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 9072 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 9073 } 9074 9075 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 9076 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 9077 9078 // If the source is floating point... 9079 if (SourceBT && SourceBT->isFloatingPoint()) { 9080 // ...and the target is floating point... 9081 if (TargetBT && TargetBT->isFloatingPoint()) { 9082 // ...then warn if we're dropping FP rank. 9083 9084 // Builtin FP kinds are ordered by increasing FP rank. 9085 if (SourceBT->getKind() > TargetBT->getKind()) { 9086 // Don't warn about float constants that are precisely 9087 // representable in the target type. 9088 Expr::EvalResult result; 9089 if (E->EvaluateAsRValue(result, S.Context)) { 9090 // Value might be a float, a float vector, or a float complex. 9091 if (IsSameFloatAfterCast(result.Val, 9092 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 9093 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 9094 return; 9095 } 9096 9097 if (S.SourceMgr.isInSystemMacro(CC)) 9098 return; 9099 9100 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 9101 } 9102 // ... or possibly if we're increasing rank, too 9103 else if (TargetBT->getKind() > SourceBT->getKind()) { 9104 if (S.SourceMgr.isInSystemMacro(CC)) 9105 return; 9106 9107 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 9108 } 9109 return; 9110 } 9111 9112 // If the target is integral, always warn. 9113 if (TargetBT && TargetBT->isInteger()) { 9114 if (S.SourceMgr.isInSystemMacro(CC)) 9115 return; 9116 9117 DiagnoseFloatingImpCast(S, E, T, CC); 9118 } 9119 9120 // Detect the case where a call result is converted from floating-point to 9121 // to bool, and the final argument to the call is converted from bool, to 9122 // discover this typo: 9123 // 9124 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 9125 // 9126 // FIXME: This is an incredibly special case; is there some more general 9127 // way to detect this class of misplaced-parentheses bug? 9128 if (Target->isBooleanType() && isa<CallExpr>(E)) { 9129 // Check last argument of function call to see if it is an 9130 // implicit cast from a type matching the type the result 9131 // is being cast to. 9132 CallExpr *CEx = cast<CallExpr>(E); 9133 if (unsigned NumArgs = CEx->getNumArgs()) { 9134 Expr *LastA = CEx->getArg(NumArgs - 1); 9135 Expr *InnerE = LastA->IgnoreParenImpCasts(); 9136 if (isa<ImplicitCastExpr>(LastA) && 9137 InnerE->getType()->isBooleanType()) { 9138 // Warn on this floating-point to bool conversion 9139 DiagnoseImpCast(S, E, T, CC, 9140 diag::warn_impcast_floating_point_to_bool); 9141 } 9142 } 9143 } 9144 return; 9145 } 9146 9147 DiagnoseNullConversion(S, E, T, CC); 9148 9149 S.DiscardMisalignedMemberAddress(Target, E); 9150 9151 if (!Source->isIntegerType() || !Target->isIntegerType()) 9152 return; 9153 9154 // TODO: remove this early return once the false positives for constant->bool 9155 // in templates, macros, etc, are reduced or removed. 9156 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 9157 return; 9158 9159 IntRange SourceRange = GetExprRange(S.Context, E); 9160 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 9161 9162 if (SourceRange.Width > TargetRange.Width) { 9163 // If the source is a constant, use a default-on diagnostic. 9164 // TODO: this should happen for bitfield stores, too. 9165 llvm::APSInt Value(32); 9166 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 9167 if (S.SourceMgr.isInSystemMacro(CC)) 9168 return; 9169 9170 std::string PrettySourceValue = Value.toString(10); 9171 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9172 9173 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9174 S.PDiag(diag::warn_impcast_integer_precision_constant) 9175 << PrettySourceValue << PrettyTargetValue 9176 << E->getType() << T << E->getSourceRange() 9177 << clang::SourceRange(CC)); 9178 return; 9179 } 9180 9181 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 9182 if (S.SourceMgr.isInSystemMacro(CC)) 9183 return; 9184 9185 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 9186 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 9187 /* pruneControlFlow */ true); 9188 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 9189 } 9190 9191 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 9192 SourceRange.NonNegative && Source->isSignedIntegerType()) { 9193 // Warn when doing a signed to signed conversion, warn if the positive 9194 // source value is exactly the width of the target type, which will 9195 // cause a negative value to be stored. 9196 9197 llvm::APSInt Value; 9198 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 9199 !S.SourceMgr.isInSystemMacro(CC)) { 9200 if (isSameWidthConstantConversion(S, E, T, CC)) { 9201 std::string PrettySourceValue = Value.toString(10); 9202 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9203 9204 S.DiagRuntimeBehavior( 9205 E->getExprLoc(), E, 9206 S.PDiag(diag::warn_impcast_integer_precision_constant) 9207 << PrettySourceValue << PrettyTargetValue << E->getType() << T 9208 << E->getSourceRange() << clang::SourceRange(CC)); 9209 return; 9210 } 9211 } 9212 9213 // Fall through for non-constants to give a sign conversion warning. 9214 } 9215 9216 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 9217 (!TargetRange.NonNegative && SourceRange.NonNegative && 9218 SourceRange.Width == TargetRange.Width)) { 9219 if (S.SourceMgr.isInSystemMacro(CC)) 9220 return; 9221 9222 unsigned DiagID = diag::warn_impcast_integer_sign; 9223 9224 // Traditionally, gcc has warned about this under -Wsign-compare. 9225 // We also want to warn about it in -Wconversion. 9226 // So if -Wconversion is off, use a completely identical diagnostic 9227 // in the sign-compare group. 9228 // The conditional-checking code will 9229 if (ICContext) { 9230 DiagID = diag::warn_impcast_integer_sign_conditional; 9231 *ICContext = true; 9232 } 9233 9234 return DiagnoseImpCast(S, E, T, CC, DiagID); 9235 } 9236 9237 // Diagnose conversions between different enumeration types. 9238 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 9239 // type, to give us better diagnostics. 9240 QualType SourceType = E->getType(); 9241 if (!S.getLangOpts().CPlusPlus) { 9242 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9243 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 9244 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 9245 SourceType = S.Context.getTypeDeclType(Enum); 9246 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 9247 } 9248 } 9249 9250 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 9251 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 9252 if (SourceEnum->getDecl()->hasNameForLinkage() && 9253 TargetEnum->getDecl()->hasNameForLinkage() && 9254 SourceEnum != TargetEnum) { 9255 if (S.SourceMgr.isInSystemMacro(CC)) 9256 return; 9257 9258 return DiagnoseImpCast(S, E, SourceType, T, CC, 9259 diag::warn_impcast_different_enum_types); 9260 } 9261 } 9262 9263 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9264 SourceLocation CC, QualType T); 9265 9266 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 9267 SourceLocation CC, bool &ICContext) { 9268 E = E->IgnoreParenImpCasts(); 9269 9270 if (isa<ConditionalOperator>(E)) 9271 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 9272 9273 AnalyzeImplicitConversions(S, E, CC); 9274 if (E->getType() != T) 9275 return CheckImplicitConversion(S, E, T, CC, &ICContext); 9276 } 9277 9278 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9279 SourceLocation CC, QualType T) { 9280 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 9281 9282 bool Suspicious = false; 9283 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 9284 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 9285 9286 // If -Wconversion would have warned about either of the candidates 9287 // for a signedness conversion to the context type... 9288 if (!Suspicious) return; 9289 9290 // ...but it's currently ignored... 9291 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 9292 return; 9293 9294 // ...then check whether it would have warned about either of the 9295 // candidates for a signedness conversion to the condition type. 9296 if (E->getType() == T) return; 9297 9298 Suspicious = false; 9299 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 9300 E->getType(), CC, &Suspicious); 9301 if (!Suspicious) 9302 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 9303 E->getType(), CC, &Suspicious); 9304 } 9305 9306 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9307 /// Input argument E is a logical expression. 9308 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 9309 if (S.getLangOpts().Bool) 9310 return; 9311 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 9312 } 9313 9314 /// AnalyzeImplicitConversions - Find and report any interesting 9315 /// implicit conversions in the given expression. There are a couple 9316 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 9317 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 9318 QualType T = OrigE->getType(); 9319 Expr *E = OrigE->IgnoreParenImpCasts(); 9320 9321 if (E->isTypeDependent() || E->isValueDependent()) 9322 return; 9323 9324 // For conditional operators, we analyze the arguments as if they 9325 // were being fed directly into the output. 9326 if (isa<ConditionalOperator>(E)) { 9327 ConditionalOperator *CO = cast<ConditionalOperator>(E); 9328 CheckConditionalOperator(S, CO, CC, T); 9329 return; 9330 } 9331 9332 // Check implicit argument conversions for function calls. 9333 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 9334 CheckImplicitArgumentConversions(S, Call, CC); 9335 9336 // Go ahead and check any implicit conversions we might have skipped. 9337 // The non-canonical typecheck is just an optimization; 9338 // CheckImplicitConversion will filter out dead implicit conversions. 9339 if (E->getType() != T) 9340 CheckImplicitConversion(S, E, T, CC); 9341 9342 // Now continue drilling into this expression. 9343 9344 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 9345 // The bound subexpressions in a PseudoObjectExpr are not reachable 9346 // as transitive children. 9347 // FIXME: Use a more uniform representation for this. 9348 for (auto *SE : POE->semantics()) 9349 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 9350 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 9351 } 9352 9353 // Skip past explicit casts. 9354 if (isa<ExplicitCastExpr>(E)) { 9355 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 9356 return AnalyzeImplicitConversions(S, E, CC); 9357 } 9358 9359 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9360 // Do a somewhat different check with comparison operators. 9361 if (BO->isComparisonOp()) 9362 return AnalyzeComparison(S, BO); 9363 9364 // And with simple assignments. 9365 if (BO->getOpcode() == BO_Assign) 9366 return AnalyzeAssignment(S, BO); 9367 } 9368 9369 // These break the otherwise-useful invariant below. Fortunately, 9370 // we don't really need to recurse into them, because any internal 9371 // expressions should have been analyzed already when they were 9372 // built into statements. 9373 if (isa<StmtExpr>(E)) return; 9374 9375 // Don't descend into unevaluated contexts. 9376 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 9377 9378 // Now just recurse over the expression's children. 9379 CC = E->getExprLoc(); 9380 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 9381 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 9382 for (Stmt *SubStmt : E->children()) { 9383 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 9384 if (!ChildExpr) 9385 continue; 9386 9387 if (IsLogicalAndOperator && 9388 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 9389 // Ignore checking string literals that are in logical and operators. 9390 // This is a common pattern for asserts. 9391 continue; 9392 AnalyzeImplicitConversions(S, ChildExpr, CC); 9393 } 9394 9395 if (BO && BO->isLogicalOp()) { 9396 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 9397 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9398 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9399 9400 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 9401 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9402 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9403 } 9404 9405 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 9406 if (U->getOpcode() == UO_LNot) 9407 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 9408 } 9409 9410 } // end anonymous namespace 9411 9412 /// Diagnose integer type and any valid implicit convertion to it. 9413 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 9414 // Taking into account implicit conversions, 9415 // allow any integer. 9416 if (!E->getType()->isIntegerType()) { 9417 S.Diag(E->getLocStart(), 9418 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 9419 return true; 9420 } 9421 // Potentially emit standard warnings for implicit conversions if enabled 9422 // using -Wconversion. 9423 CheckImplicitConversion(S, E, IntT, E->getLocStart()); 9424 return false; 9425 } 9426 9427 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 9428 // Returns true when emitting a warning about taking the address of a reference. 9429 static bool CheckForReference(Sema &SemaRef, const Expr *E, 9430 const PartialDiagnostic &PD) { 9431 E = E->IgnoreParenImpCasts(); 9432 9433 const FunctionDecl *FD = nullptr; 9434 9435 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9436 if (!DRE->getDecl()->getType()->isReferenceType()) 9437 return false; 9438 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9439 if (!M->getMemberDecl()->getType()->isReferenceType()) 9440 return false; 9441 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 9442 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 9443 return false; 9444 FD = Call->getDirectCallee(); 9445 } else { 9446 return false; 9447 } 9448 9449 SemaRef.Diag(E->getExprLoc(), PD); 9450 9451 // If possible, point to location of function. 9452 if (FD) { 9453 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 9454 } 9455 9456 return true; 9457 } 9458 9459 // Returns true if the SourceLocation is expanded from any macro body. 9460 // Returns false if the SourceLocation is invalid, is from not in a macro 9461 // expansion, or is from expanded from a top-level macro argument. 9462 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 9463 if (Loc.isInvalid()) 9464 return false; 9465 9466 while (Loc.isMacroID()) { 9467 if (SM.isMacroBodyExpansion(Loc)) 9468 return true; 9469 Loc = SM.getImmediateMacroCallerLoc(Loc); 9470 } 9471 9472 return false; 9473 } 9474 9475 /// \brief Diagnose pointers that are always non-null. 9476 /// \param E the expression containing the pointer 9477 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 9478 /// compared to a null pointer 9479 /// \param IsEqual True when the comparison is equal to a null pointer 9480 /// \param Range Extra SourceRange to highlight in the diagnostic 9481 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 9482 Expr::NullPointerConstantKind NullKind, 9483 bool IsEqual, SourceRange Range) { 9484 if (!E) 9485 return; 9486 9487 // Don't warn inside macros. 9488 if (E->getExprLoc().isMacroID()) { 9489 const SourceManager &SM = getSourceManager(); 9490 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 9491 IsInAnyMacroBody(SM, Range.getBegin())) 9492 return; 9493 } 9494 E = E->IgnoreImpCasts(); 9495 9496 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 9497 9498 if (isa<CXXThisExpr>(E)) { 9499 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 9500 : diag::warn_this_bool_conversion; 9501 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 9502 return; 9503 } 9504 9505 bool IsAddressOf = false; 9506 9507 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9508 if (UO->getOpcode() != UO_AddrOf) 9509 return; 9510 IsAddressOf = true; 9511 E = UO->getSubExpr(); 9512 } 9513 9514 if (IsAddressOf) { 9515 unsigned DiagID = IsCompare 9516 ? diag::warn_address_of_reference_null_compare 9517 : diag::warn_address_of_reference_bool_conversion; 9518 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 9519 << IsEqual; 9520 if (CheckForReference(*this, E, PD)) { 9521 return; 9522 } 9523 } 9524 9525 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 9526 bool IsParam = isa<NonNullAttr>(NonnullAttr); 9527 std::string Str; 9528 llvm::raw_string_ostream S(Str); 9529 E->printPretty(S, nullptr, getPrintingPolicy()); 9530 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 9531 : diag::warn_cast_nonnull_to_bool; 9532 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 9533 << E->getSourceRange() << Range << IsEqual; 9534 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 9535 }; 9536 9537 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 9538 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 9539 if (auto *Callee = Call->getDirectCallee()) { 9540 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 9541 ComplainAboutNonnullParamOrCall(A); 9542 return; 9543 } 9544 } 9545 } 9546 9547 // Expect to find a single Decl. Skip anything more complicated. 9548 ValueDecl *D = nullptr; 9549 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 9550 D = R->getDecl(); 9551 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9552 D = M->getMemberDecl(); 9553 } 9554 9555 // Weak Decls can be null. 9556 if (!D || D->isWeak()) 9557 return; 9558 9559 // Check for parameter decl with nonnull attribute 9560 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 9561 if (getCurFunction() && 9562 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 9563 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 9564 ComplainAboutNonnullParamOrCall(A); 9565 return; 9566 } 9567 9568 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 9569 auto ParamIter = llvm::find(FD->parameters(), PV); 9570 assert(ParamIter != FD->param_end()); 9571 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 9572 9573 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 9574 if (!NonNull->args_size()) { 9575 ComplainAboutNonnullParamOrCall(NonNull); 9576 return; 9577 } 9578 9579 for (unsigned ArgNo : NonNull->args()) { 9580 if (ArgNo == ParamNo) { 9581 ComplainAboutNonnullParamOrCall(NonNull); 9582 return; 9583 } 9584 } 9585 } 9586 } 9587 } 9588 } 9589 9590 QualType T = D->getType(); 9591 const bool IsArray = T->isArrayType(); 9592 const bool IsFunction = T->isFunctionType(); 9593 9594 // Address of function is used to silence the function warning. 9595 if (IsAddressOf && IsFunction) { 9596 return; 9597 } 9598 9599 // Found nothing. 9600 if (!IsAddressOf && !IsFunction && !IsArray) 9601 return; 9602 9603 // Pretty print the expression for the diagnostic. 9604 std::string Str; 9605 llvm::raw_string_ostream S(Str); 9606 E->printPretty(S, nullptr, getPrintingPolicy()); 9607 9608 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 9609 : diag::warn_impcast_pointer_to_bool; 9610 enum { 9611 AddressOf, 9612 FunctionPointer, 9613 ArrayPointer 9614 } DiagType; 9615 if (IsAddressOf) 9616 DiagType = AddressOf; 9617 else if (IsFunction) 9618 DiagType = FunctionPointer; 9619 else if (IsArray) 9620 DiagType = ArrayPointer; 9621 else 9622 llvm_unreachable("Could not determine diagnostic."); 9623 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 9624 << Range << IsEqual; 9625 9626 if (!IsFunction) 9627 return; 9628 9629 // Suggest '&' to silence the function warning. 9630 Diag(E->getExprLoc(), diag::note_function_warning_silence) 9631 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 9632 9633 // Check to see if '()' fixit should be emitted. 9634 QualType ReturnType; 9635 UnresolvedSet<4> NonTemplateOverloads; 9636 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 9637 if (ReturnType.isNull()) 9638 return; 9639 9640 if (IsCompare) { 9641 // There are two cases here. If there is null constant, the only suggest 9642 // for a pointer return type. If the null is 0, then suggest if the return 9643 // type is a pointer or an integer type. 9644 if (!ReturnType->isPointerType()) { 9645 if (NullKind == Expr::NPCK_ZeroExpression || 9646 NullKind == Expr::NPCK_ZeroLiteral) { 9647 if (!ReturnType->isIntegerType()) 9648 return; 9649 } else { 9650 return; 9651 } 9652 } 9653 } else { // !IsCompare 9654 // For function to bool, only suggest if the function pointer has bool 9655 // return type. 9656 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 9657 return; 9658 } 9659 Diag(E->getExprLoc(), diag::note_function_to_function_call) 9660 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 9661 } 9662 9663 /// Diagnoses "dangerous" implicit conversions within the given 9664 /// expression (which is a full expression). Implements -Wconversion 9665 /// and -Wsign-compare. 9666 /// 9667 /// \param CC the "context" location of the implicit conversion, i.e. 9668 /// the most location of the syntactic entity requiring the implicit 9669 /// conversion 9670 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 9671 // Don't diagnose in unevaluated contexts. 9672 if (isUnevaluatedContext()) 9673 return; 9674 9675 // Don't diagnose for value- or type-dependent expressions. 9676 if (E->isTypeDependent() || E->isValueDependent()) 9677 return; 9678 9679 // Check for array bounds violations in cases where the check isn't triggered 9680 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 9681 // ArraySubscriptExpr is on the RHS of a variable initialization. 9682 CheckArrayAccess(E); 9683 9684 // This is not the right CC for (e.g.) a variable initialization. 9685 AnalyzeImplicitConversions(*this, E, CC); 9686 } 9687 9688 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9689 /// Input argument E is a logical expression. 9690 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 9691 ::CheckBoolLikeConversion(*this, E, CC); 9692 } 9693 9694 /// Diagnose when expression is an integer constant expression and its evaluation 9695 /// results in integer overflow 9696 void Sema::CheckForIntOverflow (Expr *E) { 9697 // Use a work list to deal with nested struct initializers. 9698 SmallVector<Expr *, 2> Exprs(1, E); 9699 9700 do { 9701 Expr *E = Exprs.pop_back_val(); 9702 9703 if (isa<BinaryOperator>(E->IgnoreParenCasts())) { 9704 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 9705 continue; 9706 } 9707 9708 if (auto InitList = dyn_cast<InitListExpr>(E)) 9709 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 9710 } while (!Exprs.empty()); 9711 } 9712 9713 namespace { 9714 /// \brief Visitor for expressions which looks for unsequenced operations on the 9715 /// same object. 9716 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 9717 typedef EvaluatedExprVisitor<SequenceChecker> Base; 9718 9719 /// \brief A tree of sequenced regions within an expression. Two regions are 9720 /// unsequenced if one is an ancestor or a descendent of the other. When we 9721 /// finish processing an expression with sequencing, such as a comma 9722 /// expression, we fold its tree nodes into its parent, since they are 9723 /// unsequenced with respect to nodes we will visit later. 9724 class SequenceTree { 9725 struct Value { 9726 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 9727 unsigned Parent : 31; 9728 unsigned Merged : 1; 9729 }; 9730 SmallVector<Value, 8> Values; 9731 9732 public: 9733 /// \brief A region within an expression which may be sequenced with respect 9734 /// to some other region. 9735 class Seq { 9736 explicit Seq(unsigned N) : Index(N) {} 9737 unsigned Index; 9738 friend class SequenceTree; 9739 public: 9740 Seq() : Index(0) {} 9741 }; 9742 9743 SequenceTree() { Values.push_back(Value(0)); } 9744 Seq root() const { return Seq(0); } 9745 9746 /// \brief Create a new sequence of operations, which is an unsequenced 9747 /// subset of \p Parent. This sequence of operations is sequenced with 9748 /// respect to other children of \p Parent. 9749 Seq allocate(Seq Parent) { 9750 Values.push_back(Value(Parent.Index)); 9751 return Seq(Values.size() - 1); 9752 } 9753 9754 /// \brief Merge a sequence of operations into its parent. 9755 void merge(Seq S) { 9756 Values[S.Index].Merged = true; 9757 } 9758 9759 /// \brief Determine whether two operations are unsequenced. This operation 9760 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 9761 /// should have been merged into its parent as appropriate. 9762 bool isUnsequenced(Seq Cur, Seq Old) { 9763 unsigned C = representative(Cur.Index); 9764 unsigned Target = representative(Old.Index); 9765 while (C >= Target) { 9766 if (C == Target) 9767 return true; 9768 C = Values[C].Parent; 9769 } 9770 return false; 9771 } 9772 9773 private: 9774 /// \brief Pick a representative for a sequence. 9775 unsigned representative(unsigned K) { 9776 if (Values[K].Merged) 9777 // Perform path compression as we go. 9778 return Values[K].Parent = representative(Values[K].Parent); 9779 return K; 9780 } 9781 }; 9782 9783 /// An object for which we can track unsequenced uses. 9784 typedef NamedDecl *Object; 9785 9786 /// Different flavors of object usage which we track. We only track the 9787 /// least-sequenced usage of each kind. 9788 enum UsageKind { 9789 /// A read of an object. Multiple unsequenced reads are OK. 9790 UK_Use, 9791 /// A modification of an object which is sequenced before the value 9792 /// computation of the expression, such as ++n in C++. 9793 UK_ModAsValue, 9794 /// A modification of an object which is not sequenced before the value 9795 /// computation of the expression, such as n++. 9796 UK_ModAsSideEffect, 9797 9798 UK_Count = UK_ModAsSideEffect + 1 9799 }; 9800 9801 struct Usage { 9802 Usage() : Use(nullptr), Seq() {} 9803 Expr *Use; 9804 SequenceTree::Seq Seq; 9805 }; 9806 9807 struct UsageInfo { 9808 UsageInfo() : Diagnosed(false) {} 9809 Usage Uses[UK_Count]; 9810 /// Have we issued a diagnostic for this variable already? 9811 bool Diagnosed; 9812 }; 9813 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 9814 9815 Sema &SemaRef; 9816 /// Sequenced regions within the expression. 9817 SequenceTree Tree; 9818 /// Declaration modifications and references which we have seen. 9819 UsageInfoMap UsageMap; 9820 /// The region we are currently within. 9821 SequenceTree::Seq Region; 9822 /// Filled in with declarations which were modified as a side-effect 9823 /// (that is, post-increment operations). 9824 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 9825 /// Expressions to check later. We defer checking these to reduce 9826 /// stack usage. 9827 SmallVectorImpl<Expr *> &WorkList; 9828 9829 /// RAII object wrapping the visitation of a sequenced subexpression of an 9830 /// expression. At the end of this process, the side-effects of the evaluation 9831 /// become sequenced with respect to the value computation of the result, so 9832 /// we downgrade any UK_ModAsSideEffect within the evaluation to 9833 /// UK_ModAsValue. 9834 struct SequencedSubexpression { 9835 SequencedSubexpression(SequenceChecker &Self) 9836 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 9837 Self.ModAsSideEffect = &ModAsSideEffect; 9838 } 9839 ~SequencedSubexpression() { 9840 for (auto &M : llvm::reverse(ModAsSideEffect)) { 9841 UsageInfo &U = Self.UsageMap[M.first]; 9842 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 9843 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 9844 SideEffectUsage = M.second; 9845 } 9846 Self.ModAsSideEffect = OldModAsSideEffect; 9847 } 9848 9849 SequenceChecker &Self; 9850 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 9851 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 9852 }; 9853 9854 /// RAII object wrapping the visitation of a subexpression which we might 9855 /// choose to evaluate as a constant. If any subexpression is evaluated and 9856 /// found to be non-constant, this allows us to suppress the evaluation of 9857 /// the outer expression. 9858 class EvaluationTracker { 9859 public: 9860 EvaluationTracker(SequenceChecker &Self) 9861 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 9862 Self.EvalTracker = this; 9863 } 9864 ~EvaluationTracker() { 9865 Self.EvalTracker = Prev; 9866 if (Prev) 9867 Prev->EvalOK &= EvalOK; 9868 } 9869 9870 bool evaluate(const Expr *E, bool &Result) { 9871 if (!EvalOK || E->isValueDependent()) 9872 return false; 9873 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 9874 return EvalOK; 9875 } 9876 9877 private: 9878 SequenceChecker &Self; 9879 EvaluationTracker *Prev; 9880 bool EvalOK; 9881 } *EvalTracker; 9882 9883 /// \brief Find the object which is produced by the specified expression, 9884 /// if any. 9885 Object getObject(Expr *E, bool Mod) const { 9886 E = E->IgnoreParenCasts(); 9887 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9888 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 9889 return getObject(UO->getSubExpr(), Mod); 9890 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9891 if (BO->getOpcode() == BO_Comma) 9892 return getObject(BO->getRHS(), Mod); 9893 if (Mod && BO->isAssignmentOp()) 9894 return getObject(BO->getLHS(), Mod); 9895 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9896 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 9897 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 9898 return ME->getMemberDecl(); 9899 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9900 // FIXME: If this is a reference, map through to its value. 9901 return DRE->getDecl(); 9902 return nullptr; 9903 } 9904 9905 /// \brief Note that an object was modified or used by an expression. 9906 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 9907 Usage &U = UI.Uses[UK]; 9908 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 9909 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 9910 ModAsSideEffect->push_back(std::make_pair(O, U)); 9911 U.Use = Ref; 9912 U.Seq = Region; 9913 } 9914 } 9915 /// \brief Check whether a modification or use conflicts with a prior usage. 9916 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 9917 bool IsModMod) { 9918 if (UI.Diagnosed) 9919 return; 9920 9921 const Usage &U = UI.Uses[OtherKind]; 9922 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 9923 return; 9924 9925 Expr *Mod = U.Use; 9926 Expr *ModOrUse = Ref; 9927 if (OtherKind == UK_Use) 9928 std::swap(Mod, ModOrUse); 9929 9930 SemaRef.Diag(Mod->getExprLoc(), 9931 IsModMod ? diag::warn_unsequenced_mod_mod 9932 : diag::warn_unsequenced_mod_use) 9933 << O << SourceRange(ModOrUse->getExprLoc()); 9934 UI.Diagnosed = true; 9935 } 9936 9937 void notePreUse(Object O, Expr *Use) { 9938 UsageInfo &U = UsageMap[O]; 9939 // Uses conflict with other modifications. 9940 checkUsage(O, U, Use, UK_ModAsValue, false); 9941 } 9942 void notePostUse(Object O, Expr *Use) { 9943 UsageInfo &U = UsageMap[O]; 9944 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 9945 addUsage(U, O, Use, UK_Use); 9946 } 9947 9948 void notePreMod(Object O, Expr *Mod) { 9949 UsageInfo &U = UsageMap[O]; 9950 // Modifications conflict with other modifications and with uses. 9951 checkUsage(O, U, Mod, UK_ModAsValue, true); 9952 checkUsage(O, U, Mod, UK_Use, false); 9953 } 9954 void notePostMod(Object O, Expr *Use, UsageKind UK) { 9955 UsageInfo &U = UsageMap[O]; 9956 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 9957 addUsage(U, O, Use, UK); 9958 } 9959 9960 public: 9961 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 9962 : Base(S.Context), SemaRef(S), Region(Tree.root()), 9963 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 9964 Visit(E); 9965 } 9966 9967 void VisitStmt(Stmt *S) { 9968 // Skip all statements which aren't expressions for now. 9969 } 9970 9971 void VisitExpr(Expr *E) { 9972 // By default, just recurse to evaluated subexpressions. 9973 Base::VisitStmt(E); 9974 } 9975 9976 void VisitCastExpr(CastExpr *E) { 9977 Object O = Object(); 9978 if (E->getCastKind() == CK_LValueToRValue) 9979 O = getObject(E->getSubExpr(), false); 9980 9981 if (O) 9982 notePreUse(O, E); 9983 VisitExpr(E); 9984 if (O) 9985 notePostUse(O, E); 9986 } 9987 9988 void VisitBinComma(BinaryOperator *BO) { 9989 // C++11 [expr.comma]p1: 9990 // Every value computation and side effect associated with the left 9991 // expression is sequenced before every value computation and side 9992 // effect associated with the right expression. 9993 SequenceTree::Seq LHS = Tree.allocate(Region); 9994 SequenceTree::Seq RHS = Tree.allocate(Region); 9995 SequenceTree::Seq OldRegion = Region; 9996 9997 { 9998 SequencedSubexpression SeqLHS(*this); 9999 Region = LHS; 10000 Visit(BO->getLHS()); 10001 } 10002 10003 Region = RHS; 10004 Visit(BO->getRHS()); 10005 10006 Region = OldRegion; 10007 10008 // Forget that LHS and RHS are sequenced. They are both unsequenced 10009 // with respect to other stuff. 10010 Tree.merge(LHS); 10011 Tree.merge(RHS); 10012 } 10013 10014 void VisitBinAssign(BinaryOperator *BO) { 10015 // The modification is sequenced after the value computation of the LHS 10016 // and RHS, so check it before inspecting the operands and update the 10017 // map afterwards. 10018 Object O = getObject(BO->getLHS(), true); 10019 if (!O) 10020 return VisitExpr(BO); 10021 10022 notePreMod(O, BO); 10023 10024 // C++11 [expr.ass]p7: 10025 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 10026 // only once. 10027 // 10028 // Therefore, for a compound assignment operator, O is considered used 10029 // everywhere except within the evaluation of E1 itself. 10030 if (isa<CompoundAssignOperator>(BO)) 10031 notePreUse(O, BO); 10032 10033 Visit(BO->getLHS()); 10034 10035 if (isa<CompoundAssignOperator>(BO)) 10036 notePostUse(O, BO); 10037 10038 Visit(BO->getRHS()); 10039 10040 // C++11 [expr.ass]p1: 10041 // the assignment is sequenced [...] before the value computation of the 10042 // assignment expression. 10043 // C11 6.5.16/3 has no such rule. 10044 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10045 : UK_ModAsSideEffect); 10046 } 10047 10048 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 10049 VisitBinAssign(CAO); 10050 } 10051 10052 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10053 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 10054 void VisitUnaryPreIncDec(UnaryOperator *UO) { 10055 Object O = getObject(UO->getSubExpr(), true); 10056 if (!O) 10057 return VisitExpr(UO); 10058 10059 notePreMod(O, UO); 10060 Visit(UO->getSubExpr()); 10061 // C++11 [expr.pre.incr]p1: 10062 // the expression ++x is equivalent to x+=1 10063 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 10064 : UK_ModAsSideEffect); 10065 } 10066 10067 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10068 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 10069 void VisitUnaryPostIncDec(UnaryOperator *UO) { 10070 Object O = getObject(UO->getSubExpr(), true); 10071 if (!O) 10072 return VisitExpr(UO); 10073 10074 notePreMod(O, UO); 10075 Visit(UO->getSubExpr()); 10076 notePostMod(O, UO, UK_ModAsSideEffect); 10077 } 10078 10079 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 10080 void VisitBinLOr(BinaryOperator *BO) { 10081 // The side-effects of the LHS of an '&&' are sequenced before the 10082 // value computation of the RHS, and hence before the value computation 10083 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 10084 // as if they were unconditionally sequenced. 10085 EvaluationTracker Eval(*this); 10086 { 10087 SequencedSubexpression Sequenced(*this); 10088 Visit(BO->getLHS()); 10089 } 10090 10091 bool Result; 10092 if (Eval.evaluate(BO->getLHS(), Result)) { 10093 if (!Result) 10094 Visit(BO->getRHS()); 10095 } else { 10096 // Check for unsequenced operations in the RHS, treating it as an 10097 // entirely separate evaluation. 10098 // 10099 // FIXME: If there are operations in the RHS which are unsequenced 10100 // with respect to operations outside the RHS, and those operations 10101 // are unconditionally evaluated, diagnose them. 10102 WorkList.push_back(BO->getRHS()); 10103 } 10104 } 10105 void VisitBinLAnd(BinaryOperator *BO) { 10106 EvaluationTracker Eval(*this); 10107 { 10108 SequencedSubexpression Sequenced(*this); 10109 Visit(BO->getLHS()); 10110 } 10111 10112 bool Result; 10113 if (Eval.evaluate(BO->getLHS(), Result)) { 10114 if (Result) 10115 Visit(BO->getRHS()); 10116 } else { 10117 WorkList.push_back(BO->getRHS()); 10118 } 10119 } 10120 10121 // Only visit the condition, unless we can be sure which subexpression will 10122 // be chosen. 10123 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 10124 EvaluationTracker Eval(*this); 10125 { 10126 SequencedSubexpression Sequenced(*this); 10127 Visit(CO->getCond()); 10128 } 10129 10130 bool Result; 10131 if (Eval.evaluate(CO->getCond(), Result)) 10132 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 10133 else { 10134 WorkList.push_back(CO->getTrueExpr()); 10135 WorkList.push_back(CO->getFalseExpr()); 10136 } 10137 } 10138 10139 void VisitCallExpr(CallExpr *CE) { 10140 // C++11 [intro.execution]p15: 10141 // When calling a function [...], every value computation and side effect 10142 // associated with any argument expression, or with the postfix expression 10143 // designating the called function, is sequenced before execution of every 10144 // expression or statement in the body of the function [and thus before 10145 // the value computation of its result]. 10146 SequencedSubexpression Sequenced(*this); 10147 Base::VisitCallExpr(CE); 10148 10149 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 10150 } 10151 10152 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 10153 // This is a call, so all subexpressions are sequenced before the result. 10154 SequencedSubexpression Sequenced(*this); 10155 10156 if (!CCE->isListInitialization()) 10157 return VisitExpr(CCE); 10158 10159 // In C++11, list initializations are sequenced. 10160 SmallVector<SequenceTree::Seq, 32> Elts; 10161 SequenceTree::Seq Parent = Region; 10162 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 10163 E = CCE->arg_end(); 10164 I != E; ++I) { 10165 Region = Tree.allocate(Parent); 10166 Elts.push_back(Region); 10167 Visit(*I); 10168 } 10169 10170 // Forget that the initializers are sequenced. 10171 Region = Parent; 10172 for (unsigned I = 0; I < Elts.size(); ++I) 10173 Tree.merge(Elts[I]); 10174 } 10175 10176 void VisitInitListExpr(InitListExpr *ILE) { 10177 if (!SemaRef.getLangOpts().CPlusPlus11) 10178 return VisitExpr(ILE); 10179 10180 // In C++11, list initializations are sequenced. 10181 SmallVector<SequenceTree::Seq, 32> Elts; 10182 SequenceTree::Seq Parent = Region; 10183 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 10184 Expr *E = ILE->getInit(I); 10185 if (!E) continue; 10186 Region = Tree.allocate(Parent); 10187 Elts.push_back(Region); 10188 Visit(E); 10189 } 10190 10191 // Forget that the initializers are sequenced. 10192 Region = Parent; 10193 for (unsigned I = 0; I < Elts.size(); ++I) 10194 Tree.merge(Elts[I]); 10195 } 10196 }; 10197 } // end anonymous namespace 10198 10199 void Sema::CheckUnsequencedOperations(Expr *E) { 10200 SmallVector<Expr *, 8> WorkList; 10201 WorkList.push_back(E); 10202 while (!WorkList.empty()) { 10203 Expr *Item = WorkList.pop_back_val(); 10204 SequenceChecker(*this, Item, WorkList); 10205 } 10206 } 10207 10208 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 10209 bool IsConstexpr) { 10210 CheckImplicitConversions(E, CheckLoc); 10211 if (!E->isInstantiationDependent()) 10212 CheckUnsequencedOperations(E); 10213 if (!IsConstexpr && !E->isValueDependent()) 10214 CheckForIntOverflow(E); 10215 DiagnoseMisalignedMembers(); 10216 } 10217 10218 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 10219 FieldDecl *BitField, 10220 Expr *Init) { 10221 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 10222 } 10223 10224 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 10225 SourceLocation Loc) { 10226 if (!PType->isVariablyModifiedType()) 10227 return; 10228 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 10229 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 10230 return; 10231 } 10232 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 10233 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 10234 return; 10235 } 10236 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 10237 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 10238 return; 10239 } 10240 10241 const ArrayType *AT = S.Context.getAsArrayType(PType); 10242 if (!AT) 10243 return; 10244 10245 if (AT->getSizeModifier() != ArrayType::Star) { 10246 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 10247 return; 10248 } 10249 10250 S.Diag(Loc, diag::err_array_star_in_function_definition); 10251 } 10252 10253 /// CheckParmsForFunctionDef - Check that the parameters of the given 10254 /// function are appropriate for the definition of a function. This 10255 /// takes care of any checks that cannot be performed on the 10256 /// declaration itself, e.g., that the types of each of the function 10257 /// parameters are complete. 10258 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 10259 bool CheckParameterNames) { 10260 bool HasInvalidParm = false; 10261 for (ParmVarDecl *Param : Parameters) { 10262 // C99 6.7.5.3p4: the parameters in a parameter type list in a 10263 // function declarator that is part of a function definition of 10264 // that function shall not have incomplete type. 10265 // 10266 // This is also C++ [dcl.fct]p6. 10267 if (!Param->isInvalidDecl() && 10268 RequireCompleteType(Param->getLocation(), Param->getType(), 10269 diag::err_typecheck_decl_incomplete_type)) { 10270 Param->setInvalidDecl(); 10271 HasInvalidParm = true; 10272 } 10273 10274 // C99 6.9.1p5: If the declarator includes a parameter type list, the 10275 // declaration of each parameter shall include an identifier. 10276 if (CheckParameterNames && 10277 Param->getIdentifier() == nullptr && 10278 !Param->isImplicit() && 10279 !getLangOpts().CPlusPlus) 10280 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10281 10282 // C99 6.7.5.3p12: 10283 // If the function declarator is not part of a definition of that 10284 // function, parameters may have incomplete type and may use the [*] 10285 // notation in their sequences of declarator specifiers to specify 10286 // variable length array types. 10287 QualType PType = Param->getOriginalType(); 10288 // FIXME: This diagnostic should point the '[*]' if source-location 10289 // information is added for it. 10290 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 10291 10292 // MSVC destroys objects passed by value in the callee. Therefore a 10293 // function definition which takes such a parameter must be able to call the 10294 // object's destructor. However, we don't perform any direct access check 10295 // on the dtor. 10296 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 10297 .getCXXABI() 10298 .areArgsDestroyedLeftToRightInCallee()) { 10299 if (!Param->isInvalidDecl()) { 10300 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 10301 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 10302 if (!ClassDecl->isInvalidDecl() && 10303 !ClassDecl->hasIrrelevantDestructor() && 10304 !ClassDecl->isDependentContext()) { 10305 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10306 MarkFunctionReferenced(Param->getLocation(), Destructor); 10307 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 10308 } 10309 } 10310 } 10311 } 10312 10313 // Parameters with the pass_object_size attribute only need to be marked 10314 // constant at function definitions. Because we lack information about 10315 // whether we're on a declaration or definition when we're instantiating the 10316 // attribute, we need to check for constness here. 10317 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 10318 if (!Param->getType().isConstQualified()) 10319 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 10320 << Attr->getSpelling() << 1; 10321 } 10322 10323 return HasInvalidParm; 10324 } 10325 10326 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 10327 /// or MemberExpr. 10328 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 10329 ASTContext &Context) { 10330 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 10331 return Context.getDeclAlign(DRE->getDecl()); 10332 10333 if (const auto *ME = dyn_cast<MemberExpr>(E)) 10334 return Context.getDeclAlign(ME->getMemberDecl()); 10335 10336 return TypeAlign; 10337 } 10338 10339 /// CheckCastAlign - Implements -Wcast-align, which warns when a 10340 /// pointer cast increases the alignment requirements. 10341 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 10342 // This is actually a lot of work to potentially be doing on every 10343 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 10344 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 10345 return; 10346 10347 // Ignore dependent types. 10348 if (T->isDependentType() || Op->getType()->isDependentType()) 10349 return; 10350 10351 // Require that the destination be a pointer type. 10352 const PointerType *DestPtr = T->getAs<PointerType>(); 10353 if (!DestPtr) return; 10354 10355 // If the destination has alignment 1, we're done. 10356 QualType DestPointee = DestPtr->getPointeeType(); 10357 if (DestPointee->isIncompleteType()) return; 10358 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 10359 if (DestAlign.isOne()) return; 10360 10361 // Require that the source be a pointer type. 10362 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 10363 if (!SrcPtr) return; 10364 QualType SrcPointee = SrcPtr->getPointeeType(); 10365 10366 // Whitelist casts from cv void*. We already implicitly 10367 // whitelisted casts to cv void*, since they have alignment 1. 10368 // Also whitelist casts involving incomplete types, which implicitly 10369 // includes 'void'. 10370 if (SrcPointee->isIncompleteType()) return; 10371 10372 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 10373 10374 if (auto *CE = dyn_cast<CastExpr>(Op)) { 10375 if (CE->getCastKind() == CK_ArrayToPointerDecay) 10376 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 10377 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 10378 if (UO->getOpcode() == UO_AddrOf) 10379 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 10380 } 10381 10382 if (SrcAlign >= DestAlign) return; 10383 10384 Diag(TRange.getBegin(), diag::warn_cast_align) 10385 << Op->getType() << T 10386 << static_cast<unsigned>(SrcAlign.getQuantity()) 10387 << static_cast<unsigned>(DestAlign.getQuantity()) 10388 << TRange << Op->getSourceRange(); 10389 } 10390 10391 /// \brief Check whether this array fits the idiom of a size-one tail padded 10392 /// array member of a struct. 10393 /// 10394 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 10395 /// commonly used to emulate flexible arrays in C89 code. 10396 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 10397 const NamedDecl *ND) { 10398 if (Size != 1 || !ND) return false; 10399 10400 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 10401 if (!FD) return false; 10402 10403 // Don't consider sizes resulting from macro expansions or template argument 10404 // substitution to form C89 tail-padded arrays. 10405 10406 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 10407 while (TInfo) { 10408 TypeLoc TL = TInfo->getTypeLoc(); 10409 // Look through typedefs. 10410 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 10411 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 10412 TInfo = TDL->getTypeSourceInfo(); 10413 continue; 10414 } 10415 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 10416 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 10417 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 10418 return false; 10419 } 10420 break; 10421 } 10422 10423 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 10424 if (!RD) return false; 10425 if (RD->isUnion()) return false; 10426 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10427 if (!CRD->isStandardLayout()) return false; 10428 } 10429 10430 // See if this is the last field decl in the record. 10431 const Decl *D = FD; 10432 while ((D = D->getNextDeclInContext())) 10433 if (isa<FieldDecl>(D)) 10434 return false; 10435 return true; 10436 } 10437 10438 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 10439 const ArraySubscriptExpr *ASE, 10440 bool AllowOnePastEnd, bool IndexNegated) { 10441 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 10442 if (IndexExpr->isValueDependent()) 10443 return; 10444 10445 const Type *EffectiveType = 10446 BaseExpr->getType()->getPointeeOrArrayElementType(); 10447 BaseExpr = BaseExpr->IgnoreParenCasts(); 10448 const ConstantArrayType *ArrayTy = 10449 Context.getAsConstantArrayType(BaseExpr->getType()); 10450 if (!ArrayTy) 10451 return; 10452 10453 llvm::APSInt index; 10454 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 10455 return; 10456 if (IndexNegated) 10457 index = -index; 10458 10459 const NamedDecl *ND = nullptr; 10460 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10461 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10462 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10463 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10464 10465 if (index.isUnsigned() || !index.isNegative()) { 10466 llvm::APInt size = ArrayTy->getSize(); 10467 if (!size.isStrictlyPositive()) 10468 return; 10469 10470 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 10471 if (BaseType != EffectiveType) { 10472 // Make sure we're comparing apples to apples when comparing index to size 10473 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 10474 uint64_t array_typesize = Context.getTypeSize(BaseType); 10475 // Handle ptrarith_typesize being zero, such as when casting to void* 10476 if (!ptrarith_typesize) ptrarith_typesize = 1; 10477 if (ptrarith_typesize != array_typesize) { 10478 // There's a cast to a different size type involved 10479 uint64_t ratio = array_typesize / ptrarith_typesize; 10480 // TODO: Be smarter about handling cases where array_typesize is not a 10481 // multiple of ptrarith_typesize 10482 if (ptrarith_typesize * ratio == array_typesize) 10483 size *= llvm::APInt(size.getBitWidth(), ratio); 10484 } 10485 } 10486 10487 if (size.getBitWidth() > index.getBitWidth()) 10488 index = index.zext(size.getBitWidth()); 10489 else if (size.getBitWidth() < index.getBitWidth()) 10490 size = size.zext(index.getBitWidth()); 10491 10492 // For array subscripting the index must be less than size, but for pointer 10493 // arithmetic also allow the index (offset) to be equal to size since 10494 // computing the next address after the end of the array is legal and 10495 // commonly done e.g. in C++ iterators and range-based for loops. 10496 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 10497 return; 10498 10499 // Also don't warn for arrays of size 1 which are members of some 10500 // structure. These are often used to approximate flexible arrays in C89 10501 // code. 10502 if (IsTailPaddedMemberArray(*this, size, ND)) 10503 return; 10504 10505 // Suppress the warning if the subscript expression (as identified by the 10506 // ']' location) and the index expression are both from macro expansions 10507 // within a system header. 10508 if (ASE) { 10509 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 10510 ASE->getRBracketLoc()); 10511 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 10512 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 10513 IndexExpr->getLocStart()); 10514 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 10515 return; 10516 } 10517 } 10518 10519 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 10520 if (ASE) 10521 DiagID = diag::warn_array_index_exceeds_bounds; 10522 10523 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10524 PDiag(DiagID) << index.toString(10, true) 10525 << size.toString(10, true) 10526 << (unsigned)size.getLimitedValue(~0U) 10527 << IndexExpr->getSourceRange()); 10528 } else { 10529 unsigned DiagID = diag::warn_array_index_precedes_bounds; 10530 if (!ASE) { 10531 DiagID = diag::warn_ptr_arith_precedes_bounds; 10532 if (index.isNegative()) index = -index; 10533 } 10534 10535 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10536 PDiag(DiagID) << index.toString(10, true) 10537 << IndexExpr->getSourceRange()); 10538 } 10539 10540 if (!ND) { 10541 // Try harder to find a NamedDecl to point at in the note. 10542 while (const ArraySubscriptExpr *ASE = 10543 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 10544 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 10545 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10546 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10547 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10548 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10549 } 10550 10551 if (ND) 10552 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 10553 PDiag(diag::note_array_index_out_of_bounds) 10554 << ND->getDeclName()); 10555 } 10556 10557 void Sema::CheckArrayAccess(const Expr *expr) { 10558 int AllowOnePastEnd = 0; 10559 while (expr) { 10560 expr = expr->IgnoreParenImpCasts(); 10561 switch (expr->getStmtClass()) { 10562 case Stmt::ArraySubscriptExprClass: { 10563 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 10564 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 10565 AllowOnePastEnd > 0); 10566 return; 10567 } 10568 case Stmt::OMPArraySectionExprClass: { 10569 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 10570 if (ASE->getLowerBound()) 10571 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 10572 /*ASE=*/nullptr, AllowOnePastEnd > 0); 10573 return; 10574 } 10575 case Stmt::UnaryOperatorClass: { 10576 // Only unwrap the * and & unary operators 10577 const UnaryOperator *UO = cast<UnaryOperator>(expr); 10578 expr = UO->getSubExpr(); 10579 switch (UO->getOpcode()) { 10580 case UO_AddrOf: 10581 AllowOnePastEnd++; 10582 break; 10583 case UO_Deref: 10584 AllowOnePastEnd--; 10585 break; 10586 default: 10587 return; 10588 } 10589 break; 10590 } 10591 case Stmt::ConditionalOperatorClass: { 10592 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 10593 if (const Expr *lhs = cond->getLHS()) 10594 CheckArrayAccess(lhs); 10595 if (const Expr *rhs = cond->getRHS()) 10596 CheckArrayAccess(rhs); 10597 return; 10598 } 10599 default: 10600 return; 10601 } 10602 } 10603 } 10604 10605 //===--- CHECK: Objective-C retain cycles ----------------------------------// 10606 10607 namespace { 10608 struct RetainCycleOwner { 10609 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 10610 VarDecl *Variable; 10611 SourceRange Range; 10612 SourceLocation Loc; 10613 bool Indirect; 10614 10615 void setLocsFrom(Expr *e) { 10616 Loc = e->getExprLoc(); 10617 Range = e->getSourceRange(); 10618 } 10619 }; 10620 } // end anonymous namespace 10621 10622 /// Consider whether capturing the given variable can possibly lead to 10623 /// a retain cycle. 10624 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 10625 // In ARC, it's captured strongly iff the variable has __strong 10626 // lifetime. In MRR, it's captured strongly if the variable is 10627 // __block and has an appropriate type. 10628 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 10629 return false; 10630 10631 owner.Variable = var; 10632 if (ref) 10633 owner.setLocsFrom(ref); 10634 return true; 10635 } 10636 10637 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 10638 while (true) { 10639 e = e->IgnoreParens(); 10640 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 10641 switch (cast->getCastKind()) { 10642 case CK_BitCast: 10643 case CK_LValueBitCast: 10644 case CK_LValueToRValue: 10645 case CK_ARCReclaimReturnedObject: 10646 e = cast->getSubExpr(); 10647 continue; 10648 10649 default: 10650 return false; 10651 } 10652 } 10653 10654 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 10655 ObjCIvarDecl *ivar = ref->getDecl(); 10656 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 10657 return false; 10658 10659 // Try to find a retain cycle in the base. 10660 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 10661 return false; 10662 10663 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 10664 owner.Indirect = true; 10665 return true; 10666 } 10667 10668 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 10669 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 10670 if (!var) return false; 10671 return considerVariable(var, ref, owner); 10672 } 10673 10674 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 10675 if (member->isArrow()) return false; 10676 10677 // Don't count this as an indirect ownership. 10678 e = member->getBase(); 10679 continue; 10680 } 10681 10682 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 10683 // Only pay attention to pseudo-objects on property references. 10684 ObjCPropertyRefExpr *pre 10685 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 10686 ->IgnoreParens()); 10687 if (!pre) return false; 10688 if (pre->isImplicitProperty()) return false; 10689 ObjCPropertyDecl *property = pre->getExplicitProperty(); 10690 if (!property->isRetaining() && 10691 !(property->getPropertyIvarDecl() && 10692 property->getPropertyIvarDecl()->getType() 10693 .getObjCLifetime() == Qualifiers::OCL_Strong)) 10694 return false; 10695 10696 owner.Indirect = true; 10697 if (pre->isSuperReceiver()) { 10698 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 10699 if (!owner.Variable) 10700 return false; 10701 owner.Loc = pre->getLocation(); 10702 owner.Range = pre->getSourceRange(); 10703 return true; 10704 } 10705 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 10706 ->getSourceExpr()); 10707 continue; 10708 } 10709 10710 // Array ivars? 10711 10712 return false; 10713 } 10714 } 10715 10716 namespace { 10717 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 10718 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 10719 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 10720 Context(Context), Variable(variable), Capturer(nullptr), 10721 VarWillBeReased(false) {} 10722 ASTContext &Context; 10723 VarDecl *Variable; 10724 Expr *Capturer; 10725 bool VarWillBeReased; 10726 10727 void VisitDeclRefExpr(DeclRefExpr *ref) { 10728 if (ref->getDecl() == Variable && !Capturer) 10729 Capturer = ref; 10730 } 10731 10732 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 10733 if (Capturer) return; 10734 Visit(ref->getBase()); 10735 if (Capturer && ref->isFreeIvar()) 10736 Capturer = ref; 10737 } 10738 10739 void VisitBlockExpr(BlockExpr *block) { 10740 // Look inside nested blocks 10741 if (block->getBlockDecl()->capturesVariable(Variable)) 10742 Visit(block->getBlockDecl()->getBody()); 10743 } 10744 10745 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 10746 if (Capturer) return; 10747 if (OVE->getSourceExpr()) 10748 Visit(OVE->getSourceExpr()); 10749 } 10750 void VisitBinaryOperator(BinaryOperator *BinOp) { 10751 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 10752 return; 10753 Expr *LHS = BinOp->getLHS(); 10754 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 10755 if (DRE->getDecl() != Variable) 10756 return; 10757 if (Expr *RHS = BinOp->getRHS()) { 10758 RHS = RHS->IgnoreParenCasts(); 10759 llvm::APSInt Value; 10760 VarWillBeReased = 10761 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 10762 } 10763 } 10764 } 10765 }; 10766 } // end anonymous namespace 10767 10768 /// Check whether the given argument is a block which captures a 10769 /// variable. 10770 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 10771 assert(owner.Variable && owner.Loc.isValid()); 10772 10773 e = e->IgnoreParenCasts(); 10774 10775 // Look through [^{...} copy] and Block_copy(^{...}). 10776 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 10777 Selector Cmd = ME->getSelector(); 10778 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 10779 e = ME->getInstanceReceiver(); 10780 if (!e) 10781 return nullptr; 10782 e = e->IgnoreParenCasts(); 10783 } 10784 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 10785 if (CE->getNumArgs() == 1) { 10786 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 10787 if (Fn) { 10788 const IdentifierInfo *FnI = Fn->getIdentifier(); 10789 if (FnI && FnI->isStr("_Block_copy")) { 10790 e = CE->getArg(0)->IgnoreParenCasts(); 10791 } 10792 } 10793 } 10794 } 10795 10796 BlockExpr *block = dyn_cast<BlockExpr>(e); 10797 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 10798 return nullptr; 10799 10800 FindCaptureVisitor visitor(S.Context, owner.Variable); 10801 visitor.Visit(block->getBlockDecl()->getBody()); 10802 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 10803 } 10804 10805 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 10806 RetainCycleOwner &owner) { 10807 assert(capturer); 10808 assert(owner.Variable && owner.Loc.isValid()); 10809 10810 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 10811 << owner.Variable << capturer->getSourceRange(); 10812 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 10813 << owner.Indirect << owner.Range; 10814 } 10815 10816 /// Check for a keyword selector that starts with the word 'add' or 10817 /// 'set'. 10818 static bool isSetterLikeSelector(Selector sel) { 10819 if (sel.isUnarySelector()) return false; 10820 10821 StringRef str = sel.getNameForSlot(0); 10822 while (!str.empty() && str.front() == '_') str = str.substr(1); 10823 if (str.startswith("set")) 10824 str = str.substr(3); 10825 else if (str.startswith("add")) { 10826 // Specially whitelist 'addOperationWithBlock:'. 10827 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 10828 return false; 10829 str = str.substr(3); 10830 } 10831 else 10832 return false; 10833 10834 if (str.empty()) return true; 10835 return !isLowercase(str.front()); 10836 } 10837 10838 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 10839 ObjCMessageExpr *Message) { 10840 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 10841 Message->getReceiverInterface(), 10842 NSAPI::ClassId_NSMutableArray); 10843 if (!IsMutableArray) { 10844 return None; 10845 } 10846 10847 Selector Sel = Message->getSelector(); 10848 10849 Optional<NSAPI::NSArrayMethodKind> MKOpt = 10850 S.NSAPIObj->getNSArrayMethodKind(Sel); 10851 if (!MKOpt) { 10852 return None; 10853 } 10854 10855 NSAPI::NSArrayMethodKind MK = *MKOpt; 10856 10857 switch (MK) { 10858 case NSAPI::NSMutableArr_addObject: 10859 case NSAPI::NSMutableArr_insertObjectAtIndex: 10860 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 10861 return 0; 10862 case NSAPI::NSMutableArr_replaceObjectAtIndex: 10863 return 1; 10864 10865 default: 10866 return None; 10867 } 10868 10869 return None; 10870 } 10871 10872 static 10873 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 10874 ObjCMessageExpr *Message) { 10875 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 10876 Message->getReceiverInterface(), 10877 NSAPI::ClassId_NSMutableDictionary); 10878 if (!IsMutableDictionary) { 10879 return None; 10880 } 10881 10882 Selector Sel = Message->getSelector(); 10883 10884 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 10885 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 10886 if (!MKOpt) { 10887 return None; 10888 } 10889 10890 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 10891 10892 switch (MK) { 10893 case NSAPI::NSMutableDict_setObjectForKey: 10894 case NSAPI::NSMutableDict_setValueForKey: 10895 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 10896 return 0; 10897 10898 default: 10899 return None; 10900 } 10901 10902 return None; 10903 } 10904 10905 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 10906 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 10907 Message->getReceiverInterface(), 10908 NSAPI::ClassId_NSMutableSet); 10909 10910 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 10911 Message->getReceiverInterface(), 10912 NSAPI::ClassId_NSMutableOrderedSet); 10913 if (!IsMutableSet && !IsMutableOrderedSet) { 10914 return None; 10915 } 10916 10917 Selector Sel = Message->getSelector(); 10918 10919 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 10920 if (!MKOpt) { 10921 return None; 10922 } 10923 10924 NSAPI::NSSetMethodKind MK = *MKOpt; 10925 10926 switch (MK) { 10927 case NSAPI::NSMutableSet_addObject: 10928 case NSAPI::NSOrderedSet_setObjectAtIndex: 10929 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 10930 case NSAPI::NSOrderedSet_insertObjectAtIndex: 10931 return 0; 10932 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 10933 return 1; 10934 } 10935 10936 return None; 10937 } 10938 10939 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 10940 if (!Message->isInstanceMessage()) { 10941 return; 10942 } 10943 10944 Optional<int> ArgOpt; 10945 10946 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 10947 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 10948 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 10949 return; 10950 } 10951 10952 int ArgIndex = *ArgOpt; 10953 10954 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 10955 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 10956 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 10957 } 10958 10959 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 10960 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 10961 if (ArgRE->isObjCSelfExpr()) { 10962 Diag(Message->getSourceRange().getBegin(), 10963 diag::warn_objc_circular_container) 10964 << ArgRE->getDecl()->getName() << StringRef("super"); 10965 } 10966 } 10967 } else { 10968 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 10969 10970 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 10971 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 10972 } 10973 10974 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 10975 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 10976 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 10977 ValueDecl *Decl = ReceiverRE->getDecl(); 10978 Diag(Message->getSourceRange().getBegin(), 10979 diag::warn_objc_circular_container) 10980 << Decl->getName() << Decl->getName(); 10981 if (!ArgRE->isObjCSelfExpr()) { 10982 Diag(Decl->getLocation(), 10983 diag::note_objc_circular_container_declared_here) 10984 << Decl->getName(); 10985 } 10986 } 10987 } 10988 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 10989 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 10990 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 10991 ObjCIvarDecl *Decl = IvarRE->getDecl(); 10992 Diag(Message->getSourceRange().getBegin(), 10993 diag::warn_objc_circular_container) 10994 << Decl->getName() << Decl->getName(); 10995 Diag(Decl->getLocation(), 10996 diag::note_objc_circular_container_declared_here) 10997 << Decl->getName(); 10998 } 10999 } 11000 } 11001 } 11002 } 11003 11004 /// Check a message send to see if it's likely to cause a retain cycle. 11005 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 11006 // Only check instance methods whose selector looks like a setter. 11007 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 11008 return; 11009 11010 // Try to find a variable that the receiver is strongly owned by. 11011 RetainCycleOwner owner; 11012 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 11013 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 11014 return; 11015 } else { 11016 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 11017 owner.Variable = getCurMethodDecl()->getSelfDecl(); 11018 owner.Loc = msg->getSuperLoc(); 11019 owner.Range = msg->getSuperLoc(); 11020 } 11021 11022 // Check whether the receiver is captured by any of the arguments. 11023 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 11024 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 11025 return diagnoseRetainCycle(*this, capturer, owner); 11026 } 11027 11028 /// Check a property assign to see if it's likely to cause a retain cycle. 11029 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 11030 RetainCycleOwner owner; 11031 if (!findRetainCycleOwner(*this, receiver, owner)) 11032 return; 11033 11034 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 11035 diagnoseRetainCycle(*this, capturer, owner); 11036 } 11037 11038 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 11039 RetainCycleOwner Owner; 11040 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 11041 return; 11042 11043 // Because we don't have an expression for the variable, we have to set the 11044 // location explicitly here. 11045 Owner.Loc = Var->getLocation(); 11046 Owner.Range = Var->getSourceRange(); 11047 11048 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 11049 diagnoseRetainCycle(*this, Capturer, Owner); 11050 } 11051 11052 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 11053 Expr *RHS, bool isProperty) { 11054 // Check if RHS is an Objective-C object literal, which also can get 11055 // immediately zapped in a weak reference. Note that we explicitly 11056 // allow ObjCStringLiterals, since those are designed to never really die. 11057 RHS = RHS->IgnoreParenImpCasts(); 11058 11059 // This enum needs to match with the 'select' in 11060 // warn_objc_arc_literal_assign (off-by-1). 11061 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 11062 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 11063 return false; 11064 11065 S.Diag(Loc, diag::warn_arc_literal_assign) 11066 << (unsigned) Kind 11067 << (isProperty ? 0 : 1) 11068 << RHS->getSourceRange(); 11069 11070 return true; 11071 } 11072 11073 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 11074 Qualifiers::ObjCLifetime LT, 11075 Expr *RHS, bool isProperty) { 11076 // Strip off any implicit cast added to get to the one ARC-specific. 11077 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11078 if (cast->getCastKind() == CK_ARCConsumeObject) { 11079 S.Diag(Loc, diag::warn_arc_retained_assign) 11080 << (LT == Qualifiers::OCL_ExplicitNone) 11081 << (isProperty ? 0 : 1) 11082 << RHS->getSourceRange(); 11083 return true; 11084 } 11085 RHS = cast->getSubExpr(); 11086 } 11087 11088 if (LT == Qualifiers::OCL_Weak && 11089 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 11090 return true; 11091 11092 return false; 11093 } 11094 11095 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 11096 QualType LHS, Expr *RHS) { 11097 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 11098 11099 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 11100 return false; 11101 11102 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 11103 return true; 11104 11105 return false; 11106 } 11107 11108 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 11109 Expr *LHS, Expr *RHS) { 11110 QualType LHSType; 11111 // PropertyRef on LHS type need be directly obtained from 11112 // its declaration as it has a PseudoType. 11113 ObjCPropertyRefExpr *PRE 11114 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 11115 if (PRE && !PRE->isImplicitProperty()) { 11116 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11117 if (PD) 11118 LHSType = PD->getType(); 11119 } 11120 11121 if (LHSType.isNull()) 11122 LHSType = LHS->getType(); 11123 11124 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 11125 11126 if (LT == Qualifiers::OCL_Weak) { 11127 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 11128 getCurFunction()->markSafeWeakUse(LHS); 11129 } 11130 11131 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 11132 return; 11133 11134 // FIXME. Check for other life times. 11135 if (LT != Qualifiers::OCL_None) 11136 return; 11137 11138 if (PRE) { 11139 if (PRE->isImplicitProperty()) 11140 return; 11141 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11142 if (!PD) 11143 return; 11144 11145 unsigned Attributes = PD->getPropertyAttributes(); 11146 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 11147 // when 'assign' attribute was not explicitly specified 11148 // by user, ignore it and rely on property type itself 11149 // for lifetime info. 11150 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 11151 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 11152 LHSType->isObjCRetainableType()) 11153 return; 11154 11155 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11156 if (cast->getCastKind() == CK_ARCConsumeObject) { 11157 Diag(Loc, diag::warn_arc_retained_property_assign) 11158 << RHS->getSourceRange(); 11159 return; 11160 } 11161 RHS = cast->getSubExpr(); 11162 } 11163 } 11164 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 11165 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 11166 return; 11167 } 11168 } 11169 } 11170 11171 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 11172 11173 namespace { 11174 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 11175 SourceLocation StmtLoc, 11176 const NullStmt *Body) { 11177 // Do not warn if the body is a macro that expands to nothing, e.g: 11178 // 11179 // #define CALL(x) 11180 // if (condition) 11181 // CALL(0); 11182 // 11183 if (Body->hasLeadingEmptyMacro()) 11184 return false; 11185 11186 // Get line numbers of statement and body. 11187 bool StmtLineInvalid; 11188 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 11189 &StmtLineInvalid); 11190 if (StmtLineInvalid) 11191 return false; 11192 11193 bool BodyLineInvalid; 11194 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 11195 &BodyLineInvalid); 11196 if (BodyLineInvalid) 11197 return false; 11198 11199 // Warn if null statement and body are on the same line. 11200 if (StmtLine != BodyLine) 11201 return false; 11202 11203 return true; 11204 } 11205 } // end anonymous namespace 11206 11207 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 11208 const Stmt *Body, 11209 unsigned DiagID) { 11210 // Since this is a syntactic check, don't emit diagnostic for template 11211 // instantiations, this just adds noise. 11212 if (CurrentInstantiationScope) 11213 return; 11214 11215 // The body should be a null statement. 11216 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11217 if (!NBody) 11218 return; 11219 11220 // Do the usual checks. 11221 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11222 return; 11223 11224 Diag(NBody->getSemiLoc(), DiagID); 11225 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11226 } 11227 11228 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 11229 const Stmt *PossibleBody) { 11230 assert(!CurrentInstantiationScope); // Ensured by caller 11231 11232 SourceLocation StmtLoc; 11233 const Stmt *Body; 11234 unsigned DiagID; 11235 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 11236 StmtLoc = FS->getRParenLoc(); 11237 Body = FS->getBody(); 11238 DiagID = diag::warn_empty_for_body; 11239 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 11240 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 11241 Body = WS->getBody(); 11242 DiagID = diag::warn_empty_while_body; 11243 } else 11244 return; // Neither `for' nor `while'. 11245 11246 // The body should be a null statement. 11247 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11248 if (!NBody) 11249 return; 11250 11251 // Skip expensive checks if diagnostic is disabled. 11252 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 11253 return; 11254 11255 // Do the usual checks. 11256 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11257 return; 11258 11259 // `for(...);' and `while(...);' are popular idioms, so in order to keep 11260 // noise level low, emit diagnostics only if for/while is followed by a 11261 // CompoundStmt, e.g.: 11262 // for (int i = 0; i < n; i++); 11263 // { 11264 // a(i); 11265 // } 11266 // or if for/while is followed by a statement with more indentation 11267 // than for/while itself: 11268 // for (int i = 0; i < n; i++); 11269 // a(i); 11270 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 11271 if (!ProbableTypo) { 11272 bool BodyColInvalid; 11273 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 11274 PossibleBody->getLocStart(), 11275 &BodyColInvalid); 11276 if (BodyColInvalid) 11277 return; 11278 11279 bool StmtColInvalid; 11280 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 11281 S->getLocStart(), 11282 &StmtColInvalid); 11283 if (StmtColInvalid) 11284 return; 11285 11286 if (BodyCol > StmtCol) 11287 ProbableTypo = true; 11288 } 11289 11290 if (ProbableTypo) { 11291 Diag(NBody->getSemiLoc(), DiagID); 11292 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11293 } 11294 } 11295 11296 //===--- CHECK: Warn on self move with std::move. -------------------------===// 11297 11298 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 11299 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 11300 SourceLocation OpLoc) { 11301 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 11302 return; 11303 11304 if (!ActiveTemplateInstantiations.empty()) 11305 return; 11306 11307 // Strip parens and casts away. 11308 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11309 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11310 11311 // Check for a call expression 11312 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 11313 if (!CE || CE->getNumArgs() != 1) 11314 return; 11315 11316 // Check for a call to std::move 11317 const FunctionDecl *FD = CE->getDirectCallee(); 11318 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() || 11319 !FD->getIdentifier()->isStr("move")) 11320 return; 11321 11322 // Get argument from std::move 11323 RHSExpr = CE->getArg(0); 11324 11325 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11326 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11327 11328 // Two DeclRefExpr's, check that the decls are the same. 11329 if (LHSDeclRef && RHSDeclRef) { 11330 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11331 return; 11332 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11333 RHSDeclRef->getDecl()->getCanonicalDecl()) 11334 return; 11335 11336 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11337 << LHSExpr->getSourceRange() 11338 << RHSExpr->getSourceRange(); 11339 return; 11340 } 11341 11342 // Member variables require a different approach to check for self moves. 11343 // MemberExpr's are the same if every nested MemberExpr refers to the same 11344 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 11345 // the base Expr's are CXXThisExpr's. 11346 const Expr *LHSBase = LHSExpr; 11347 const Expr *RHSBase = RHSExpr; 11348 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 11349 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 11350 if (!LHSME || !RHSME) 11351 return; 11352 11353 while (LHSME && RHSME) { 11354 if (LHSME->getMemberDecl()->getCanonicalDecl() != 11355 RHSME->getMemberDecl()->getCanonicalDecl()) 11356 return; 11357 11358 LHSBase = LHSME->getBase(); 11359 RHSBase = RHSME->getBase(); 11360 LHSME = dyn_cast<MemberExpr>(LHSBase); 11361 RHSME = dyn_cast<MemberExpr>(RHSBase); 11362 } 11363 11364 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 11365 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 11366 if (LHSDeclRef && RHSDeclRef) { 11367 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11368 return; 11369 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11370 RHSDeclRef->getDecl()->getCanonicalDecl()) 11371 return; 11372 11373 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11374 << LHSExpr->getSourceRange() 11375 << RHSExpr->getSourceRange(); 11376 return; 11377 } 11378 11379 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 11380 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11381 << LHSExpr->getSourceRange() 11382 << RHSExpr->getSourceRange(); 11383 } 11384 11385 //===--- Layout compatibility ----------------------------------------------// 11386 11387 namespace { 11388 11389 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 11390 11391 /// \brief Check if two enumeration types are layout-compatible. 11392 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 11393 // C++11 [dcl.enum] p8: 11394 // Two enumeration types are layout-compatible if they have the same 11395 // underlying type. 11396 return ED1->isComplete() && ED2->isComplete() && 11397 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 11398 } 11399 11400 /// \brief Check if two fields are layout-compatible. 11401 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 11402 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 11403 return false; 11404 11405 if (Field1->isBitField() != Field2->isBitField()) 11406 return false; 11407 11408 if (Field1->isBitField()) { 11409 // Make sure that the bit-fields are the same length. 11410 unsigned Bits1 = Field1->getBitWidthValue(C); 11411 unsigned Bits2 = Field2->getBitWidthValue(C); 11412 11413 if (Bits1 != Bits2) 11414 return false; 11415 } 11416 11417 return true; 11418 } 11419 11420 /// \brief Check if two standard-layout structs are layout-compatible. 11421 /// (C++11 [class.mem] p17) 11422 bool isLayoutCompatibleStruct(ASTContext &C, 11423 RecordDecl *RD1, 11424 RecordDecl *RD2) { 11425 // If both records are C++ classes, check that base classes match. 11426 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 11427 // If one of records is a CXXRecordDecl we are in C++ mode, 11428 // thus the other one is a CXXRecordDecl, too. 11429 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 11430 // Check number of base classes. 11431 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 11432 return false; 11433 11434 // Check the base classes. 11435 for (CXXRecordDecl::base_class_const_iterator 11436 Base1 = D1CXX->bases_begin(), 11437 BaseEnd1 = D1CXX->bases_end(), 11438 Base2 = D2CXX->bases_begin(); 11439 Base1 != BaseEnd1; 11440 ++Base1, ++Base2) { 11441 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 11442 return false; 11443 } 11444 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 11445 // If only RD2 is a C++ class, it should have zero base classes. 11446 if (D2CXX->getNumBases() > 0) 11447 return false; 11448 } 11449 11450 // Check the fields. 11451 RecordDecl::field_iterator Field2 = RD2->field_begin(), 11452 Field2End = RD2->field_end(), 11453 Field1 = RD1->field_begin(), 11454 Field1End = RD1->field_end(); 11455 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 11456 if (!isLayoutCompatible(C, *Field1, *Field2)) 11457 return false; 11458 } 11459 if (Field1 != Field1End || Field2 != Field2End) 11460 return false; 11461 11462 return true; 11463 } 11464 11465 /// \brief Check if two standard-layout unions are layout-compatible. 11466 /// (C++11 [class.mem] p18) 11467 bool isLayoutCompatibleUnion(ASTContext &C, 11468 RecordDecl *RD1, 11469 RecordDecl *RD2) { 11470 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 11471 for (auto *Field2 : RD2->fields()) 11472 UnmatchedFields.insert(Field2); 11473 11474 for (auto *Field1 : RD1->fields()) { 11475 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 11476 I = UnmatchedFields.begin(), 11477 E = UnmatchedFields.end(); 11478 11479 for ( ; I != E; ++I) { 11480 if (isLayoutCompatible(C, Field1, *I)) { 11481 bool Result = UnmatchedFields.erase(*I); 11482 (void) Result; 11483 assert(Result); 11484 break; 11485 } 11486 } 11487 if (I == E) 11488 return false; 11489 } 11490 11491 return UnmatchedFields.empty(); 11492 } 11493 11494 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 11495 if (RD1->isUnion() != RD2->isUnion()) 11496 return false; 11497 11498 if (RD1->isUnion()) 11499 return isLayoutCompatibleUnion(C, RD1, RD2); 11500 else 11501 return isLayoutCompatibleStruct(C, RD1, RD2); 11502 } 11503 11504 /// \brief Check if two types are layout-compatible in C++11 sense. 11505 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 11506 if (T1.isNull() || T2.isNull()) 11507 return false; 11508 11509 // C++11 [basic.types] p11: 11510 // If two types T1 and T2 are the same type, then T1 and T2 are 11511 // layout-compatible types. 11512 if (C.hasSameType(T1, T2)) 11513 return true; 11514 11515 T1 = T1.getCanonicalType().getUnqualifiedType(); 11516 T2 = T2.getCanonicalType().getUnqualifiedType(); 11517 11518 const Type::TypeClass TC1 = T1->getTypeClass(); 11519 const Type::TypeClass TC2 = T2->getTypeClass(); 11520 11521 if (TC1 != TC2) 11522 return false; 11523 11524 if (TC1 == Type::Enum) { 11525 return isLayoutCompatible(C, 11526 cast<EnumType>(T1)->getDecl(), 11527 cast<EnumType>(T2)->getDecl()); 11528 } else if (TC1 == Type::Record) { 11529 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 11530 return false; 11531 11532 return isLayoutCompatible(C, 11533 cast<RecordType>(T1)->getDecl(), 11534 cast<RecordType>(T2)->getDecl()); 11535 } 11536 11537 return false; 11538 } 11539 } // end anonymous namespace 11540 11541 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 11542 11543 namespace { 11544 /// \brief Given a type tag expression find the type tag itself. 11545 /// 11546 /// \param TypeExpr Type tag expression, as it appears in user's code. 11547 /// 11548 /// \param VD Declaration of an identifier that appears in a type tag. 11549 /// 11550 /// \param MagicValue Type tag magic value. 11551 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 11552 const ValueDecl **VD, uint64_t *MagicValue) { 11553 while(true) { 11554 if (!TypeExpr) 11555 return false; 11556 11557 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 11558 11559 switch (TypeExpr->getStmtClass()) { 11560 case Stmt::UnaryOperatorClass: { 11561 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 11562 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 11563 TypeExpr = UO->getSubExpr(); 11564 continue; 11565 } 11566 return false; 11567 } 11568 11569 case Stmt::DeclRefExprClass: { 11570 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 11571 *VD = DRE->getDecl(); 11572 return true; 11573 } 11574 11575 case Stmt::IntegerLiteralClass: { 11576 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 11577 llvm::APInt MagicValueAPInt = IL->getValue(); 11578 if (MagicValueAPInt.getActiveBits() <= 64) { 11579 *MagicValue = MagicValueAPInt.getZExtValue(); 11580 return true; 11581 } else 11582 return false; 11583 } 11584 11585 case Stmt::BinaryConditionalOperatorClass: 11586 case Stmt::ConditionalOperatorClass: { 11587 const AbstractConditionalOperator *ACO = 11588 cast<AbstractConditionalOperator>(TypeExpr); 11589 bool Result; 11590 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 11591 if (Result) 11592 TypeExpr = ACO->getTrueExpr(); 11593 else 11594 TypeExpr = ACO->getFalseExpr(); 11595 continue; 11596 } 11597 return false; 11598 } 11599 11600 case Stmt::BinaryOperatorClass: { 11601 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 11602 if (BO->getOpcode() == BO_Comma) { 11603 TypeExpr = BO->getRHS(); 11604 continue; 11605 } 11606 return false; 11607 } 11608 11609 default: 11610 return false; 11611 } 11612 } 11613 } 11614 11615 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 11616 /// 11617 /// \param TypeExpr Expression that specifies a type tag. 11618 /// 11619 /// \param MagicValues Registered magic values. 11620 /// 11621 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 11622 /// kind. 11623 /// 11624 /// \param TypeInfo Information about the corresponding C type. 11625 /// 11626 /// \returns true if the corresponding C type was found. 11627 bool GetMatchingCType( 11628 const IdentifierInfo *ArgumentKind, 11629 const Expr *TypeExpr, const ASTContext &Ctx, 11630 const llvm::DenseMap<Sema::TypeTagMagicValue, 11631 Sema::TypeTagData> *MagicValues, 11632 bool &FoundWrongKind, 11633 Sema::TypeTagData &TypeInfo) { 11634 FoundWrongKind = false; 11635 11636 // Variable declaration that has type_tag_for_datatype attribute. 11637 const ValueDecl *VD = nullptr; 11638 11639 uint64_t MagicValue; 11640 11641 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 11642 return false; 11643 11644 if (VD) { 11645 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 11646 if (I->getArgumentKind() != ArgumentKind) { 11647 FoundWrongKind = true; 11648 return false; 11649 } 11650 TypeInfo.Type = I->getMatchingCType(); 11651 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 11652 TypeInfo.MustBeNull = I->getMustBeNull(); 11653 return true; 11654 } 11655 return false; 11656 } 11657 11658 if (!MagicValues) 11659 return false; 11660 11661 llvm::DenseMap<Sema::TypeTagMagicValue, 11662 Sema::TypeTagData>::const_iterator I = 11663 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 11664 if (I == MagicValues->end()) 11665 return false; 11666 11667 TypeInfo = I->second; 11668 return true; 11669 } 11670 } // end anonymous namespace 11671 11672 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 11673 uint64_t MagicValue, QualType Type, 11674 bool LayoutCompatible, 11675 bool MustBeNull) { 11676 if (!TypeTagForDatatypeMagicValues) 11677 TypeTagForDatatypeMagicValues.reset( 11678 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 11679 11680 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 11681 (*TypeTagForDatatypeMagicValues)[Magic] = 11682 TypeTagData(Type, LayoutCompatible, MustBeNull); 11683 } 11684 11685 namespace { 11686 bool IsSameCharType(QualType T1, QualType T2) { 11687 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 11688 if (!BT1) 11689 return false; 11690 11691 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 11692 if (!BT2) 11693 return false; 11694 11695 BuiltinType::Kind T1Kind = BT1->getKind(); 11696 BuiltinType::Kind T2Kind = BT2->getKind(); 11697 11698 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 11699 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 11700 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 11701 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 11702 } 11703 } // end anonymous namespace 11704 11705 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 11706 const Expr * const *ExprArgs) { 11707 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 11708 bool IsPointerAttr = Attr->getIsPointer(); 11709 11710 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 11711 bool FoundWrongKind; 11712 TypeTagData TypeInfo; 11713 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 11714 TypeTagForDatatypeMagicValues.get(), 11715 FoundWrongKind, TypeInfo)) { 11716 if (FoundWrongKind) 11717 Diag(TypeTagExpr->getExprLoc(), 11718 diag::warn_type_tag_for_datatype_wrong_kind) 11719 << TypeTagExpr->getSourceRange(); 11720 return; 11721 } 11722 11723 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 11724 if (IsPointerAttr) { 11725 // Skip implicit cast of pointer to `void *' (as a function argument). 11726 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 11727 if (ICE->getType()->isVoidPointerType() && 11728 ICE->getCastKind() == CK_BitCast) 11729 ArgumentExpr = ICE->getSubExpr(); 11730 } 11731 QualType ArgumentType = ArgumentExpr->getType(); 11732 11733 // Passing a `void*' pointer shouldn't trigger a warning. 11734 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 11735 return; 11736 11737 if (TypeInfo.MustBeNull) { 11738 // Type tag with matching void type requires a null pointer. 11739 if (!ArgumentExpr->isNullPointerConstant(Context, 11740 Expr::NPC_ValueDependentIsNotNull)) { 11741 Diag(ArgumentExpr->getExprLoc(), 11742 diag::warn_type_safety_null_pointer_required) 11743 << ArgumentKind->getName() 11744 << ArgumentExpr->getSourceRange() 11745 << TypeTagExpr->getSourceRange(); 11746 } 11747 return; 11748 } 11749 11750 QualType RequiredType = TypeInfo.Type; 11751 if (IsPointerAttr) 11752 RequiredType = Context.getPointerType(RequiredType); 11753 11754 bool mismatch = false; 11755 if (!TypeInfo.LayoutCompatible) { 11756 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 11757 11758 // C++11 [basic.fundamental] p1: 11759 // Plain char, signed char, and unsigned char are three distinct types. 11760 // 11761 // But we treat plain `char' as equivalent to `signed char' or `unsigned 11762 // char' depending on the current char signedness mode. 11763 if (mismatch) 11764 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 11765 RequiredType->getPointeeType())) || 11766 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 11767 mismatch = false; 11768 } else 11769 if (IsPointerAttr) 11770 mismatch = !isLayoutCompatible(Context, 11771 ArgumentType->getPointeeType(), 11772 RequiredType->getPointeeType()); 11773 else 11774 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 11775 11776 if (mismatch) 11777 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 11778 << ArgumentType << ArgumentKind 11779 << TypeInfo.LayoutCompatible << RequiredType 11780 << ArgumentExpr->getSourceRange() 11781 << TypeTagExpr->getSourceRange(); 11782 } 11783 11784 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 11785 CharUnits Alignment) { 11786 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 11787 } 11788 11789 void Sema::DiagnoseMisalignedMembers() { 11790 for (MisalignedMember &m : MisalignedMembers) { 11791 const NamedDecl *ND = m.RD; 11792 if (ND->getName().empty()) { 11793 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 11794 ND = TD; 11795 } 11796 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 11797 << m.MD << ND << m.E->getSourceRange(); 11798 } 11799 MisalignedMembers.clear(); 11800 } 11801 11802 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 11803 E = E->IgnoreParens(); 11804 if (!T->isPointerType() && !T->isIntegerType()) 11805 return; 11806 if (isa<UnaryOperator>(E) && 11807 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 11808 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 11809 if (isa<MemberExpr>(Op)) { 11810 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 11811 MisalignedMember(Op)); 11812 if (MA != MisalignedMembers.end() && 11813 (T->isIntegerType() || 11814 (T->isPointerType() && 11815 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment))) 11816 MisalignedMembers.erase(MA); 11817 } 11818 } 11819 } 11820 11821 void Sema::RefersToMemberWithReducedAlignment( 11822 Expr *E, 11823 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 11824 Action) { 11825 const auto *ME = dyn_cast<MemberExpr>(E); 11826 if (!ME) 11827 return; 11828 11829 // For a chain of MemberExpr like "a.b.c.d" this list 11830 // will keep FieldDecl's like [d, c, b]. 11831 SmallVector<FieldDecl *, 4> ReverseMemberChain; 11832 const MemberExpr *TopME = nullptr; 11833 bool AnyIsPacked = false; 11834 do { 11835 QualType BaseType = ME->getBase()->getType(); 11836 if (ME->isArrow()) 11837 BaseType = BaseType->getPointeeType(); 11838 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 11839 11840 ValueDecl *MD = ME->getMemberDecl(); 11841 auto *FD = dyn_cast<FieldDecl>(MD); 11842 // We do not care about non-data members. 11843 if (!FD || FD->isInvalidDecl()) 11844 return; 11845 11846 AnyIsPacked = 11847 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 11848 ReverseMemberChain.push_back(FD); 11849 11850 TopME = ME; 11851 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 11852 } while (ME); 11853 assert(TopME && "We did not compute a topmost MemberExpr!"); 11854 11855 // Not the scope of this diagnostic. 11856 if (!AnyIsPacked) 11857 return; 11858 11859 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 11860 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 11861 // TODO: The innermost base of the member expression may be too complicated. 11862 // For now, just disregard these cases. This is left for future 11863 // improvement. 11864 if (!DRE && !isa<CXXThisExpr>(TopBase)) 11865 return; 11866 11867 // Alignment expected by the whole expression. 11868 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 11869 11870 // No need to do anything else with this case. 11871 if (ExpectedAlignment.isOne()) 11872 return; 11873 11874 // Synthesize offset of the whole access. 11875 CharUnits Offset; 11876 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 11877 I++) { 11878 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 11879 } 11880 11881 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 11882 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 11883 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 11884 11885 // The base expression of the innermost MemberExpr may give 11886 // stronger guarantees than the class containing the member. 11887 if (DRE && !TopME->isArrow()) { 11888 const ValueDecl *VD = DRE->getDecl(); 11889 if (!VD->getType()->isReferenceType()) 11890 CompleteObjectAlignment = 11891 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 11892 } 11893 11894 // Check if the synthesized offset fulfills the alignment. 11895 if (Offset % ExpectedAlignment != 0 || 11896 // It may fulfill the offset it but the effective alignment may still be 11897 // lower than the expected expression alignment. 11898 CompleteObjectAlignment < ExpectedAlignment) { 11899 // If this happens, we want to determine a sensible culprit of this. 11900 // Intuitively, watching the chain of member expressions from right to 11901 // left, we start with the required alignment (as required by the field 11902 // type) but some packed attribute in that chain has reduced the alignment. 11903 // It may happen that another packed structure increases it again. But if 11904 // we are here such increase has not been enough. So pointing the first 11905 // FieldDecl that either is packed or else its RecordDecl is, 11906 // seems reasonable. 11907 FieldDecl *FD = nullptr; 11908 CharUnits Alignment; 11909 for (FieldDecl *FDI : ReverseMemberChain) { 11910 if (FDI->hasAttr<PackedAttr>() || 11911 FDI->getParent()->hasAttr<PackedAttr>()) { 11912 FD = FDI; 11913 Alignment = std::min( 11914 Context.getTypeAlignInChars(FD->getType()), 11915 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 11916 break; 11917 } 11918 } 11919 assert(FD && "We did not find a packed FieldDecl!"); 11920 Action(E, FD->getParent(), FD, Alignment); 11921 } 11922 } 11923 11924 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 11925 using namespace std::placeholders; 11926 RefersToMemberWithReducedAlignment( 11927 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 11928 _2, _3, _4)); 11929 } 11930 11931