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