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