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