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