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 // Fifth argument is always passed as a pointer to clk_event_t. 455 if (!Arg4->isNullPointerConstant(S.Context, 456 Expr::NPC_ValueDependentIsNotNull) && 457 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 458 S.Diag(TheCall->getArg(4)->getLocStart(), 459 diag::err_opencl_enqueue_kernel_expected_type) 460 << S.Context.getPointerType(S.Context.OCLClkEventTy); 461 return true; 462 } 463 464 // Sixth argument is always passed as a pointer to clk_event_t. 465 if (!Arg5->isNullPointerConstant(S.Context, 466 Expr::NPC_ValueDependentIsNotNull) && 467 !(Arg5->getType()->isPointerType() && 468 Arg5->getType()->getPointeeType()->isClkEventT())) { 469 S.Diag(TheCall->getArg(5)->getLocStart(), 470 diag::err_opencl_enqueue_kernel_expected_type) 471 << S.Context.getPointerType(S.Context.OCLClkEventTy); 472 return true; 473 } 474 475 if (NumArgs == 7) 476 return false; 477 478 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 479 } 480 481 // None of the specific case has been detected, give generic error 482 S.Diag(TheCall->getLocStart(), 483 diag::err_opencl_enqueue_kernel_incorrect_args); 484 return true; 485 } 486 487 /// Returns OpenCL access qual. 488 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 489 return D->getAttr<OpenCLAccessAttr>(); 490 } 491 492 /// Returns true if pipe element type is different from the pointer. 493 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 494 const Expr *Arg0 = Call->getArg(0); 495 // First argument type should always be pipe. 496 if (!Arg0->getType()->isPipeType()) { 497 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 498 << Call->getDirectCallee() << Arg0->getSourceRange(); 499 return true; 500 } 501 OpenCLAccessAttr *AccessQual = 502 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 503 // Validates the access qualifier is compatible with the call. 504 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 505 // read_only and write_only, and assumed to be read_only if no qualifier is 506 // specified. 507 switch (Call->getDirectCallee()->getBuiltinID()) { 508 case Builtin::BIread_pipe: 509 case Builtin::BIreserve_read_pipe: 510 case Builtin::BIcommit_read_pipe: 511 case Builtin::BIwork_group_reserve_read_pipe: 512 case Builtin::BIsub_group_reserve_read_pipe: 513 case Builtin::BIwork_group_commit_read_pipe: 514 case Builtin::BIsub_group_commit_read_pipe: 515 if (!(!AccessQual || AccessQual->isReadOnly())) { 516 S.Diag(Arg0->getLocStart(), 517 diag::err_opencl_builtin_pipe_invalid_access_modifier) 518 << "read_only" << Arg0->getSourceRange(); 519 return true; 520 } 521 break; 522 case Builtin::BIwrite_pipe: 523 case Builtin::BIreserve_write_pipe: 524 case Builtin::BIcommit_write_pipe: 525 case Builtin::BIwork_group_reserve_write_pipe: 526 case Builtin::BIsub_group_reserve_write_pipe: 527 case Builtin::BIwork_group_commit_write_pipe: 528 case Builtin::BIsub_group_commit_write_pipe: 529 if (!(AccessQual && AccessQual->isWriteOnly())) { 530 S.Diag(Arg0->getLocStart(), 531 diag::err_opencl_builtin_pipe_invalid_access_modifier) 532 << "write_only" << Arg0->getSourceRange(); 533 return true; 534 } 535 break; 536 default: 537 break; 538 } 539 return false; 540 } 541 542 /// Returns true if pipe element type is different from the pointer. 543 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 544 const Expr *Arg0 = Call->getArg(0); 545 const Expr *ArgIdx = Call->getArg(Idx); 546 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 547 const QualType EltTy = PipeTy->getElementType(); 548 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 549 // The Idx argument should be a pointer and the type of the pointer and 550 // the type of pipe element should also be the same. 551 if (!ArgTy || 552 !S.Context.hasSameType( 553 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 554 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 555 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 556 << ArgIdx->getType() << ArgIdx->getSourceRange(); 557 return true; 558 } 559 return false; 560 } 561 562 // \brief Performs semantic analysis for the read/write_pipe call. 563 // \param S Reference to the semantic analyzer. 564 // \param Call A pointer to the builtin call. 565 // \return True if a semantic error has been found, false otherwise. 566 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 567 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 568 // functions have two forms. 569 switch (Call->getNumArgs()) { 570 case 2: { 571 if (checkOpenCLPipeArg(S, Call)) 572 return true; 573 // The call with 2 arguments should be 574 // read/write_pipe(pipe T, T*). 575 // Check packet type T. 576 if (checkOpenCLPipePacketType(S, Call, 1)) 577 return true; 578 } break; 579 580 case 4: { 581 if (checkOpenCLPipeArg(S, Call)) 582 return true; 583 // The call with 4 arguments should be 584 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 585 // Check reserve_id_t. 586 if (!Call->getArg(1)->getType()->isReserveIDT()) { 587 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 588 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 589 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 590 return true; 591 } 592 593 // Check the index. 594 const Expr *Arg2 = Call->getArg(2); 595 if (!Arg2->getType()->isIntegerType() && 596 !Arg2->getType()->isUnsignedIntegerType()) { 597 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 598 << Call->getDirectCallee() << S.Context.UnsignedIntTy 599 << Arg2->getType() << Arg2->getSourceRange(); 600 return true; 601 } 602 603 // Check packet type T. 604 if (checkOpenCLPipePacketType(S, Call, 3)) 605 return true; 606 } break; 607 default: 608 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) 609 << Call->getDirectCallee() << Call->getSourceRange(); 610 return true; 611 } 612 613 return false; 614 } 615 616 // \brief Performs a semantic analysis on the {work_group_/sub_group_ 617 // /_}reserve_{read/write}_pipe 618 // \param S Reference to the semantic analyzer. 619 // \param Call The call to the builtin function to be analyzed. 620 // \return True if a semantic error was found, false otherwise. 621 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 622 if (checkArgCount(S, Call, 2)) 623 return true; 624 625 if (checkOpenCLPipeArg(S, Call)) 626 return true; 627 628 // Check the reserve size. 629 if (!Call->getArg(1)->getType()->isIntegerType() && 630 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 631 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 632 << Call->getDirectCallee() << S.Context.UnsignedIntTy 633 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 634 return true; 635 } 636 637 return false; 638 } 639 640 // \brief Performs a semantic analysis on {work_group_/sub_group_ 641 // /_}commit_{read/write}_pipe 642 // \param S Reference to the semantic analyzer. 643 // \param Call The call to the builtin function to be analyzed. 644 // \return True if a semantic error was found, false otherwise. 645 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 646 if (checkArgCount(S, Call, 2)) 647 return true; 648 649 if (checkOpenCLPipeArg(S, Call)) 650 return true; 651 652 // Check reserve_id_t. 653 if (!Call->getArg(1)->getType()->isReserveIDT()) { 654 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 655 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 656 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 657 return true; 658 } 659 660 return false; 661 } 662 663 // \brief Performs a semantic analysis on the call to built-in Pipe 664 // Query Functions. 665 // \param S Reference to the semantic analyzer. 666 // \param Call The call to the builtin function to be analyzed. 667 // \return True if a semantic error was found, false otherwise. 668 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 669 if (checkArgCount(S, Call, 1)) 670 return true; 671 672 if (!Call->getArg(0)->getType()->isPipeType()) { 673 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 674 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 675 return true; 676 } 677 678 return false; 679 } 680 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions. 681 // \brief Performs semantic analysis for the to_global/local/private call. 682 // \param S Reference to the semantic analyzer. 683 // \param BuiltinID ID of the builtin function. 684 // \param Call A pointer to the builtin call. 685 // \return True if a semantic error has been found, false otherwise. 686 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 687 CallExpr *Call) { 688 if (Call->getNumArgs() != 1) { 689 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 690 << Call->getDirectCallee() << Call->getSourceRange(); 691 return true; 692 } 693 694 auto RT = Call->getArg(0)->getType(); 695 if (!RT->isPointerType() || RT->getPointeeType() 696 .getAddressSpace() == LangAS::opencl_constant) { 697 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 698 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 699 return true; 700 } 701 702 RT = RT->getPointeeType(); 703 auto Qual = RT.getQualifiers(); 704 switch (BuiltinID) { 705 case Builtin::BIto_global: 706 Qual.setAddressSpace(LangAS::opencl_global); 707 break; 708 case Builtin::BIto_local: 709 Qual.setAddressSpace(LangAS::opencl_local); 710 break; 711 default: 712 Qual.removeAddressSpace(); 713 } 714 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 715 RT.getUnqualifiedType(), Qual))); 716 717 return false; 718 } 719 720 ExprResult 721 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 722 CallExpr *TheCall) { 723 ExprResult TheCallResult(TheCall); 724 725 // Find out if any arguments are required to be integer constant expressions. 726 unsigned ICEArguments = 0; 727 ASTContext::GetBuiltinTypeError Error; 728 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 729 if (Error != ASTContext::GE_None) 730 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 731 732 // If any arguments are required to be ICE's, check and diagnose. 733 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 734 // Skip arguments not required to be ICE's. 735 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 736 737 llvm::APSInt Result; 738 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 739 return true; 740 ICEArguments &= ~(1 << ArgNo); 741 } 742 743 switch (BuiltinID) { 744 case Builtin::BI__builtin___CFStringMakeConstantString: 745 assert(TheCall->getNumArgs() == 1 && 746 "Wrong # arguments to builtin CFStringMakeConstantString"); 747 if (CheckObjCString(TheCall->getArg(0))) 748 return ExprError(); 749 break; 750 case Builtin::BI__builtin_stdarg_start: 751 case Builtin::BI__builtin_va_start: 752 if (SemaBuiltinVAStart(TheCall)) 753 return ExprError(); 754 break; 755 case Builtin::BI__va_start: { 756 switch (Context.getTargetInfo().getTriple().getArch()) { 757 case llvm::Triple::arm: 758 case llvm::Triple::thumb: 759 if (SemaBuiltinVAStartARM(TheCall)) 760 return ExprError(); 761 break; 762 default: 763 if (SemaBuiltinVAStart(TheCall)) 764 return ExprError(); 765 break; 766 } 767 break; 768 } 769 case Builtin::BI__builtin_isgreater: 770 case Builtin::BI__builtin_isgreaterequal: 771 case Builtin::BI__builtin_isless: 772 case Builtin::BI__builtin_islessequal: 773 case Builtin::BI__builtin_islessgreater: 774 case Builtin::BI__builtin_isunordered: 775 if (SemaBuiltinUnorderedCompare(TheCall)) 776 return ExprError(); 777 break; 778 case Builtin::BI__builtin_fpclassify: 779 if (SemaBuiltinFPClassification(TheCall, 6)) 780 return ExprError(); 781 break; 782 case Builtin::BI__builtin_isfinite: 783 case Builtin::BI__builtin_isinf: 784 case Builtin::BI__builtin_isinf_sign: 785 case Builtin::BI__builtin_isnan: 786 case Builtin::BI__builtin_isnormal: 787 if (SemaBuiltinFPClassification(TheCall, 1)) 788 return ExprError(); 789 break; 790 case Builtin::BI__builtin_shufflevector: 791 return SemaBuiltinShuffleVector(TheCall); 792 // TheCall will be freed by the smart pointer here, but that's fine, since 793 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 794 case Builtin::BI__builtin_prefetch: 795 if (SemaBuiltinPrefetch(TheCall)) 796 return ExprError(); 797 break; 798 case Builtin::BI__builtin_alloca_with_align: 799 if (SemaBuiltinAllocaWithAlign(TheCall)) 800 return ExprError(); 801 break; 802 case Builtin::BI__assume: 803 case Builtin::BI__builtin_assume: 804 if (SemaBuiltinAssume(TheCall)) 805 return ExprError(); 806 break; 807 case Builtin::BI__builtin_assume_aligned: 808 if (SemaBuiltinAssumeAligned(TheCall)) 809 return ExprError(); 810 break; 811 case Builtin::BI__builtin_object_size: 812 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 813 return ExprError(); 814 break; 815 case Builtin::BI__builtin_longjmp: 816 if (SemaBuiltinLongjmp(TheCall)) 817 return ExprError(); 818 break; 819 case Builtin::BI__builtin_setjmp: 820 if (SemaBuiltinSetjmp(TheCall)) 821 return ExprError(); 822 break; 823 case Builtin::BI_setjmp: 824 case Builtin::BI_setjmpex: 825 if (checkArgCount(*this, TheCall, 1)) 826 return true; 827 break; 828 829 case Builtin::BI__builtin_classify_type: 830 if (checkArgCount(*this, TheCall, 1)) return true; 831 TheCall->setType(Context.IntTy); 832 break; 833 case Builtin::BI__builtin_constant_p: 834 if (checkArgCount(*this, TheCall, 1)) return true; 835 TheCall->setType(Context.IntTy); 836 break; 837 case Builtin::BI__sync_fetch_and_add: 838 case Builtin::BI__sync_fetch_and_add_1: 839 case Builtin::BI__sync_fetch_and_add_2: 840 case Builtin::BI__sync_fetch_and_add_4: 841 case Builtin::BI__sync_fetch_and_add_8: 842 case Builtin::BI__sync_fetch_and_add_16: 843 case Builtin::BI__sync_fetch_and_sub: 844 case Builtin::BI__sync_fetch_and_sub_1: 845 case Builtin::BI__sync_fetch_and_sub_2: 846 case Builtin::BI__sync_fetch_and_sub_4: 847 case Builtin::BI__sync_fetch_and_sub_8: 848 case Builtin::BI__sync_fetch_and_sub_16: 849 case Builtin::BI__sync_fetch_and_or: 850 case Builtin::BI__sync_fetch_and_or_1: 851 case Builtin::BI__sync_fetch_and_or_2: 852 case Builtin::BI__sync_fetch_and_or_4: 853 case Builtin::BI__sync_fetch_and_or_8: 854 case Builtin::BI__sync_fetch_and_or_16: 855 case Builtin::BI__sync_fetch_and_and: 856 case Builtin::BI__sync_fetch_and_and_1: 857 case Builtin::BI__sync_fetch_and_and_2: 858 case Builtin::BI__sync_fetch_and_and_4: 859 case Builtin::BI__sync_fetch_and_and_8: 860 case Builtin::BI__sync_fetch_and_and_16: 861 case Builtin::BI__sync_fetch_and_xor: 862 case Builtin::BI__sync_fetch_and_xor_1: 863 case Builtin::BI__sync_fetch_and_xor_2: 864 case Builtin::BI__sync_fetch_and_xor_4: 865 case Builtin::BI__sync_fetch_and_xor_8: 866 case Builtin::BI__sync_fetch_and_xor_16: 867 case Builtin::BI__sync_fetch_and_nand: 868 case Builtin::BI__sync_fetch_and_nand_1: 869 case Builtin::BI__sync_fetch_and_nand_2: 870 case Builtin::BI__sync_fetch_and_nand_4: 871 case Builtin::BI__sync_fetch_and_nand_8: 872 case Builtin::BI__sync_fetch_and_nand_16: 873 case Builtin::BI__sync_add_and_fetch: 874 case Builtin::BI__sync_add_and_fetch_1: 875 case Builtin::BI__sync_add_and_fetch_2: 876 case Builtin::BI__sync_add_and_fetch_4: 877 case Builtin::BI__sync_add_and_fetch_8: 878 case Builtin::BI__sync_add_and_fetch_16: 879 case Builtin::BI__sync_sub_and_fetch: 880 case Builtin::BI__sync_sub_and_fetch_1: 881 case Builtin::BI__sync_sub_and_fetch_2: 882 case Builtin::BI__sync_sub_and_fetch_4: 883 case Builtin::BI__sync_sub_and_fetch_8: 884 case Builtin::BI__sync_sub_and_fetch_16: 885 case Builtin::BI__sync_and_and_fetch: 886 case Builtin::BI__sync_and_and_fetch_1: 887 case Builtin::BI__sync_and_and_fetch_2: 888 case Builtin::BI__sync_and_and_fetch_4: 889 case Builtin::BI__sync_and_and_fetch_8: 890 case Builtin::BI__sync_and_and_fetch_16: 891 case Builtin::BI__sync_or_and_fetch: 892 case Builtin::BI__sync_or_and_fetch_1: 893 case Builtin::BI__sync_or_and_fetch_2: 894 case Builtin::BI__sync_or_and_fetch_4: 895 case Builtin::BI__sync_or_and_fetch_8: 896 case Builtin::BI__sync_or_and_fetch_16: 897 case Builtin::BI__sync_xor_and_fetch: 898 case Builtin::BI__sync_xor_and_fetch_1: 899 case Builtin::BI__sync_xor_and_fetch_2: 900 case Builtin::BI__sync_xor_and_fetch_4: 901 case Builtin::BI__sync_xor_and_fetch_8: 902 case Builtin::BI__sync_xor_and_fetch_16: 903 case Builtin::BI__sync_nand_and_fetch: 904 case Builtin::BI__sync_nand_and_fetch_1: 905 case Builtin::BI__sync_nand_and_fetch_2: 906 case Builtin::BI__sync_nand_and_fetch_4: 907 case Builtin::BI__sync_nand_and_fetch_8: 908 case Builtin::BI__sync_nand_and_fetch_16: 909 case Builtin::BI__sync_val_compare_and_swap: 910 case Builtin::BI__sync_val_compare_and_swap_1: 911 case Builtin::BI__sync_val_compare_and_swap_2: 912 case Builtin::BI__sync_val_compare_and_swap_4: 913 case Builtin::BI__sync_val_compare_and_swap_8: 914 case Builtin::BI__sync_val_compare_and_swap_16: 915 case Builtin::BI__sync_bool_compare_and_swap: 916 case Builtin::BI__sync_bool_compare_and_swap_1: 917 case Builtin::BI__sync_bool_compare_and_swap_2: 918 case Builtin::BI__sync_bool_compare_and_swap_4: 919 case Builtin::BI__sync_bool_compare_and_swap_8: 920 case Builtin::BI__sync_bool_compare_and_swap_16: 921 case Builtin::BI__sync_lock_test_and_set: 922 case Builtin::BI__sync_lock_test_and_set_1: 923 case Builtin::BI__sync_lock_test_and_set_2: 924 case Builtin::BI__sync_lock_test_and_set_4: 925 case Builtin::BI__sync_lock_test_and_set_8: 926 case Builtin::BI__sync_lock_test_and_set_16: 927 case Builtin::BI__sync_lock_release: 928 case Builtin::BI__sync_lock_release_1: 929 case Builtin::BI__sync_lock_release_2: 930 case Builtin::BI__sync_lock_release_4: 931 case Builtin::BI__sync_lock_release_8: 932 case Builtin::BI__sync_lock_release_16: 933 case Builtin::BI__sync_swap: 934 case Builtin::BI__sync_swap_1: 935 case Builtin::BI__sync_swap_2: 936 case Builtin::BI__sync_swap_4: 937 case Builtin::BI__sync_swap_8: 938 case Builtin::BI__sync_swap_16: 939 return SemaBuiltinAtomicOverloaded(TheCallResult); 940 case Builtin::BI__builtin_nontemporal_load: 941 case Builtin::BI__builtin_nontemporal_store: 942 return SemaBuiltinNontemporalOverloaded(TheCallResult); 943 #define BUILTIN(ID, TYPE, ATTRS) 944 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 945 case Builtin::BI##ID: \ 946 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 947 #include "clang/Basic/Builtins.def" 948 case Builtin::BI__builtin_annotation: 949 if (SemaBuiltinAnnotation(*this, TheCall)) 950 return ExprError(); 951 break; 952 case Builtin::BI__builtin_addressof: 953 if (SemaBuiltinAddressof(*this, TheCall)) 954 return ExprError(); 955 break; 956 case Builtin::BI__builtin_add_overflow: 957 case Builtin::BI__builtin_sub_overflow: 958 case Builtin::BI__builtin_mul_overflow: 959 if (SemaBuiltinOverflow(*this, TheCall)) 960 return ExprError(); 961 break; 962 case Builtin::BI__builtin_operator_new: 963 case Builtin::BI__builtin_operator_delete: 964 if (!getLangOpts().CPlusPlus) { 965 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 966 << (BuiltinID == Builtin::BI__builtin_operator_new 967 ? "__builtin_operator_new" 968 : "__builtin_operator_delete") 969 << "C++"; 970 return ExprError(); 971 } 972 // CodeGen assumes it can find the global new and delete to call, 973 // so ensure that they are declared. 974 DeclareGlobalNewDelete(); 975 break; 976 977 // check secure string manipulation functions where overflows 978 // are detectable at compile time 979 case Builtin::BI__builtin___memcpy_chk: 980 case Builtin::BI__builtin___memmove_chk: 981 case Builtin::BI__builtin___memset_chk: 982 case Builtin::BI__builtin___strlcat_chk: 983 case Builtin::BI__builtin___strlcpy_chk: 984 case Builtin::BI__builtin___strncat_chk: 985 case Builtin::BI__builtin___strncpy_chk: 986 case Builtin::BI__builtin___stpncpy_chk: 987 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 988 break; 989 case Builtin::BI__builtin___memccpy_chk: 990 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 991 break; 992 case Builtin::BI__builtin___snprintf_chk: 993 case Builtin::BI__builtin___vsnprintf_chk: 994 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 995 break; 996 case Builtin::BI__builtin_call_with_static_chain: 997 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 998 return ExprError(); 999 break; 1000 case Builtin::BI__exception_code: 1001 case Builtin::BI_exception_code: 1002 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1003 diag::err_seh___except_block)) 1004 return ExprError(); 1005 break; 1006 case Builtin::BI__exception_info: 1007 case Builtin::BI_exception_info: 1008 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1009 diag::err_seh___except_filter)) 1010 return ExprError(); 1011 break; 1012 case Builtin::BI__GetExceptionInfo: 1013 if (checkArgCount(*this, TheCall, 1)) 1014 return ExprError(); 1015 1016 if (CheckCXXThrowOperand( 1017 TheCall->getLocStart(), 1018 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1019 TheCall)) 1020 return ExprError(); 1021 1022 TheCall->setType(Context.VoidPtrTy); 1023 break; 1024 // OpenCL v2.0, s6.13.16 - Pipe functions 1025 case Builtin::BIread_pipe: 1026 case Builtin::BIwrite_pipe: 1027 // Since those two functions are declared with var args, we need a semantic 1028 // check for the argument. 1029 if (SemaBuiltinRWPipe(*this, TheCall)) 1030 return ExprError(); 1031 TheCall->setType(Context.IntTy); 1032 break; 1033 case Builtin::BIreserve_read_pipe: 1034 case Builtin::BIreserve_write_pipe: 1035 case Builtin::BIwork_group_reserve_read_pipe: 1036 case Builtin::BIwork_group_reserve_write_pipe: 1037 case Builtin::BIsub_group_reserve_read_pipe: 1038 case Builtin::BIsub_group_reserve_write_pipe: 1039 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1040 return ExprError(); 1041 // Since return type of reserve_read/write_pipe built-in function is 1042 // reserve_id_t, which is not defined in the builtin def file , we used int 1043 // as return type and need to override the return type of these functions. 1044 TheCall->setType(Context.OCLReserveIDTy); 1045 break; 1046 case Builtin::BIcommit_read_pipe: 1047 case Builtin::BIcommit_write_pipe: 1048 case Builtin::BIwork_group_commit_read_pipe: 1049 case Builtin::BIwork_group_commit_write_pipe: 1050 case Builtin::BIsub_group_commit_read_pipe: 1051 case Builtin::BIsub_group_commit_write_pipe: 1052 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1053 return ExprError(); 1054 break; 1055 case Builtin::BIget_pipe_num_packets: 1056 case Builtin::BIget_pipe_max_packets: 1057 if (SemaBuiltinPipePackets(*this, TheCall)) 1058 return ExprError(); 1059 TheCall->setType(Context.UnsignedIntTy); 1060 break; 1061 case Builtin::BIto_global: 1062 case Builtin::BIto_local: 1063 case Builtin::BIto_private: 1064 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1065 return ExprError(); 1066 break; 1067 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1068 case Builtin::BIenqueue_kernel: 1069 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1070 return ExprError(); 1071 break; 1072 case Builtin::BIget_kernel_work_group_size: 1073 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1074 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1075 return ExprError(); 1076 break; 1077 case Builtin::BI__builtin_os_log_format: 1078 case Builtin::BI__builtin_os_log_format_buffer_size: 1079 if (SemaBuiltinOSLogFormat(TheCall)) { 1080 return ExprError(); 1081 } 1082 break; 1083 } 1084 1085 // Since the target specific builtins for each arch overlap, only check those 1086 // of the arch we are compiling for. 1087 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1088 switch (Context.getTargetInfo().getTriple().getArch()) { 1089 case llvm::Triple::arm: 1090 case llvm::Triple::armeb: 1091 case llvm::Triple::thumb: 1092 case llvm::Triple::thumbeb: 1093 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1094 return ExprError(); 1095 break; 1096 case llvm::Triple::aarch64: 1097 case llvm::Triple::aarch64_be: 1098 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1099 return ExprError(); 1100 break; 1101 case llvm::Triple::mips: 1102 case llvm::Triple::mipsel: 1103 case llvm::Triple::mips64: 1104 case llvm::Triple::mips64el: 1105 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1106 return ExprError(); 1107 break; 1108 case llvm::Triple::systemz: 1109 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1110 return ExprError(); 1111 break; 1112 case llvm::Triple::x86: 1113 case llvm::Triple::x86_64: 1114 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1115 return ExprError(); 1116 break; 1117 case llvm::Triple::ppc: 1118 case llvm::Triple::ppc64: 1119 case llvm::Triple::ppc64le: 1120 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1121 return ExprError(); 1122 break; 1123 default: 1124 break; 1125 } 1126 } 1127 1128 return TheCallResult; 1129 } 1130 1131 // Get the valid immediate range for the specified NEON type code. 1132 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1133 NeonTypeFlags Type(t); 1134 int IsQuad = ForceQuad ? true : Type.isQuad(); 1135 switch (Type.getEltType()) { 1136 case NeonTypeFlags::Int8: 1137 case NeonTypeFlags::Poly8: 1138 return shift ? 7 : (8 << IsQuad) - 1; 1139 case NeonTypeFlags::Int16: 1140 case NeonTypeFlags::Poly16: 1141 return shift ? 15 : (4 << IsQuad) - 1; 1142 case NeonTypeFlags::Int32: 1143 return shift ? 31 : (2 << IsQuad) - 1; 1144 case NeonTypeFlags::Int64: 1145 case NeonTypeFlags::Poly64: 1146 return shift ? 63 : (1 << IsQuad) - 1; 1147 case NeonTypeFlags::Poly128: 1148 return shift ? 127 : (1 << IsQuad) - 1; 1149 case NeonTypeFlags::Float16: 1150 assert(!shift && "cannot shift float types!"); 1151 return (4 << IsQuad) - 1; 1152 case NeonTypeFlags::Float32: 1153 assert(!shift && "cannot shift float types!"); 1154 return (2 << IsQuad) - 1; 1155 case NeonTypeFlags::Float64: 1156 assert(!shift && "cannot shift float types!"); 1157 return (1 << IsQuad) - 1; 1158 } 1159 llvm_unreachable("Invalid NeonTypeFlag!"); 1160 } 1161 1162 /// getNeonEltType - Return the QualType corresponding to the elements of 1163 /// the vector type specified by the NeonTypeFlags. This is used to check 1164 /// the pointer arguments for Neon load/store intrinsics. 1165 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1166 bool IsPolyUnsigned, bool IsInt64Long) { 1167 switch (Flags.getEltType()) { 1168 case NeonTypeFlags::Int8: 1169 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1170 case NeonTypeFlags::Int16: 1171 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1172 case NeonTypeFlags::Int32: 1173 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1174 case NeonTypeFlags::Int64: 1175 if (IsInt64Long) 1176 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1177 else 1178 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1179 : Context.LongLongTy; 1180 case NeonTypeFlags::Poly8: 1181 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1182 case NeonTypeFlags::Poly16: 1183 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1184 case NeonTypeFlags::Poly64: 1185 if (IsInt64Long) 1186 return Context.UnsignedLongTy; 1187 else 1188 return Context.UnsignedLongLongTy; 1189 case NeonTypeFlags::Poly128: 1190 break; 1191 case NeonTypeFlags::Float16: 1192 return Context.HalfTy; 1193 case NeonTypeFlags::Float32: 1194 return Context.FloatTy; 1195 case NeonTypeFlags::Float64: 1196 return Context.DoubleTy; 1197 } 1198 llvm_unreachable("Invalid NeonTypeFlag!"); 1199 } 1200 1201 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1202 llvm::APSInt Result; 1203 uint64_t mask = 0; 1204 unsigned TV = 0; 1205 int PtrArgNum = -1; 1206 bool HasConstPtr = false; 1207 switch (BuiltinID) { 1208 #define GET_NEON_OVERLOAD_CHECK 1209 #include "clang/Basic/arm_neon.inc" 1210 #undef GET_NEON_OVERLOAD_CHECK 1211 } 1212 1213 // For NEON intrinsics which are overloaded on vector element type, validate 1214 // the immediate which specifies which variant to emit. 1215 unsigned ImmArg = TheCall->getNumArgs()-1; 1216 if (mask) { 1217 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1218 return true; 1219 1220 TV = Result.getLimitedValue(64); 1221 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1222 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1223 << TheCall->getArg(ImmArg)->getSourceRange(); 1224 } 1225 1226 if (PtrArgNum >= 0) { 1227 // Check that pointer arguments have the specified type. 1228 Expr *Arg = TheCall->getArg(PtrArgNum); 1229 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1230 Arg = ICE->getSubExpr(); 1231 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1232 QualType RHSTy = RHS.get()->getType(); 1233 1234 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1235 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64; 1236 bool IsInt64Long = 1237 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1238 QualType EltTy = 1239 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1240 if (HasConstPtr) 1241 EltTy = EltTy.withConst(); 1242 QualType LHSTy = Context.getPointerType(EltTy); 1243 AssignConvertType ConvTy; 1244 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1245 if (RHS.isInvalid()) 1246 return true; 1247 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1248 RHS.get(), AA_Assigning)) 1249 return true; 1250 } 1251 1252 // For NEON intrinsics which take an immediate value as part of the 1253 // instruction, range check them here. 1254 unsigned i = 0, l = 0, u = 0; 1255 switch (BuiltinID) { 1256 default: 1257 return false; 1258 #define GET_NEON_IMMEDIATE_CHECK 1259 #include "clang/Basic/arm_neon.inc" 1260 #undef GET_NEON_IMMEDIATE_CHECK 1261 } 1262 1263 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1264 } 1265 1266 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1267 unsigned MaxWidth) { 1268 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1269 BuiltinID == ARM::BI__builtin_arm_ldaex || 1270 BuiltinID == ARM::BI__builtin_arm_strex || 1271 BuiltinID == ARM::BI__builtin_arm_stlex || 1272 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1273 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1274 BuiltinID == AArch64::BI__builtin_arm_strex || 1275 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1276 "unexpected ARM builtin"); 1277 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1278 BuiltinID == ARM::BI__builtin_arm_ldaex || 1279 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1280 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1281 1282 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1283 1284 // Ensure that we have the proper number of arguments. 1285 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1286 return true; 1287 1288 // Inspect the pointer argument of the atomic builtin. This should always be 1289 // a pointer type, whose element is an integral scalar or pointer type. 1290 // Because it is a pointer type, we don't have to worry about any implicit 1291 // casts here. 1292 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1293 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1294 if (PointerArgRes.isInvalid()) 1295 return true; 1296 PointerArg = PointerArgRes.get(); 1297 1298 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1299 if (!pointerType) { 1300 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1301 << PointerArg->getType() << PointerArg->getSourceRange(); 1302 return true; 1303 } 1304 1305 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1306 // task is to insert the appropriate casts into the AST. First work out just 1307 // what the appropriate type is. 1308 QualType ValType = pointerType->getPointeeType(); 1309 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1310 if (IsLdrex) 1311 AddrType.addConst(); 1312 1313 // Issue a warning if the cast is dodgy. 1314 CastKind CastNeeded = CK_NoOp; 1315 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1316 CastNeeded = CK_BitCast; 1317 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1318 << PointerArg->getType() 1319 << Context.getPointerType(AddrType) 1320 << AA_Passing << PointerArg->getSourceRange(); 1321 } 1322 1323 // Finally, do the cast and replace the argument with the corrected version. 1324 AddrType = Context.getPointerType(AddrType); 1325 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1326 if (PointerArgRes.isInvalid()) 1327 return true; 1328 PointerArg = PointerArgRes.get(); 1329 1330 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1331 1332 // In general, we allow ints, floats and pointers to be loaded and stored. 1333 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1334 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1335 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1336 << PointerArg->getType() << PointerArg->getSourceRange(); 1337 return true; 1338 } 1339 1340 // But ARM doesn't have instructions to deal with 128-bit versions. 1341 if (Context.getTypeSize(ValType) > MaxWidth) { 1342 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1343 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1344 << PointerArg->getType() << PointerArg->getSourceRange(); 1345 return true; 1346 } 1347 1348 switch (ValType.getObjCLifetime()) { 1349 case Qualifiers::OCL_None: 1350 case Qualifiers::OCL_ExplicitNone: 1351 // okay 1352 break; 1353 1354 case Qualifiers::OCL_Weak: 1355 case Qualifiers::OCL_Strong: 1356 case Qualifiers::OCL_Autoreleasing: 1357 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1358 << ValType << PointerArg->getSourceRange(); 1359 return true; 1360 } 1361 1362 if (IsLdrex) { 1363 TheCall->setType(ValType); 1364 return false; 1365 } 1366 1367 // Initialize the argument to be stored. 1368 ExprResult ValArg = TheCall->getArg(0); 1369 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1370 Context, ValType, /*consume*/ false); 1371 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1372 if (ValArg.isInvalid()) 1373 return true; 1374 TheCall->setArg(0, ValArg.get()); 1375 1376 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1377 // but the custom checker bypasses all default analysis. 1378 TheCall->setType(Context.IntTy); 1379 return false; 1380 } 1381 1382 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1383 llvm::APSInt Result; 1384 1385 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1386 BuiltinID == ARM::BI__builtin_arm_ldaex || 1387 BuiltinID == ARM::BI__builtin_arm_strex || 1388 BuiltinID == ARM::BI__builtin_arm_stlex) { 1389 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1390 } 1391 1392 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1393 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1394 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1395 } 1396 1397 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1398 BuiltinID == ARM::BI__builtin_arm_wsr64) 1399 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1400 1401 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1402 BuiltinID == ARM::BI__builtin_arm_rsrp || 1403 BuiltinID == ARM::BI__builtin_arm_wsr || 1404 BuiltinID == ARM::BI__builtin_arm_wsrp) 1405 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1406 1407 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1408 return true; 1409 1410 // For intrinsics which take an immediate value as part of the instruction, 1411 // range check them here. 1412 unsigned i = 0, l = 0, u = 0; 1413 switch (BuiltinID) { 1414 default: return false; 1415 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 1416 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 1417 case ARM::BI__builtin_arm_vcvtr_f: 1418 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 1419 case ARM::BI__builtin_arm_dmb: 1420 case ARM::BI__builtin_arm_dsb: 1421 case ARM::BI__builtin_arm_isb: 1422 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break; 1423 } 1424 1425 // FIXME: VFP Intrinsics should error if VFP not present. 1426 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1427 } 1428 1429 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1430 CallExpr *TheCall) { 1431 llvm::APSInt Result; 1432 1433 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1434 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1435 BuiltinID == AArch64::BI__builtin_arm_strex || 1436 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1437 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1438 } 1439 1440 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1441 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1442 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1443 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1444 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1445 } 1446 1447 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1448 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1449 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1450 1451 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1452 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1453 BuiltinID == AArch64::BI__builtin_arm_wsr || 1454 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1455 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1456 1457 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1458 return true; 1459 1460 // For intrinsics which take an immediate value as part of the instruction, 1461 // range check them here. 1462 unsigned i = 0, l = 0, u = 0; 1463 switch (BuiltinID) { 1464 default: return false; 1465 case AArch64::BI__builtin_arm_dmb: 1466 case AArch64::BI__builtin_arm_dsb: 1467 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1468 } 1469 1470 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1471 } 1472 1473 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1474 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1475 // ordering for DSP is unspecified. MSA is ordered by the data format used 1476 // by the underlying instruction i.e., df/m, df/n and then by size. 1477 // 1478 // FIXME: The size tests here should instead be tablegen'd along with the 1479 // definitions from include/clang/Basic/BuiltinsMips.def. 1480 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1481 // be too. 1482 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1483 unsigned i = 0, l = 0, u = 0, m = 0; 1484 switch (BuiltinID) { 1485 default: return false; 1486 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1487 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1488 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1489 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1490 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1491 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1492 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1493 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1494 // df/m field. 1495 // These intrinsics take an unsigned 3 bit immediate. 1496 case Mips::BI__builtin_msa_bclri_b: 1497 case Mips::BI__builtin_msa_bnegi_b: 1498 case Mips::BI__builtin_msa_bseti_b: 1499 case Mips::BI__builtin_msa_sat_s_b: 1500 case Mips::BI__builtin_msa_sat_u_b: 1501 case Mips::BI__builtin_msa_slli_b: 1502 case Mips::BI__builtin_msa_srai_b: 1503 case Mips::BI__builtin_msa_srari_b: 1504 case Mips::BI__builtin_msa_srli_b: 1505 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1506 case Mips::BI__builtin_msa_binsli_b: 1507 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1508 // These intrinsics take an unsigned 4 bit immediate. 1509 case Mips::BI__builtin_msa_bclri_h: 1510 case Mips::BI__builtin_msa_bnegi_h: 1511 case Mips::BI__builtin_msa_bseti_h: 1512 case Mips::BI__builtin_msa_sat_s_h: 1513 case Mips::BI__builtin_msa_sat_u_h: 1514 case Mips::BI__builtin_msa_slli_h: 1515 case Mips::BI__builtin_msa_srai_h: 1516 case Mips::BI__builtin_msa_srari_h: 1517 case Mips::BI__builtin_msa_srli_h: 1518 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1519 case Mips::BI__builtin_msa_binsli_h: 1520 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 1521 // These intrinsics take an unsigned 5 bit immedate. 1522 // The first block of intrinsics actually have an unsigned 5 bit field, 1523 // not a df/n field. 1524 case Mips::BI__builtin_msa_clei_u_b: 1525 case Mips::BI__builtin_msa_clei_u_h: 1526 case Mips::BI__builtin_msa_clei_u_w: 1527 case Mips::BI__builtin_msa_clei_u_d: 1528 case Mips::BI__builtin_msa_clti_u_b: 1529 case Mips::BI__builtin_msa_clti_u_h: 1530 case Mips::BI__builtin_msa_clti_u_w: 1531 case Mips::BI__builtin_msa_clti_u_d: 1532 case Mips::BI__builtin_msa_maxi_u_b: 1533 case Mips::BI__builtin_msa_maxi_u_h: 1534 case Mips::BI__builtin_msa_maxi_u_w: 1535 case Mips::BI__builtin_msa_maxi_u_d: 1536 case Mips::BI__builtin_msa_mini_u_b: 1537 case Mips::BI__builtin_msa_mini_u_h: 1538 case Mips::BI__builtin_msa_mini_u_w: 1539 case Mips::BI__builtin_msa_mini_u_d: 1540 case Mips::BI__builtin_msa_addvi_b: 1541 case Mips::BI__builtin_msa_addvi_h: 1542 case Mips::BI__builtin_msa_addvi_w: 1543 case Mips::BI__builtin_msa_addvi_d: 1544 case Mips::BI__builtin_msa_bclri_w: 1545 case Mips::BI__builtin_msa_bnegi_w: 1546 case Mips::BI__builtin_msa_bseti_w: 1547 case Mips::BI__builtin_msa_sat_s_w: 1548 case Mips::BI__builtin_msa_sat_u_w: 1549 case Mips::BI__builtin_msa_slli_w: 1550 case Mips::BI__builtin_msa_srai_w: 1551 case Mips::BI__builtin_msa_srari_w: 1552 case Mips::BI__builtin_msa_srli_w: 1553 case Mips::BI__builtin_msa_srlri_w: 1554 case Mips::BI__builtin_msa_subvi_b: 1555 case Mips::BI__builtin_msa_subvi_h: 1556 case Mips::BI__builtin_msa_subvi_w: 1557 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 1558 case Mips::BI__builtin_msa_binsli_w: 1559 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 1560 // These intrinsics take an unsigned 6 bit immediate. 1561 case Mips::BI__builtin_msa_bclri_d: 1562 case Mips::BI__builtin_msa_bnegi_d: 1563 case Mips::BI__builtin_msa_bseti_d: 1564 case Mips::BI__builtin_msa_sat_s_d: 1565 case Mips::BI__builtin_msa_sat_u_d: 1566 case Mips::BI__builtin_msa_slli_d: 1567 case Mips::BI__builtin_msa_srai_d: 1568 case Mips::BI__builtin_msa_srari_d: 1569 case Mips::BI__builtin_msa_srli_d: 1570 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 1571 case Mips::BI__builtin_msa_binsli_d: 1572 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 1573 // These intrinsics take a signed 5 bit immediate. 1574 case Mips::BI__builtin_msa_ceqi_b: 1575 case Mips::BI__builtin_msa_ceqi_h: 1576 case Mips::BI__builtin_msa_ceqi_w: 1577 case Mips::BI__builtin_msa_ceqi_d: 1578 case Mips::BI__builtin_msa_clti_s_b: 1579 case Mips::BI__builtin_msa_clti_s_h: 1580 case Mips::BI__builtin_msa_clti_s_w: 1581 case Mips::BI__builtin_msa_clti_s_d: 1582 case Mips::BI__builtin_msa_clei_s_b: 1583 case Mips::BI__builtin_msa_clei_s_h: 1584 case Mips::BI__builtin_msa_clei_s_w: 1585 case Mips::BI__builtin_msa_clei_s_d: 1586 case Mips::BI__builtin_msa_maxi_s_b: 1587 case Mips::BI__builtin_msa_maxi_s_h: 1588 case Mips::BI__builtin_msa_maxi_s_w: 1589 case Mips::BI__builtin_msa_maxi_s_d: 1590 case Mips::BI__builtin_msa_mini_s_b: 1591 case Mips::BI__builtin_msa_mini_s_h: 1592 case Mips::BI__builtin_msa_mini_s_w: 1593 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 1594 // These intrinsics take an unsigned 8 bit immediate. 1595 case Mips::BI__builtin_msa_andi_b: 1596 case Mips::BI__builtin_msa_nori_b: 1597 case Mips::BI__builtin_msa_ori_b: 1598 case Mips::BI__builtin_msa_shf_b: 1599 case Mips::BI__builtin_msa_shf_h: 1600 case Mips::BI__builtin_msa_shf_w: 1601 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 1602 case Mips::BI__builtin_msa_bseli_b: 1603 case Mips::BI__builtin_msa_bmnzi_b: 1604 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 1605 // df/n format 1606 // These intrinsics take an unsigned 4 bit immediate. 1607 case Mips::BI__builtin_msa_copy_s_b: 1608 case Mips::BI__builtin_msa_copy_u_b: 1609 case Mips::BI__builtin_msa_insve_b: 1610 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 1611 case Mips::BI__builtin_msa_sld_b: 1612 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 1613 // These intrinsics take an unsigned 3 bit immediate. 1614 case Mips::BI__builtin_msa_copy_s_h: 1615 case Mips::BI__builtin_msa_copy_u_h: 1616 case Mips::BI__builtin_msa_insve_h: 1617 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 1618 case Mips::BI__builtin_msa_sld_h: 1619 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 1620 // These intrinsics take an unsigned 2 bit immediate. 1621 case Mips::BI__builtin_msa_copy_s_w: 1622 case Mips::BI__builtin_msa_copy_u_w: 1623 case Mips::BI__builtin_msa_insve_w: 1624 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 1625 case Mips::BI__builtin_msa_sld_w: 1626 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 1627 // These intrinsics take an unsigned 1 bit immediate. 1628 case Mips::BI__builtin_msa_copy_s_d: 1629 case Mips::BI__builtin_msa_copy_u_d: 1630 case Mips::BI__builtin_msa_insve_d: 1631 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 1632 case Mips::BI__builtin_msa_sld_d: 1633 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 1634 // Memory offsets and immediate loads. 1635 // These intrinsics take a signed 10 bit immediate. 1636 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break; 1637 case Mips::BI__builtin_msa_ldi_h: 1638 case Mips::BI__builtin_msa_ldi_w: 1639 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 1640 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 1641 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 1642 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 1643 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 1644 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 1645 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 1646 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 1647 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 1648 } 1649 1650 if (!m) 1651 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1652 1653 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 1654 SemaBuiltinConstantArgMultiple(TheCall, i, m); 1655 } 1656 1657 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1658 unsigned i = 0, l = 0, u = 0; 1659 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 1660 BuiltinID == PPC::BI__builtin_divdeu || 1661 BuiltinID == PPC::BI__builtin_bpermd; 1662 bool IsTarget64Bit = Context.getTargetInfo() 1663 .getTypeWidth(Context 1664 .getTargetInfo() 1665 .getIntPtrType()) == 64; 1666 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 1667 BuiltinID == PPC::BI__builtin_divweu || 1668 BuiltinID == PPC::BI__builtin_divde || 1669 BuiltinID == PPC::BI__builtin_divdeu; 1670 1671 if (Is64BitBltin && !IsTarget64Bit) 1672 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 1673 << TheCall->getSourceRange(); 1674 1675 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 1676 (BuiltinID == PPC::BI__builtin_bpermd && 1677 !Context.getTargetInfo().hasFeature("bpermd"))) 1678 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 1679 << TheCall->getSourceRange(); 1680 1681 switch (BuiltinID) { 1682 default: return false; 1683 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 1684 case PPC::BI__builtin_altivec_crypto_vshasigmad: 1685 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1686 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1687 case PPC::BI__builtin_tbegin: 1688 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 1689 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 1690 case PPC::BI__builtin_tabortwc: 1691 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 1692 case PPC::BI__builtin_tabortwci: 1693 case PPC::BI__builtin_tabortdci: 1694 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 1695 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 1696 } 1697 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1698 } 1699 1700 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 1701 CallExpr *TheCall) { 1702 if (BuiltinID == SystemZ::BI__builtin_tabort) { 1703 Expr *Arg = TheCall->getArg(0); 1704 llvm::APSInt AbortCode(32); 1705 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 1706 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 1707 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 1708 << Arg->getSourceRange(); 1709 } 1710 1711 // For intrinsics which take an immediate value as part of the instruction, 1712 // range check them here. 1713 unsigned i = 0, l = 0, u = 0; 1714 switch (BuiltinID) { 1715 default: return false; 1716 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 1717 case SystemZ::BI__builtin_s390_verimb: 1718 case SystemZ::BI__builtin_s390_verimh: 1719 case SystemZ::BI__builtin_s390_verimf: 1720 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 1721 case SystemZ::BI__builtin_s390_vfaeb: 1722 case SystemZ::BI__builtin_s390_vfaeh: 1723 case SystemZ::BI__builtin_s390_vfaef: 1724 case SystemZ::BI__builtin_s390_vfaebs: 1725 case SystemZ::BI__builtin_s390_vfaehs: 1726 case SystemZ::BI__builtin_s390_vfaefs: 1727 case SystemZ::BI__builtin_s390_vfaezb: 1728 case SystemZ::BI__builtin_s390_vfaezh: 1729 case SystemZ::BI__builtin_s390_vfaezf: 1730 case SystemZ::BI__builtin_s390_vfaezbs: 1731 case SystemZ::BI__builtin_s390_vfaezhs: 1732 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 1733 case SystemZ::BI__builtin_s390_vfidb: 1734 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 1735 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1736 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 1737 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 1738 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 1739 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 1740 case SystemZ::BI__builtin_s390_vstrcb: 1741 case SystemZ::BI__builtin_s390_vstrch: 1742 case SystemZ::BI__builtin_s390_vstrcf: 1743 case SystemZ::BI__builtin_s390_vstrczb: 1744 case SystemZ::BI__builtin_s390_vstrczh: 1745 case SystemZ::BI__builtin_s390_vstrczf: 1746 case SystemZ::BI__builtin_s390_vstrcbs: 1747 case SystemZ::BI__builtin_s390_vstrchs: 1748 case SystemZ::BI__builtin_s390_vstrcfs: 1749 case SystemZ::BI__builtin_s390_vstrczbs: 1750 case SystemZ::BI__builtin_s390_vstrczhs: 1751 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 1752 } 1753 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1754 } 1755 1756 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 1757 /// This checks that the target supports __builtin_cpu_supports and 1758 /// that the string argument is constant and valid. 1759 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 1760 Expr *Arg = TheCall->getArg(0); 1761 1762 // Check if the argument is a string literal. 1763 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1764 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1765 << Arg->getSourceRange(); 1766 1767 // Check the contents of the string. 1768 StringRef Feature = 1769 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1770 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 1771 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 1772 << Arg->getSourceRange(); 1773 return false; 1774 } 1775 1776 // Check if the rounding mode is legal. 1777 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 1778 // Indicates if this instruction has rounding control or just SAE. 1779 bool HasRC = false; 1780 1781 unsigned ArgNum = 0; 1782 switch (BuiltinID) { 1783 default: 1784 return false; 1785 case X86::BI__builtin_ia32_vcvttsd2si32: 1786 case X86::BI__builtin_ia32_vcvttsd2si64: 1787 case X86::BI__builtin_ia32_vcvttsd2usi32: 1788 case X86::BI__builtin_ia32_vcvttsd2usi64: 1789 case X86::BI__builtin_ia32_vcvttss2si32: 1790 case X86::BI__builtin_ia32_vcvttss2si64: 1791 case X86::BI__builtin_ia32_vcvttss2usi32: 1792 case X86::BI__builtin_ia32_vcvttss2usi64: 1793 ArgNum = 1; 1794 break; 1795 case X86::BI__builtin_ia32_cvtps2pd512_mask: 1796 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 1797 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 1798 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 1799 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 1800 case X86::BI__builtin_ia32_cvttps2dq512_mask: 1801 case X86::BI__builtin_ia32_cvttps2qq512_mask: 1802 case X86::BI__builtin_ia32_cvttps2udq512_mask: 1803 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 1804 case X86::BI__builtin_ia32_exp2pd_mask: 1805 case X86::BI__builtin_ia32_exp2ps_mask: 1806 case X86::BI__builtin_ia32_getexppd512_mask: 1807 case X86::BI__builtin_ia32_getexpps512_mask: 1808 case X86::BI__builtin_ia32_rcp28pd_mask: 1809 case X86::BI__builtin_ia32_rcp28ps_mask: 1810 case X86::BI__builtin_ia32_rsqrt28pd_mask: 1811 case X86::BI__builtin_ia32_rsqrt28ps_mask: 1812 case X86::BI__builtin_ia32_vcomisd: 1813 case X86::BI__builtin_ia32_vcomiss: 1814 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 1815 ArgNum = 3; 1816 break; 1817 case X86::BI__builtin_ia32_cmppd512_mask: 1818 case X86::BI__builtin_ia32_cmpps512_mask: 1819 case X86::BI__builtin_ia32_cmpsd_mask: 1820 case X86::BI__builtin_ia32_cmpss_mask: 1821 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 1822 case X86::BI__builtin_ia32_getexpsd128_round_mask: 1823 case X86::BI__builtin_ia32_getexpss128_round_mask: 1824 case X86::BI__builtin_ia32_maxpd512_mask: 1825 case X86::BI__builtin_ia32_maxps512_mask: 1826 case X86::BI__builtin_ia32_maxsd_round_mask: 1827 case X86::BI__builtin_ia32_maxss_round_mask: 1828 case X86::BI__builtin_ia32_minpd512_mask: 1829 case X86::BI__builtin_ia32_minps512_mask: 1830 case X86::BI__builtin_ia32_minsd_round_mask: 1831 case X86::BI__builtin_ia32_minss_round_mask: 1832 case X86::BI__builtin_ia32_rcp28sd_round_mask: 1833 case X86::BI__builtin_ia32_rcp28ss_round_mask: 1834 case X86::BI__builtin_ia32_reducepd512_mask: 1835 case X86::BI__builtin_ia32_reduceps512_mask: 1836 case X86::BI__builtin_ia32_rndscalepd_mask: 1837 case X86::BI__builtin_ia32_rndscaleps_mask: 1838 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 1839 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 1840 ArgNum = 4; 1841 break; 1842 case X86::BI__builtin_ia32_fixupimmpd512_mask: 1843 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 1844 case X86::BI__builtin_ia32_fixupimmps512_mask: 1845 case X86::BI__builtin_ia32_fixupimmps512_maskz: 1846 case X86::BI__builtin_ia32_fixupimmsd_mask: 1847 case X86::BI__builtin_ia32_fixupimmsd_maskz: 1848 case X86::BI__builtin_ia32_fixupimmss_mask: 1849 case X86::BI__builtin_ia32_fixupimmss_maskz: 1850 case X86::BI__builtin_ia32_rangepd512_mask: 1851 case X86::BI__builtin_ia32_rangeps512_mask: 1852 case X86::BI__builtin_ia32_rangesd128_round_mask: 1853 case X86::BI__builtin_ia32_rangess128_round_mask: 1854 case X86::BI__builtin_ia32_reducesd_mask: 1855 case X86::BI__builtin_ia32_reducess_mask: 1856 case X86::BI__builtin_ia32_rndscalesd_round_mask: 1857 case X86::BI__builtin_ia32_rndscaless_round_mask: 1858 ArgNum = 5; 1859 break; 1860 case X86::BI__builtin_ia32_vcvtsd2si64: 1861 case X86::BI__builtin_ia32_vcvtsd2si32: 1862 case X86::BI__builtin_ia32_vcvtsd2usi32: 1863 case X86::BI__builtin_ia32_vcvtsd2usi64: 1864 case X86::BI__builtin_ia32_vcvtss2si32: 1865 case X86::BI__builtin_ia32_vcvtss2si64: 1866 case X86::BI__builtin_ia32_vcvtss2usi32: 1867 case X86::BI__builtin_ia32_vcvtss2usi64: 1868 ArgNum = 1; 1869 HasRC = true; 1870 break; 1871 case X86::BI__builtin_ia32_cvtsi2sd64: 1872 case X86::BI__builtin_ia32_cvtsi2ss32: 1873 case X86::BI__builtin_ia32_cvtsi2ss64: 1874 case X86::BI__builtin_ia32_cvtusi2sd64: 1875 case X86::BI__builtin_ia32_cvtusi2ss32: 1876 case X86::BI__builtin_ia32_cvtusi2ss64: 1877 ArgNum = 2; 1878 HasRC = true; 1879 break; 1880 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 1881 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 1882 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 1883 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 1884 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 1885 case X86::BI__builtin_ia32_cvtps2qq512_mask: 1886 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 1887 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 1888 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 1889 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 1890 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 1891 case X86::BI__builtin_ia32_sqrtpd512_mask: 1892 case X86::BI__builtin_ia32_sqrtps512_mask: 1893 ArgNum = 3; 1894 HasRC = true; 1895 break; 1896 case X86::BI__builtin_ia32_addpd512_mask: 1897 case X86::BI__builtin_ia32_addps512_mask: 1898 case X86::BI__builtin_ia32_divpd512_mask: 1899 case X86::BI__builtin_ia32_divps512_mask: 1900 case X86::BI__builtin_ia32_mulpd512_mask: 1901 case X86::BI__builtin_ia32_mulps512_mask: 1902 case X86::BI__builtin_ia32_subpd512_mask: 1903 case X86::BI__builtin_ia32_subps512_mask: 1904 case X86::BI__builtin_ia32_addss_round_mask: 1905 case X86::BI__builtin_ia32_addsd_round_mask: 1906 case X86::BI__builtin_ia32_divss_round_mask: 1907 case X86::BI__builtin_ia32_divsd_round_mask: 1908 case X86::BI__builtin_ia32_mulss_round_mask: 1909 case X86::BI__builtin_ia32_mulsd_round_mask: 1910 case X86::BI__builtin_ia32_subss_round_mask: 1911 case X86::BI__builtin_ia32_subsd_round_mask: 1912 case X86::BI__builtin_ia32_scalefpd512_mask: 1913 case X86::BI__builtin_ia32_scalefps512_mask: 1914 case X86::BI__builtin_ia32_scalefsd_round_mask: 1915 case X86::BI__builtin_ia32_scalefss_round_mask: 1916 case X86::BI__builtin_ia32_getmantpd512_mask: 1917 case X86::BI__builtin_ia32_getmantps512_mask: 1918 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 1919 case X86::BI__builtin_ia32_sqrtsd_round_mask: 1920 case X86::BI__builtin_ia32_sqrtss_round_mask: 1921 case X86::BI__builtin_ia32_vfmaddpd512_mask: 1922 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 1923 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 1924 case X86::BI__builtin_ia32_vfmaddps512_mask: 1925 case X86::BI__builtin_ia32_vfmaddps512_mask3: 1926 case X86::BI__builtin_ia32_vfmaddps512_maskz: 1927 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 1928 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 1929 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 1930 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 1931 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 1932 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 1933 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 1934 case X86::BI__builtin_ia32_vfmsubps512_mask3: 1935 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 1936 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 1937 case X86::BI__builtin_ia32_vfnmaddpd512_mask: 1938 case X86::BI__builtin_ia32_vfnmaddps512_mask: 1939 case X86::BI__builtin_ia32_vfnmsubpd512_mask: 1940 case X86::BI__builtin_ia32_vfnmsubpd512_mask3: 1941 case X86::BI__builtin_ia32_vfnmsubps512_mask: 1942 case X86::BI__builtin_ia32_vfnmsubps512_mask3: 1943 case X86::BI__builtin_ia32_vfmaddsd3_mask: 1944 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 1945 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 1946 case X86::BI__builtin_ia32_vfmaddss3_mask: 1947 case X86::BI__builtin_ia32_vfmaddss3_maskz: 1948 case X86::BI__builtin_ia32_vfmaddss3_mask3: 1949 ArgNum = 4; 1950 HasRC = true; 1951 break; 1952 case X86::BI__builtin_ia32_getmantsd_round_mask: 1953 case X86::BI__builtin_ia32_getmantss_round_mask: 1954 ArgNum = 5; 1955 HasRC = true; 1956 break; 1957 } 1958 1959 llvm::APSInt Result; 1960 1961 // We can't check the value of a dependent argument. 1962 Expr *Arg = TheCall->getArg(ArgNum); 1963 if (Arg->isTypeDependent() || Arg->isValueDependent()) 1964 return false; 1965 1966 // Check constant-ness first. 1967 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 1968 return true; 1969 1970 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 1971 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 1972 // combined with ROUND_NO_EXC. 1973 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 1974 Result == 8/*ROUND_NO_EXC*/ || 1975 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 1976 return false; 1977 1978 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 1979 << Arg->getSourceRange(); 1980 } 1981 1982 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1983 if (BuiltinID == X86::BI__builtin_cpu_supports) 1984 return SemaBuiltinCpuSupports(*this, TheCall); 1985 1986 if (BuiltinID == X86::BI__builtin_ms_va_start) 1987 return SemaBuiltinMSVAStart(TheCall); 1988 1989 // If the intrinsic has rounding or SAE make sure its valid. 1990 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 1991 return true; 1992 1993 // For intrinsics which take an immediate value as part of the instruction, 1994 // range check them here. 1995 int i = 0, l = 0, u = 0; 1996 switch (BuiltinID) { 1997 default: 1998 return false; 1999 case X86::BI_mm_prefetch: 2000 i = 1; l = 0; u = 3; 2001 break; 2002 case X86::BI__builtin_ia32_sha1rnds4: 2003 case X86::BI__builtin_ia32_shuf_f32x4_256_mask: 2004 case X86::BI__builtin_ia32_shuf_f64x2_256_mask: 2005 case X86::BI__builtin_ia32_shuf_i32x4_256_mask: 2006 case X86::BI__builtin_ia32_shuf_i64x2_256_mask: 2007 i = 2; l = 0; u = 3; 2008 break; 2009 case X86::BI__builtin_ia32_vpermil2pd: 2010 case X86::BI__builtin_ia32_vpermil2pd256: 2011 case X86::BI__builtin_ia32_vpermil2ps: 2012 case X86::BI__builtin_ia32_vpermil2ps256: 2013 i = 3; l = 0; u = 3; 2014 break; 2015 case X86::BI__builtin_ia32_cmpb128_mask: 2016 case X86::BI__builtin_ia32_cmpw128_mask: 2017 case X86::BI__builtin_ia32_cmpd128_mask: 2018 case X86::BI__builtin_ia32_cmpq128_mask: 2019 case X86::BI__builtin_ia32_cmpb256_mask: 2020 case X86::BI__builtin_ia32_cmpw256_mask: 2021 case X86::BI__builtin_ia32_cmpd256_mask: 2022 case X86::BI__builtin_ia32_cmpq256_mask: 2023 case X86::BI__builtin_ia32_cmpb512_mask: 2024 case X86::BI__builtin_ia32_cmpw512_mask: 2025 case X86::BI__builtin_ia32_cmpd512_mask: 2026 case X86::BI__builtin_ia32_cmpq512_mask: 2027 case X86::BI__builtin_ia32_ucmpb128_mask: 2028 case X86::BI__builtin_ia32_ucmpw128_mask: 2029 case X86::BI__builtin_ia32_ucmpd128_mask: 2030 case X86::BI__builtin_ia32_ucmpq128_mask: 2031 case X86::BI__builtin_ia32_ucmpb256_mask: 2032 case X86::BI__builtin_ia32_ucmpw256_mask: 2033 case X86::BI__builtin_ia32_ucmpd256_mask: 2034 case X86::BI__builtin_ia32_ucmpq256_mask: 2035 case X86::BI__builtin_ia32_ucmpb512_mask: 2036 case X86::BI__builtin_ia32_ucmpw512_mask: 2037 case X86::BI__builtin_ia32_ucmpd512_mask: 2038 case X86::BI__builtin_ia32_ucmpq512_mask: 2039 case X86::BI__builtin_ia32_vpcomub: 2040 case X86::BI__builtin_ia32_vpcomuw: 2041 case X86::BI__builtin_ia32_vpcomud: 2042 case X86::BI__builtin_ia32_vpcomuq: 2043 case X86::BI__builtin_ia32_vpcomb: 2044 case X86::BI__builtin_ia32_vpcomw: 2045 case X86::BI__builtin_ia32_vpcomd: 2046 case X86::BI__builtin_ia32_vpcomq: 2047 i = 2; l = 0; u = 7; 2048 break; 2049 case X86::BI__builtin_ia32_roundps: 2050 case X86::BI__builtin_ia32_roundpd: 2051 case X86::BI__builtin_ia32_roundps256: 2052 case X86::BI__builtin_ia32_roundpd256: 2053 i = 1; l = 0; u = 15; 2054 break; 2055 case X86::BI__builtin_ia32_roundss: 2056 case X86::BI__builtin_ia32_roundsd: 2057 case X86::BI__builtin_ia32_rangepd128_mask: 2058 case X86::BI__builtin_ia32_rangepd256_mask: 2059 case X86::BI__builtin_ia32_rangepd512_mask: 2060 case X86::BI__builtin_ia32_rangeps128_mask: 2061 case X86::BI__builtin_ia32_rangeps256_mask: 2062 case X86::BI__builtin_ia32_rangeps512_mask: 2063 case X86::BI__builtin_ia32_getmantsd_round_mask: 2064 case X86::BI__builtin_ia32_getmantss_round_mask: 2065 i = 2; l = 0; u = 15; 2066 break; 2067 case X86::BI__builtin_ia32_cmpps: 2068 case X86::BI__builtin_ia32_cmpss: 2069 case X86::BI__builtin_ia32_cmppd: 2070 case X86::BI__builtin_ia32_cmpsd: 2071 case X86::BI__builtin_ia32_cmpps256: 2072 case X86::BI__builtin_ia32_cmppd256: 2073 case X86::BI__builtin_ia32_cmpps128_mask: 2074 case X86::BI__builtin_ia32_cmppd128_mask: 2075 case X86::BI__builtin_ia32_cmpps256_mask: 2076 case X86::BI__builtin_ia32_cmppd256_mask: 2077 case X86::BI__builtin_ia32_cmpps512_mask: 2078 case X86::BI__builtin_ia32_cmppd512_mask: 2079 case X86::BI__builtin_ia32_cmpsd_mask: 2080 case X86::BI__builtin_ia32_cmpss_mask: 2081 i = 2; l = 0; u = 31; 2082 break; 2083 case X86::BI__builtin_ia32_xabort: 2084 i = 0; l = -128; u = 255; 2085 break; 2086 case X86::BI__builtin_ia32_pshufw: 2087 case X86::BI__builtin_ia32_aeskeygenassist128: 2088 i = 1; l = -128; u = 255; 2089 break; 2090 case X86::BI__builtin_ia32_vcvtps2ph: 2091 case X86::BI__builtin_ia32_vcvtps2ph256: 2092 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2093 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2094 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2095 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2096 case X86::BI__builtin_ia32_rndscaleps_mask: 2097 case X86::BI__builtin_ia32_rndscalepd_mask: 2098 case X86::BI__builtin_ia32_reducepd128_mask: 2099 case X86::BI__builtin_ia32_reducepd256_mask: 2100 case X86::BI__builtin_ia32_reducepd512_mask: 2101 case X86::BI__builtin_ia32_reduceps128_mask: 2102 case X86::BI__builtin_ia32_reduceps256_mask: 2103 case X86::BI__builtin_ia32_reduceps512_mask: 2104 case X86::BI__builtin_ia32_prold512_mask: 2105 case X86::BI__builtin_ia32_prolq512_mask: 2106 case X86::BI__builtin_ia32_prold128_mask: 2107 case X86::BI__builtin_ia32_prold256_mask: 2108 case X86::BI__builtin_ia32_prolq128_mask: 2109 case X86::BI__builtin_ia32_prolq256_mask: 2110 case X86::BI__builtin_ia32_prord128_mask: 2111 case X86::BI__builtin_ia32_prord256_mask: 2112 case X86::BI__builtin_ia32_prorq128_mask: 2113 case X86::BI__builtin_ia32_prorq256_mask: 2114 case X86::BI__builtin_ia32_fpclasspd128_mask: 2115 case X86::BI__builtin_ia32_fpclasspd256_mask: 2116 case X86::BI__builtin_ia32_fpclassps128_mask: 2117 case X86::BI__builtin_ia32_fpclassps256_mask: 2118 case X86::BI__builtin_ia32_fpclassps512_mask: 2119 case X86::BI__builtin_ia32_fpclasspd512_mask: 2120 case X86::BI__builtin_ia32_fpclasssd_mask: 2121 case X86::BI__builtin_ia32_fpclassss_mask: 2122 i = 1; l = 0; u = 255; 2123 break; 2124 case X86::BI__builtin_ia32_palignr: 2125 case X86::BI__builtin_ia32_insertps128: 2126 case X86::BI__builtin_ia32_dpps: 2127 case X86::BI__builtin_ia32_dppd: 2128 case X86::BI__builtin_ia32_dpps256: 2129 case X86::BI__builtin_ia32_mpsadbw128: 2130 case X86::BI__builtin_ia32_mpsadbw256: 2131 case X86::BI__builtin_ia32_pcmpistrm128: 2132 case X86::BI__builtin_ia32_pcmpistri128: 2133 case X86::BI__builtin_ia32_pcmpistria128: 2134 case X86::BI__builtin_ia32_pcmpistric128: 2135 case X86::BI__builtin_ia32_pcmpistrio128: 2136 case X86::BI__builtin_ia32_pcmpistris128: 2137 case X86::BI__builtin_ia32_pcmpistriz128: 2138 case X86::BI__builtin_ia32_pclmulqdq128: 2139 case X86::BI__builtin_ia32_vperm2f128_pd256: 2140 case X86::BI__builtin_ia32_vperm2f128_ps256: 2141 case X86::BI__builtin_ia32_vperm2f128_si256: 2142 case X86::BI__builtin_ia32_permti256: 2143 i = 2; l = -128; u = 255; 2144 break; 2145 case X86::BI__builtin_ia32_palignr128: 2146 case X86::BI__builtin_ia32_palignr256: 2147 case X86::BI__builtin_ia32_palignr512_mask: 2148 case X86::BI__builtin_ia32_alignq512_mask: 2149 case X86::BI__builtin_ia32_alignd512_mask: 2150 case X86::BI__builtin_ia32_alignd128_mask: 2151 case X86::BI__builtin_ia32_alignd256_mask: 2152 case X86::BI__builtin_ia32_alignq128_mask: 2153 case X86::BI__builtin_ia32_alignq256_mask: 2154 case X86::BI__builtin_ia32_vcomisd: 2155 case X86::BI__builtin_ia32_vcomiss: 2156 case X86::BI__builtin_ia32_shuf_f32x4_mask: 2157 case X86::BI__builtin_ia32_shuf_f64x2_mask: 2158 case X86::BI__builtin_ia32_shuf_i32x4_mask: 2159 case X86::BI__builtin_ia32_shuf_i64x2_mask: 2160 case X86::BI__builtin_ia32_dbpsadbw128_mask: 2161 case X86::BI__builtin_ia32_dbpsadbw256_mask: 2162 case X86::BI__builtin_ia32_dbpsadbw512_mask: 2163 i = 2; l = 0; u = 255; 2164 break; 2165 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2166 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2167 case X86::BI__builtin_ia32_fixupimmps512_mask: 2168 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2169 case X86::BI__builtin_ia32_fixupimmsd_mask: 2170 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2171 case X86::BI__builtin_ia32_fixupimmss_mask: 2172 case X86::BI__builtin_ia32_fixupimmss_maskz: 2173 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2174 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2175 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2176 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2177 case X86::BI__builtin_ia32_fixupimmps128_mask: 2178 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2179 case X86::BI__builtin_ia32_fixupimmps256_mask: 2180 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2181 case X86::BI__builtin_ia32_pternlogd512_mask: 2182 case X86::BI__builtin_ia32_pternlogd512_maskz: 2183 case X86::BI__builtin_ia32_pternlogq512_mask: 2184 case X86::BI__builtin_ia32_pternlogq512_maskz: 2185 case X86::BI__builtin_ia32_pternlogd128_mask: 2186 case X86::BI__builtin_ia32_pternlogd128_maskz: 2187 case X86::BI__builtin_ia32_pternlogd256_mask: 2188 case X86::BI__builtin_ia32_pternlogd256_maskz: 2189 case X86::BI__builtin_ia32_pternlogq128_mask: 2190 case X86::BI__builtin_ia32_pternlogq128_maskz: 2191 case X86::BI__builtin_ia32_pternlogq256_mask: 2192 case X86::BI__builtin_ia32_pternlogq256_maskz: 2193 i = 3; l = 0; u = 255; 2194 break; 2195 case X86::BI__builtin_ia32_pcmpestrm128: 2196 case X86::BI__builtin_ia32_pcmpestri128: 2197 case X86::BI__builtin_ia32_pcmpestria128: 2198 case X86::BI__builtin_ia32_pcmpestric128: 2199 case X86::BI__builtin_ia32_pcmpestrio128: 2200 case X86::BI__builtin_ia32_pcmpestris128: 2201 case X86::BI__builtin_ia32_pcmpestriz128: 2202 i = 4; l = -128; u = 255; 2203 break; 2204 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2205 case X86::BI__builtin_ia32_rndscaless_round_mask: 2206 i = 4; l = 0; u = 255; 2207 break; 2208 } 2209 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2210 } 2211 2212 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2213 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2214 /// Returns true when the format fits the function and the FormatStringInfo has 2215 /// been populated. 2216 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2217 FormatStringInfo *FSI) { 2218 FSI->HasVAListArg = Format->getFirstArg() == 0; 2219 FSI->FormatIdx = Format->getFormatIdx() - 1; 2220 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2221 2222 // The way the format attribute works in GCC, the implicit this argument 2223 // of member functions is counted. However, it doesn't appear in our own 2224 // lists, so decrement format_idx in that case. 2225 if (IsCXXMember) { 2226 if(FSI->FormatIdx == 0) 2227 return false; 2228 --FSI->FormatIdx; 2229 if (FSI->FirstDataArg != 0) 2230 --FSI->FirstDataArg; 2231 } 2232 return true; 2233 } 2234 2235 /// Checks if a the given expression evaluates to null. 2236 /// 2237 /// \brief Returns true if the value evaluates to null. 2238 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2239 // If the expression has non-null type, it doesn't evaluate to null. 2240 if (auto nullability 2241 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2242 if (*nullability == NullabilityKind::NonNull) 2243 return false; 2244 } 2245 2246 // As a special case, transparent unions initialized with zero are 2247 // considered null for the purposes of the nonnull attribute. 2248 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2249 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2250 if (const CompoundLiteralExpr *CLE = 2251 dyn_cast<CompoundLiteralExpr>(Expr)) 2252 if (const InitListExpr *ILE = 2253 dyn_cast<InitListExpr>(CLE->getInitializer())) 2254 Expr = ILE->getInit(0); 2255 } 2256 2257 bool Result; 2258 return (!Expr->isValueDependent() && 2259 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2260 !Result); 2261 } 2262 2263 static void CheckNonNullArgument(Sema &S, 2264 const Expr *ArgExpr, 2265 SourceLocation CallSiteLoc) { 2266 if (CheckNonNullExpr(S, ArgExpr)) 2267 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2268 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2269 } 2270 2271 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2272 FormatStringInfo FSI; 2273 if ((GetFormatStringType(Format) == FST_NSString) && 2274 getFormatStringInfo(Format, false, &FSI)) { 2275 Idx = FSI.FormatIdx; 2276 return true; 2277 } 2278 return false; 2279 } 2280 /// \brief Diagnose use of %s directive in an NSString which is being passed 2281 /// as formatting string to formatting method. 2282 static void 2283 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 2284 const NamedDecl *FDecl, 2285 Expr **Args, 2286 unsigned NumArgs) { 2287 unsigned Idx = 0; 2288 bool Format = false; 2289 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 2290 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 2291 Idx = 2; 2292 Format = true; 2293 } 2294 else 2295 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2296 if (S.GetFormatNSStringIdx(I, Idx)) { 2297 Format = true; 2298 break; 2299 } 2300 } 2301 if (!Format || NumArgs <= Idx) 2302 return; 2303 const Expr *FormatExpr = Args[Idx]; 2304 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 2305 FormatExpr = CSCE->getSubExpr(); 2306 const StringLiteral *FormatString; 2307 if (const ObjCStringLiteral *OSL = 2308 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 2309 FormatString = OSL->getString(); 2310 else 2311 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 2312 if (!FormatString) 2313 return; 2314 if (S.FormatStringHasSArg(FormatString)) { 2315 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2316 << "%s" << 1 << 1; 2317 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 2318 << FDecl->getDeclName(); 2319 } 2320 } 2321 2322 /// Determine whether the given type has a non-null nullability annotation. 2323 static bool isNonNullType(ASTContext &ctx, QualType type) { 2324 if (auto nullability = type->getNullability(ctx)) 2325 return *nullability == NullabilityKind::NonNull; 2326 2327 return false; 2328 } 2329 2330 static void CheckNonNullArguments(Sema &S, 2331 const NamedDecl *FDecl, 2332 const FunctionProtoType *Proto, 2333 ArrayRef<const Expr *> Args, 2334 SourceLocation CallSiteLoc) { 2335 assert((FDecl || Proto) && "Need a function declaration or prototype"); 2336 2337 // Check the attributes attached to the method/function itself. 2338 llvm::SmallBitVector NonNullArgs; 2339 if (FDecl) { 2340 // Handle the nonnull attribute on the function/method declaration itself. 2341 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 2342 if (!NonNull->args_size()) { 2343 // Easy case: all pointer arguments are nonnull. 2344 for (const auto *Arg : Args) 2345 if (S.isValidPointerAttrType(Arg->getType())) 2346 CheckNonNullArgument(S, Arg, CallSiteLoc); 2347 return; 2348 } 2349 2350 for (unsigned Val : NonNull->args()) { 2351 if (Val >= Args.size()) 2352 continue; 2353 if (NonNullArgs.empty()) 2354 NonNullArgs.resize(Args.size()); 2355 NonNullArgs.set(Val); 2356 } 2357 } 2358 } 2359 2360 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 2361 // Handle the nonnull attribute on the parameters of the 2362 // function/method. 2363 ArrayRef<ParmVarDecl*> parms; 2364 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 2365 parms = FD->parameters(); 2366 else 2367 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 2368 2369 unsigned ParamIndex = 0; 2370 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 2371 I != E; ++I, ++ParamIndex) { 2372 const ParmVarDecl *PVD = *I; 2373 if (PVD->hasAttr<NonNullAttr>() || 2374 isNonNullType(S.Context, PVD->getType())) { 2375 if (NonNullArgs.empty()) 2376 NonNullArgs.resize(Args.size()); 2377 2378 NonNullArgs.set(ParamIndex); 2379 } 2380 } 2381 } else { 2382 // If we have a non-function, non-method declaration but no 2383 // function prototype, try to dig out the function prototype. 2384 if (!Proto) { 2385 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 2386 QualType type = VD->getType().getNonReferenceType(); 2387 if (auto pointerType = type->getAs<PointerType>()) 2388 type = pointerType->getPointeeType(); 2389 else if (auto blockType = type->getAs<BlockPointerType>()) 2390 type = blockType->getPointeeType(); 2391 // FIXME: data member pointers? 2392 2393 // Dig out the function prototype, if there is one. 2394 Proto = type->getAs<FunctionProtoType>(); 2395 } 2396 } 2397 2398 // Fill in non-null argument information from the nullability 2399 // information on the parameter types (if we have them). 2400 if (Proto) { 2401 unsigned Index = 0; 2402 for (auto paramType : Proto->getParamTypes()) { 2403 if (isNonNullType(S.Context, paramType)) { 2404 if (NonNullArgs.empty()) 2405 NonNullArgs.resize(Args.size()); 2406 2407 NonNullArgs.set(Index); 2408 } 2409 2410 ++Index; 2411 } 2412 } 2413 } 2414 2415 // Check for non-null arguments. 2416 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 2417 ArgIndex != ArgIndexEnd; ++ArgIndex) { 2418 if (NonNullArgs[ArgIndex]) 2419 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 2420 } 2421 } 2422 2423 /// Handles the checks for format strings, non-POD arguments to vararg 2424 /// functions, and NULL arguments passed to non-NULL parameters. 2425 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2426 ArrayRef<const Expr *> Args, bool IsMemberFunction, 2427 SourceLocation Loc, SourceRange Range, 2428 VariadicCallType CallType) { 2429 // FIXME: We should check as much as we can in the template definition. 2430 if (CurContext->isDependentContext()) 2431 return; 2432 2433 // Printf and scanf checking. 2434 llvm::SmallBitVector CheckedVarArgs; 2435 if (FDecl) { 2436 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 2437 // Only create vector if there are format attributes. 2438 CheckedVarArgs.resize(Args.size()); 2439 2440 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 2441 CheckedVarArgs); 2442 } 2443 } 2444 2445 // Refuse POD arguments that weren't caught by the format string 2446 // checks above. 2447 if (CallType != VariadicDoesNotApply) { 2448 unsigned NumParams = Proto ? Proto->getNumParams() 2449 : FDecl && isa<FunctionDecl>(FDecl) 2450 ? cast<FunctionDecl>(FDecl)->getNumParams() 2451 : FDecl && isa<ObjCMethodDecl>(FDecl) 2452 ? cast<ObjCMethodDecl>(FDecl)->param_size() 2453 : 0; 2454 2455 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 2456 // Args[ArgIdx] can be null in malformed code. 2457 if (const Expr *Arg = Args[ArgIdx]) { 2458 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 2459 checkVariadicArgument(Arg, CallType); 2460 } 2461 } 2462 } 2463 2464 if (FDecl || Proto) { 2465 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 2466 2467 // Type safety checking. 2468 if (FDecl) { 2469 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 2470 CheckArgumentWithTypeTag(I, Args.data()); 2471 } 2472 } 2473 } 2474 2475 /// CheckConstructorCall - Check a constructor call for correctness and safety 2476 /// properties not enforced by the C type system. 2477 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 2478 ArrayRef<const Expr *> Args, 2479 const FunctionProtoType *Proto, 2480 SourceLocation Loc) { 2481 VariadicCallType CallType = 2482 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 2483 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(), 2484 CallType); 2485 } 2486 2487 /// CheckFunctionCall - Check a direct function call for various correctness 2488 /// and safety properties not strictly enforced by the C type system. 2489 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2490 const FunctionProtoType *Proto) { 2491 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 2492 isa<CXXMethodDecl>(FDecl); 2493 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 2494 IsMemberOperatorCall; 2495 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 2496 TheCall->getCallee()); 2497 Expr** Args = TheCall->getArgs(); 2498 unsigned NumArgs = TheCall->getNumArgs(); 2499 if (IsMemberOperatorCall) { 2500 // If this is a call to a member operator, hide the first argument 2501 // from checkCall. 2502 // FIXME: Our choice of AST representation here is less than ideal. 2503 ++Args; 2504 --NumArgs; 2505 } 2506 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs), 2507 IsMemberFunction, TheCall->getRParenLoc(), 2508 TheCall->getCallee()->getSourceRange(), CallType); 2509 2510 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 2511 // None of the checks below are needed for functions that don't have 2512 // simple names (e.g., C++ conversion functions). 2513 if (!FnInfo) 2514 return false; 2515 2516 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo); 2517 if (getLangOpts().ObjC1) 2518 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 2519 2520 unsigned CMId = FDecl->getMemoryFunctionKind(); 2521 if (CMId == 0) 2522 return false; 2523 2524 // Handle memory setting and copying functions. 2525 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 2526 CheckStrlcpycatArguments(TheCall, FnInfo); 2527 else if (CMId == Builtin::BIstrncat) 2528 CheckStrncatArguments(TheCall, FnInfo); 2529 else 2530 CheckMemaccessArguments(TheCall, CMId, FnInfo); 2531 2532 return false; 2533 } 2534 2535 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 2536 ArrayRef<const Expr *> Args) { 2537 VariadicCallType CallType = 2538 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 2539 2540 checkCall(Method, nullptr, Args, 2541 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 2542 CallType); 2543 2544 return false; 2545 } 2546 2547 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2548 const FunctionProtoType *Proto) { 2549 QualType Ty; 2550 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 2551 Ty = V->getType().getNonReferenceType(); 2552 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 2553 Ty = F->getType().getNonReferenceType(); 2554 else 2555 return false; 2556 2557 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 2558 !Ty->isFunctionProtoType()) 2559 return false; 2560 2561 VariadicCallType CallType; 2562 if (!Proto || !Proto->isVariadic()) { 2563 CallType = VariadicDoesNotApply; 2564 } else if (Ty->isBlockPointerType()) { 2565 CallType = VariadicBlock; 2566 } else { // Ty->isFunctionPointerType() 2567 CallType = VariadicFunction; 2568 } 2569 2570 checkCall(NDecl, Proto, 2571 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2572 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2573 TheCall->getCallee()->getSourceRange(), CallType); 2574 2575 return false; 2576 } 2577 2578 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2579 /// such as function pointers returned from functions. 2580 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 2581 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 2582 TheCall->getCallee()); 2583 checkCall(/*FDecl=*/nullptr, Proto, 2584 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 2585 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 2586 TheCall->getCallee()->getSourceRange(), CallType); 2587 2588 return false; 2589 } 2590 2591 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 2592 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 2593 return false; 2594 2595 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 2596 switch (Op) { 2597 case AtomicExpr::AO__c11_atomic_init: 2598 llvm_unreachable("There is no ordering argument for an init"); 2599 2600 case AtomicExpr::AO__c11_atomic_load: 2601 case AtomicExpr::AO__atomic_load_n: 2602 case AtomicExpr::AO__atomic_load: 2603 return OrderingCABI != llvm::AtomicOrderingCABI::release && 2604 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2605 2606 case AtomicExpr::AO__c11_atomic_store: 2607 case AtomicExpr::AO__atomic_store: 2608 case AtomicExpr::AO__atomic_store_n: 2609 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 2610 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 2611 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 2612 2613 default: 2614 return true; 2615 } 2616 } 2617 2618 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 2619 AtomicExpr::AtomicOp Op) { 2620 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 2621 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2622 2623 // All these operations take one of the following forms: 2624 enum { 2625 // C __c11_atomic_init(A *, C) 2626 Init, 2627 // C __c11_atomic_load(A *, int) 2628 Load, 2629 // void __atomic_load(A *, CP, int) 2630 LoadCopy, 2631 // void __atomic_store(A *, CP, int) 2632 Copy, 2633 // C __c11_atomic_add(A *, M, int) 2634 Arithmetic, 2635 // C __atomic_exchange_n(A *, CP, int) 2636 Xchg, 2637 // void __atomic_exchange(A *, C *, CP, int) 2638 GNUXchg, 2639 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 2640 C11CmpXchg, 2641 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 2642 GNUCmpXchg 2643 } Form = Init; 2644 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 2645 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 2646 // where: 2647 // C is an appropriate type, 2648 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 2649 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 2650 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 2651 // the int parameters are for orderings. 2652 2653 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 2654 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 2655 AtomicExpr::AO__atomic_load, 2656 "need to update code for modified C11 atomics"); 2657 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init && 2658 Op <= AtomicExpr::AO__c11_atomic_fetch_xor; 2659 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 2660 Op == AtomicExpr::AO__atomic_store_n || 2661 Op == AtomicExpr::AO__atomic_exchange_n || 2662 Op == AtomicExpr::AO__atomic_compare_exchange_n; 2663 bool IsAddSub = false; 2664 2665 switch (Op) { 2666 case AtomicExpr::AO__c11_atomic_init: 2667 Form = Init; 2668 break; 2669 2670 case AtomicExpr::AO__c11_atomic_load: 2671 case AtomicExpr::AO__atomic_load_n: 2672 Form = Load; 2673 break; 2674 2675 case AtomicExpr::AO__atomic_load: 2676 Form = LoadCopy; 2677 break; 2678 2679 case AtomicExpr::AO__c11_atomic_store: 2680 case AtomicExpr::AO__atomic_store: 2681 case AtomicExpr::AO__atomic_store_n: 2682 Form = Copy; 2683 break; 2684 2685 case AtomicExpr::AO__c11_atomic_fetch_add: 2686 case AtomicExpr::AO__c11_atomic_fetch_sub: 2687 case AtomicExpr::AO__atomic_fetch_add: 2688 case AtomicExpr::AO__atomic_fetch_sub: 2689 case AtomicExpr::AO__atomic_add_fetch: 2690 case AtomicExpr::AO__atomic_sub_fetch: 2691 IsAddSub = true; 2692 // Fall through. 2693 case AtomicExpr::AO__c11_atomic_fetch_and: 2694 case AtomicExpr::AO__c11_atomic_fetch_or: 2695 case AtomicExpr::AO__c11_atomic_fetch_xor: 2696 case AtomicExpr::AO__atomic_fetch_and: 2697 case AtomicExpr::AO__atomic_fetch_or: 2698 case AtomicExpr::AO__atomic_fetch_xor: 2699 case AtomicExpr::AO__atomic_fetch_nand: 2700 case AtomicExpr::AO__atomic_and_fetch: 2701 case AtomicExpr::AO__atomic_or_fetch: 2702 case AtomicExpr::AO__atomic_xor_fetch: 2703 case AtomicExpr::AO__atomic_nand_fetch: 2704 Form = Arithmetic; 2705 break; 2706 2707 case AtomicExpr::AO__c11_atomic_exchange: 2708 case AtomicExpr::AO__atomic_exchange_n: 2709 Form = Xchg; 2710 break; 2711 2712 case AtomicExpr::AO__atomic_exchange: 2713 Form = GNUXchg; 2714 break; 2715 2716 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 2717 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 2718 Form = C11CmpXchg; 2719 break; 2720 2721 case AtomicExpr::AO__atomic_compare_exchange: 2722 case AtomicExpr::AO__atomic_compare_exchange_n: 2723 Form = GNUCmpXchg; 2724 break; 2725 } 2726 2727 // Check we have the right number of arguments. 2728 if (TheCall->getNumArgs() < NumArgs[Form]) { 2729 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 2730 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2731 << TheCall->getCallee()->getSourceRange(); 2732 return ExprError(); 2733 } else if (TheCall->getNumArgs() > NumArgs[Form]) { 2734 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(), 2735 diag::err_typecheck_call_too_many_args) 2736 << 0 << NumArgs[Form] << TheCall->getNumArgs() 2737 << TheCall->getCallee()->getSourceRange(); 2738 return ExprError(); 2739 } 2740 2741 // Inspect the first argument of the atomic operation. 2742 Expr *Ptr = TheCall->getArg(0); 2743 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 2744 if (ConvertedPtr.isInvalid()) 2745 return ExprError(); 2746 2747 Ptr = ConvertedPtr.get(); 2748 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 2749 if (!pointerType) { 2750 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 2751 << Ptr->getType() << Ptr->getSourceRange(); 2752 return ExprError(); 2753 } 2754 2755 // For a __c11 builtin, this should be a pointer to an _Atomic type. 2756 QualType AtomTy = pointerType->getPointeeType(); // 'A' 2757 QualType ValType = AtomTy; // 'C' 2758 if (IsC11) { 2759 if (!AtomTy->isAtomicType()) { 2760 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 2761 << Ptr->getType() << Ptr->getSourceRange(); 2762 return ExprError(); 2763 } 2764 if (AtomTy.isConstQualified()) { 2765 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 2766 << Ptr->getType() << Ptr->getSourceRange(); 2767 return ExprError(); 2768 } 2769 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 2770 } else if (Form != Load && Form != LoadCopy) { 2771 if (ValType.isConstQualified()) { 2772 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 2773 << Ptr->getType() << Ptr->getSourceRange(); 2774 return ExprError(); 2775 } 2776 } 2777 2778 // For an arithmetic operation, the implied arithmetic must be well-formed. 2779 if (Form == Arithmetic) { 2780 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 2781 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 2782 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2783 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2784 return ExprError(); 2785 } 2786 if (!IsAddSub && !ValType->isIntegerType()) { 2787 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 2788 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2789 return ExprError(); 2790 } 2791 if (IsC11 && ValType->isPointerType() && 2792 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 2793 diag::err_incomplete_type)) { 2794 return ExprError(); 2795 } 2796 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 2797 // For __atomic_*_n operations, the value type must be a scalar integral or 2798 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 2799 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 2800 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 2801 return ExprError(); 2802 } 2803 2804 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 2805 !AtomTy->isScalarType()) { 2806 // For GNU atomics, require a trivially-copyable type. This is not part of 2807 // the GNU atomics specification, but we enforce it for sanity. 2808 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 2809 << Ptr->getType() << Ptr->getSourceRange(); 2810 return ExprError(); 2811 } 2812 2813 switch (ValType.getObjCLifetime()) { 2814 case Qualifiers::OCL_None: 2815 case Qualifiers::OCL_ExplicitNone: 2816 // okay 2817 break; 2818 2819 case Qualifiers::OCL_Weak: 2820 case Qualifiers::OCL_Strong: 2821 case Qualifiers::OCL_Autoreleasing: 2822 // FIXME: Can this happen? By this point, ValType should be known 2823 // to be trivially copyable. 2824 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 2825 << ValType << Ptr->getSourceRange(); 2826 return ExprError(); 2827 } 2828 2829 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 2830 // volatile-ness of the pointee-type inject itself into the result or the 2831 // other operands. Similarly atomic_load can take a pointer to a const 'A'. 2832 ValType.removeLocalVolatile(); 2833 ValType.removeLocalConst(); 2834 QualType ResultType = ValType; 2835 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init) 2836 ResultType = Context.VoidTy; 2837 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 2838 ResultType = Context.BoolTy; 2839 2840 // The type of a parameter passed 'by value'. In the GNU atomics, such 2841 // arguments are actually passed as pointers. 2842 QualType ByValType = ValType; // 'CP' 2843 if (!IsC11 && !IsN) 2844 ByValType = Ptr->getType(); 2845 2846 // The first argument --- the pointer --- has a fixed type; we 2847 // deduce the types of the rest of the arguments accordingly. Walk 2848 // the remaining arguments, converting them to the deduced value type. 2849 for (unsigned i = 1; i != NumArgs[Form]; ++i) { 2850 QualType Ty; 2851 if (i < NumVals[Form] + 1) { 2852 switch (i) { 2853 case 1: 2854 // The second argument is the non-atomic operand. For arithmetic, this 2855 // is always passed by value, and for a compare_exchange it is always 2856 // passed by address. For the rest, GNU uses by-address and C11 uses 2857 // by-value. 2858 assert(Form != Load); 2859 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 2860 Ty = ValType; 2861 else if (Form == Copy || Form == Xchg) 2862 Ty = ByValType; 2863 else if (Form == Arithmetic) 2864 Ty = Context.getPointerDiffType(); 2865 else { 2866 Expr *ValArg = TheCall->getArg(i); 2867 unsigned AS = 0; 2868 // Keep address space of non-atomic pointer type. 2869 if (const PointerType *PtrTy = 2870 ValArg->getType()->getAs<PointerType>()) { 2871 AS = PtrTy->getPointeeType().getAddressSpace(); 2872 } 2873 Ty = Context.getPointerType( 2874 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 2875 } 2876 break; 2877 case 2: 2878 // The third argument to compare_exchange / GNU exchange is a 2879 // (pointer to a) desired value. 2880 Ty = ByValType; 2881 break; 2882 case 3: 2883 // The fourth argument to GNU compare_exchange is a 'weak' flag. 2884 Ty = Context.BoolTy; 2885 break; 2886 } 2887 } else { 2888 // The order(s) are always converted to int. 2889 Ty = Context.IntTy; 2890 } 2891 2892 InitializedEntity Entity = 2893 InitializedEntity::InitializeParameter(Context, Ty, false); 2894 ExprResult Arg = TheCall->getArg(i); 2895 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 2896 if (Arg.isInvalid()) 2897 return true; 2898 TheCall->setArg(i, Arg.get()); 2899 } 2900 2901 // Permute the arguments into a 'consistent' order. 2902 SmallVector<Expr*, 5> SubExprs; 2903 SubExprs.push_back(Ptr); 2904 switch (Form) { 2905 case Init: 2906 // Note, AtomicExpr::getVal1() has a special case for this atomic. 2907 SubExprs.push_back(TheCall->getArg(1)); // Val1 2908 break; 2909 case Load: 2910 SubExprs.push_back(TheCall->getArg(1)); // Order 2911 break; 2912 case LoadCopy: 2913 case Copy: 2914 case Arithmetic: 2915 case Xchg: 2916 SubExprs.push_back(TheCall->getArg(2)); // Order 2917 SubExprs.push_back(TheCall->getArg(1)); // Val1 2918 break; 2919 case GNUXchg: 2920 // Note, AtomicExpr::getVal2() has a special case for this atomic. 2921 SubExprs.push_back(TheCall->getArg(3)); // Order 2922 SubExprs.push_back(TheCall->getArg(1)); // Val1 2923 SubExprs.push_back(TheCall->getArg(2)); // Val2 2924 break; 2925 case C11CmpXchg: 2926 SubExprs.push_back(TheCall->getArg(3)); // Order 2927 SubExprs.push_back(TheCall->getArg(1)); // Val1 2928 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 2929 SubExprs.push_back(TheCall->getArg(2)); // Val2 2930 break; 2931 case GNUCmpXchg: 2932 SubExprs.push_back(TheCall->getArg(4)); // Order 2933 SubExprs.push_back(TheCall->getArg(1)); // Val1 2934 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 2935 SubExprs.push_back(TheCall->getArg(2)); // Val2 2936 SubExprs.push_back(TheCall->getArg(3)); // Weak 2937 break; 2938 } 2939 2940 if (SubExprs.size() >= 2 && Form != Init) { 2941 llvm::APSInt Result(32); 2942 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 2943 !isValidOrderingForOp(Result.getSExtValue(), Op)) 2944 Diag(SubExprs[1]->getLocStart(), 2945 diag::warn_atomic_op_has_invalid_memory_order) 2946 << SubExprs[1]->getSourceRange(); 2947 } 2948 2949 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 2950 SubExprs, ResultType, Op, 2951 TheCall->getRParenLoc()); 2952 2953 if ((Op == AtomicExpr::AO__c11_atomic_load || 2954 (Op == AtomicExpr::AO__c11_atomic_store)) && 2955 Context.AtomicUsesUnsupportedLibcall(AE)) 2956 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) << 2957 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1); 2958 2959 return AE; 2960 } 2961 2962 /// checkBuiltinArgument - Given a call to a builtin function, perform 2963 /// normal type-checking on the given argument, updating the call in 2964 /// place. This is useful when a builtin function requires custom 2965 /// type-checking for some of its arguments but not necessarily all of 2966 /// them. 2967 /// 2968 /// Returns true on error. 2969 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 2970 FunctionDecl *Fn = E->getDirectCallee(); 2971 assert(Fn && "builtin call without direct callee!"); 2972 2973 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 2974 InitializedEntity Entity = 2975 InitializedEntity::InitializeParameter(S.Context, Param); 2976 2977 ExprResult Arg = E->getArg(0); 2978 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 2979 if (Arg.isInvalid()) 2980 return true; 2981 2982 E->setArg(ArgIndex, Arg.get()); 2983 return false; 2984 } 2985 2986 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 2987 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 2988 /// type of its first argument. The main ActOnCallExpr routines have already 2989 /// promoted the types of arguments because all of these calls are prototyped as 2990 /// void(...). 2991 /// 2992 /// This function goes through and does final semantic checking for these 2993 /// builtins, 2994 ExprResult 2995 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 2996 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 2997 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2998 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 2999 3000 // Ensure that we have at least one argument to do type inference from. 3001 if (TheCall->getNumArgs() < 1) { 3002 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3003 << 0 << 1 << TheCall->getNumArgs() 3004 << TheCall->getCallee()->getSourceRange(); 3005 return ExprError(); 3006 } 3007 3008 // Inspect the first argument of the atomic builtin. This should always be 3009 // a pointer type, whose element is an integral scalar or pointer type. 3010 // Because it is a pointer type, we don't have to worry about any implicit 3011 // casts here. 3012 // FIXME: We don't allow floating point scalars as input. 3013 Expr *FirstArg = TheCall->getArg(0); 3014 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3015 if (FirstArgResult.isInvalid()) 3016 return ExprError(); 3017 FirstArg = FirstArgResult.get(); 3018 TheCall->setArg(0, FirstArg); 3019 3020 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3021 if (!pointerType) { 3022 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3023 << FirstArg->getType() << FirstArg->getSourceRange(); 3024 return ExprError(); 3025 } 3026 3027 QualType ValType = pointerType->getPointeeType(); 3028 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3029 !ValType->isBlockPointerType()) { 3030 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3031 << FirstArg->getType() << FirstArg->getSourceRange(); 3032 return ExprError(); 3033 } 3034 3035 switch (ValType.getObjCLifetime()) { 3036 case Qualifiers::OCL_None: 3037 case Qualifiers::OCL_ExplicitNone: 3038 // okay 3039 break; 3040 3041 case Qualifiers::OCL_Weak: 3042 case Qualifiers::OCL_Strong: 3043 case Qualifiers::OCL_Autoreleasing: 3044 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3045 << ValType << FirstArg->getSourceRange(); 3046 return ExprError(); 3047 } 3048 3049 // Strip any qualifiers off ValType. 3050 ValType = ValType.getUnqualifiedType(); 3051 3052 // The majority of builtins return a value, but a few have special return 3053 // types, so allow them to override appropriately below. 3054 QualType ResultType = ValType; 3055 3056 // We need to figure out which concrete builtin this maps onto. For example, 3057 // __sync_fetch_and_add with a 2 byte object turns into 3058 // __sync_fetch_and_add_2. 3059 #define BUILTIN_ROW(x) \ 3060 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3061 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3062 3063 static const unsigned BuiltinIndices[][5] = { 3064 BUILTIN_ROW(__sync_fetch_and_add), 3065 BUILTIN_ROW(__sync_fetch_and_sub), 3066 BUILTIN_ROW(__sync_fetch_and_or), 3067 BUILTIN_ROW(__sync_fetch_and_and), 3068 BUILTIN_ROW(__sync_fetch_and_xor), 3069 BUILTIN_ROW(__sync_fetch_and_nand), 3070 3071 BUILTIN_ROW(__sync_add_and_fetch), 3072 BUILTIN_ROW(__sync_sub_and_fetch), 3073 BUILTIN_ROW(__sync_and_and_fetch), 3074 BUILTIN_ROW(__sync_or_and_fetch), 3075 BUILTIN_ROW(__sync_xor_and_fetch), 3076 BUILTIN_ROW(__sync_nand_and_fetch), 3077 3078 BUILTIN_ROW(__sync_val_compare_and_swap), 3079 BUILTIN_ROW(__sync_bool_compare_and_swap), 3080 BUILTIN_ROW(__sync_lock_test_and_set), 3081 BUILTIN_ROW(__sync_lock_release), 3082 BUILTIN_ROW(__sync_swap) 3083 }; 3084 #undef BUILTIN_ROW 3085 3086 // Determine the index of the size. 3087 unsigned SizeIndex; 3088 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3089 case 1: SizeIndex = 0; break; 3090 case 2: SizeIndex = 1; break; 3091 case 4: SizeIndex = 2; break; 3092 case 8: SizeIndex = 3; break; 3093 case 16: SizeIndex = 4; break; 3094 default: 3095 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3096 << FirstArg->getType() << FirstArg->getSourceRange(); 3097 return ExprError(); 3098 } 3099 3100 // Each of these builtins has one pointer argument, followed by some number of 3101 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3102 // that we ignore. Find out which row of BuiltinIndices to read from as well 3103 // as the number of fixed args. 3104 unsigned BuiltinID = FDecl->getBuiltinID(); 3105 unsigned BuiltinIndex, NumFixed = 1; 3106 bool WarnAboutSemanticsChange = false; 3107 switch (BuiltinID) { 3108 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3109 case Builtin::BI__sync_fetch_and_add: 3110 case Builtin::BI__sync_fetch_and_add_1: 3111 case Builtin::BI__sync_fetch_and_add_2: 3112 case Builtin::BI__sync_fetch_and_add_4: 3113 case Builtin::BI__sync_fetch_and_add_8: 3114 case Builtin::BI__sync_fetch_and_add_16: 3115 BuiltinIndex = 0; 3116 break; 3117 3118 case Builtin::BI__sync_fetch_and_sub: 3119 case Builtin::BI__sync_fetch_and_sub_1: 3120 case Builtin::BI__sync_fetch_and_sub_2: 3121 case Builtin::BI__sync_fetch_and_sub_4: 3122 case Builtin::BI__sync_fetch_and_sub_8: 3123 case Builtin::BI__sync_fetch_and_sub_16: 3124 BuiltinIndex = 1; 3125 break; 3126 3127 case Builtin::BI__sync_fetch_and_or: 3128 case Builtin::BI__sync_fetch_and_or_1: 3129 case Builtin::BI__sync_fetch_and_or_2: 3130 case Builtin::BI__sync_fetch_and_or_4: 3131 case Builtin::BI__sync_fetch_and_or_8: 3132 case Builtin::BI__sync_fetch_and_or_16: 3133 BuiltinIndex = 2; 3134 break; 3135 3136 case Builtin::BI__sync_fetch_and_and: 3137 case Builtin::BI__sync_fetch_and_and_1: 3138 case Builtin::BI__sync_fetch_and_and_2: 3139 case Builtin::BI__sync_fetch_and_and_4: 3140 case Builtin::BI__sync_fetch_and_and_8: 3141 case Builtin::BI__sync_fetch_and_and_16: 3142 BuiltinIndex = 3; 3143 break; 3144 3145 case Builtin::BI__sync_fetch_and_xor: 3146 case Builtin::BI__sync_fetch_and_xor_1: 3147 case Builtin::BI__sync_fetch_and_xor_2: 3148 case Builtin::BI__sync_fetch_and_xor_4: 3149 case Builtin::BI__sync_fetch_and_xor_8: 3150 case Builtin::BI__sync_fetch_and_xor_16: 3151 BuiltinIndex = 4; 3152 break; 3153 3154 case Builtin::BI__sync_fetch_and_nand: 3155 case Builtin::BI__sync_fetch_and_nand_1: 3156 case Builtin::BI__sync_fetch_and_nand_2: 3157 case Builtin::BI__sync_fetch_and_nand_4: 3158 case Builtin::BI__sync_fetch_and_nand_8: 3159 case Builtin::BI__sync_fetch_and_nand_16: 3160 BuiltinIndex = 5; 3161 WarnAboutSemanticsChange = true; 3162 break; 3163 3164 case Builtin::BI__sync_add_and_fetch: 3165 case Builtin::BI__sync_add_and_fetch_1: 3166 case Builtin::BI__sync_add_and_fetch_2: 3167 case Builtin::BI__sync_add_and_fetch_4: 3168 case Builtin::BI__sync_add_and_fetch_8: 3169 case Builtin::BI__sync_add_and_fetch_16: 3170 BuiltinIndex = 6; 3171 break; 3172 3173 case Builtin::BI__sync_sub_and_fetch: 3174 case Builtin::BI__sync_sub_and_fetch_1: 3175 case Builtin::BI__sync_sub_and_fetch_2: 3176 case Builtin::BI__sync_sub_and_fetch_4: 3177 case Builtin::BI__sync_sub_and_fetch_8: 3178 case Builtin::BI__sync_sub_and_fetch_16: 3179 BuiltinIndex = 7; 3180 break; 3181 3182 case Builtin::BI__sync_and_and_fetch: 3183 case Builtin::BI__sync_and_and_fetch_1: 3184 case Builtin::BI__sync_and_and_fetch_2: 3185 case Builtin::BI__sync_and_and_fetch_4: 3186 case Builtin::BI__sync_and_and_fetch_8: 3187 case Builtin::BI__sync_and_and_fetch_16: 3188 BuiltinIndex = 8; 3189 break; 3190 3191 case Builtin::BI__sync_or_and_fetch: 3192 case Builtin::BI__sync_or_and_fetch_1: 3193 case Builtin::BI__sync_or_and_fetch_2: 3194 case Builtin::BI__sync_or_and_fetch_4: 3195 case Builtin::BI__sync_or_and_fetch_8: 3196 case Builtin::BI__sync_or_and_fetch_16: 3197 BuiltinIndex = 9; 3198 break; 3199 3200 case Builtin::BI__sync_xor_and_fetch: 3201 case Builtin::BI__sync_xor_and_fetch_1: 3202 case Builtin::BI__sync_xor_and_fetch_2: 3203 case Builtin::BI__sync_xor_and_fetch_4: 3204 case Builtin::BI__sync_xor_and_fetch_8: 3205 case Builtin::BI__sync_xor_and_fetch_16: 3206 BuiltinIndex = 10; 3207 break; 3208 3209 case Builtin::BI__sync_nand_and_fetch: 3210 case Builtin::BI__sync_nand_and_fetch_1: 3211 case Builtin::BI__sync_nand_and_fetch_2: 3212 case Builtin::BI__sync_nand_and_fetch_4: 3213 case Builtin::BI__sync_nand_and_fetch_8: 3214 case Builtin::BI__sync_nand_and_fetch_16: 3215 BuiltinIndex = 11; 3216 WarnAboutSemanticsChange = true; 3217 break; 3218 3219 case Builtin::BI__sync_val_compare_and_swap: 3220 case Builtin::BI__sync_val_compare_and_swap_1: 3221 case Builtin::BI__sync_val_compare_and_swap_2: 3222 case Builtin::BI__sync_val_compare_and_swap_4: 3223 case Builtin::BI__sync_val_compare_and_swap_8: 3224 case Builtin::BI__sync_val_compare_and_swap_16: 3225 BuiltinIndex = 12; 3226 NumFixed = 2; 3227 break; 3228 3229 case Builtin::BI__sync_bool_compare_and_swap: 3230 case Builtin::BI__sync_bool_compare_and_swap_1: 3231 case Builtin::BI__sync_bool_compare_and_swap_2: 3232 case Builtin::BI__sync_bool_compare_and_swap_4: 3233 case Builtin::BI__sync_bool_compare_and_swap_8: 3234 case Builtin::BI__sync_bool_compare_and_swap_16: 3235 BuiltinIndex = 13; 3236 NumFixed = 2; 3237 ResultType = Context.BoolTy; 3238 break; 3239 3240 case Builtin::BI__sync_lock_test_and_set: 3241 case Builtin::BI__sync_lock_test_and_set_1: 3242 case Builtin::BI__sync_lock_test_and_set_2: 3243 case Builtin::BI__sync_lock_test_and_set_4: 3244 case Builtin::BI__sync_lock_test_and_set_8: 3245 case Builtin::BI__sync_lock_test_and_set_16: 3246 BuiltinIndex = 14; 3247 break; 3248 3249 case Builtin::BI__sync_lock_release: 3250 case Builtin::BI__sync_lock_release_1: 3251 case Builtin::BI__sync_lock_release_2: 3252 case Builtin::BI__sync_lock_release_4: 3253 case Builtin::BI__sync_lock_release_8: 3254 case Builtin::BI__sync_lock_release_16: 3255 BuiltinIndex = 15; 3256 NumFixed = 0; 3257 ResultType = Context.VoidTy; 3258 break; 3259 3260 case Builtin::BI__sync_swap: 3261 case Builtin::BI__sync_swap_1: 3262 case Builtin::BI__sync_swap_2: 3263 case Builtin::BI__sync_swap_4: 3264 case Builtin::BI__sync_swap_8: 3265 case Builtin::BI__sync_swap_16: 3266 BuiltinIndex = 16; 3267 break; 3268 } 3269 3270 // Now that we know how many fixed arguments we expect, first check that we 3271 // have at least that many. 3272 if (TheCall->getNumArgs() < 1+NumFixed) { 3273 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3274 << 0 << 1+NumFixed << TheCall->getNumArgs() 3275 << TheCall->getCallee()->getSourceRange(); 3276 return ExprError(); 3277 } 3278 3279 if (WarnAboutSemanticsChange) { 3280 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 3281 << TheCall->getCallee()->getSourceRange(); 3282 } 3283 3284 // Get the decl for the concrete builtin from this, we can tell what the 3285 // concrete integer type we should convert to is. 3286 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 3287 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 3288 FunctionDecl *NewBuiltinDecl; 3289 if (NewBuiltinID == BuiltinID) 3290 NewBuiltinDecl = FDecl; 3291 else { 3292 // Perform builtin lookup to avoid redeclaring it. 3293 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 3294 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 3295 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 3296 assert(Res.getFoundDecl()); 3297 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 3298 if (!NewBuiltinDecl) 3299 return ExprError(); 3300 } 3301 3302 // The first argument --- the pointer --- has a fixed type; we 3303 // deduce the types of the rest of the arguments accordingly. Walk 3304 // the remaining arguments, converting them to the deduced value type. 3305 for (unsigned i = 0; i != NumFixed; ++i) { 3306 ExprResult Arg = TheCall->getArg(i+1); 3307 3308 // GCC does an implicit conversion to the pointer or integer ValType. This 3309 // can fail in some cases (1i -> int**), check for this error case now. 3310 // Initialize the argument. 3311 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3312 ValType, /*consume*/ false); 3313 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3314 if (Arg.isInvalid()) 3315 return ExprError(); 3316 3317 // Okay, we have something that *can* be converted to the right type. Check 3318 // to see if there is a potentially weird extension going on here. This can 3319 // happen when you do an atomic operation on something like an char* and 3320 // pass in 42. The 42 gets converted to char. This is even more strange 3321 // for things like 45.123 -> char, etc. 3322 // FIXME: Do this check. 3323 TheCall->setArg(i+1, Arg.get()); 3324 } 3325 3326 ASTContext& Context = this->getASTContext(); 3327 3328 // Create a new DeclRefExpr to refer to the new decl. 3329 DeclRefExpr* NewDRE = DeclRefExpr::Create( 3330 Context, 3331 DRE->getQualifierLoc(), 3332 SourceLocation(), 3333 NewBuiltinDecl, 3334 /*enclosing*/ false, 3335 DRE->getLocation(), 3336 Context.BuiltinFnTy, 3337 DRE->getValueKind()); 3338 3339 // Set the callee in the CallExpr. 3340 // FIXME: This loses syntactic information. 3341 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 3342 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 3343 CK_BuiltinFnToFnPtr); 3344 TheCall->setCallee(PromotedCall.get()); 3345 3346 // Change the result type of the call to match the original value type. This 3347 // is arbitrary, but the codegen for these builtins ins design to handle it 3348 // gracefully. 3349 TheCall->setType(ResultType); 3350 3351 return TheCallResult; 3352 } 3353 3354 /// SemaBuiltinNontemporalOverloaded - We have a call to 3355 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 3356 /// overloaded function based on the pointer type of its last argument. 3357 /// 3358 /// This function goes through and does final semantic checking for these 3359 /// builtins. 3360 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 3361 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3362 DeclRefExpr *DRE = 3363 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3364 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3365 unsigned BuiltinID = FDecl->getBuiltinID(); 3366 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 3367 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 3368 "Unexpected nontemporal load/store builtin!"); 3369 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 3370 unsigned numArgs = isStore ? 2 : 1; 3371 3372 // Ensure that we have the proper number of arguments. 3373 if (checkArgCount(*this, TheCall, numArgs)) 3374 return ExprError(); 3375 3376 // Inspect the last argument of the nontemporal builtin. This should always 3377 // be a pointer type, from which we imply the type of the memory access. 3378 // Because it is a pointer type, we don't have to worry about any implicit 3379 // casts here. 3380 Expr *PointerArg = TheCall->getArg(numArgs - 1); 3381 ExprResult PointerArgResult = 3382 DefaultFunctionArrayLvalueConversion(PointerArg); 3383 3384 if (PointerArgResult.isInvalid()) 3385 return ExprError(); 3386 PointerArg = PointerArgResult.get(); 3387 TheCall->setArg(numArgs - 1, PointerArg); 3388 3389 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 3390 if (!pointerType) { 3391 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 3392 << PointerArg->getType() << PointerArg->getSourceRange(); 3393 return ExprError(); 3394 } 3395 3396 QualType ValType = pointerType->getPointeeType(); 3397 3398 // Strip any qualifiers off ValType. 3399 ValType = ValType.getUnqualifiedType(); 3400 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3401 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 3402 !ValType->isVectorType()) { 3403 Diag(DRE->getLocStart(), 3404 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 3405 << PointerArg->getType() << PointerArg->getSourceRange(); 3406 return ExprError(); 3407 } 3408 3409 if (!isStore) { 3410 TheCall->setType(ValType); 3411 return TheCallResult; 3412 } 3413 3414 ExprResult ValArg = TheCall->getArg(0); 3415 InitializedEntity Entity = InitializedEntity::InitializeParameter( 3416 Context, ValType, /*consume*/ false); 3417 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 3418 if (ValArg.isInvalid()) 3419 return ExprError(); 3420 3421 TheCall->setArg(0, ValArg.get()); 3422 TheCall->setType(Context.VoidTy); 3423 return TheCallResult; 3424 } 3425 3426 /// CheckObjCString - Checks that the argument to the builtin 3427 /// CFString constructor is correct 3428 /// Note: It might also make sense to do the UTF-16 conversion here (would 3429 /// simplify the backend). 3430 bool Sema::CheckObjCString(Expr *Arg) { 3431 Arg = Arg->IgnoreParenCasts(); 3432 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 3433 3434 if (!Literal || !Literal->isAscii()) { 3435 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 3436 << Arg->getSourceRange(); 3437 return true; 3438 } 3439 3440 if (Literal->containsNonAsciiOrNull()) { 3441 StringRef String = Literal->getString(); 3442 unsigned NumBytes = String.size(); 3443 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 3444 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 3445 llvm::UTF16 *ToPtr = &ToBuf[0]; 3446 3447 llvm::ConversionResult Result = 3448 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 3449 ToPtr + NumBytes, llvm::strictConversion); 3450 // Check for conversion failure. 3451 if (Result != llvm::conversionOK) 3452 Diag(Arg->getLocStart(), 3453 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 3454 } 3455 return false; 3456 } 3457 3458 /// CheckObjCString - Checks that the format string argument to the os_log() 3459 /// and os_trace() functions is correct, and converts it to const char *. 3460 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 3461 Arg = Arg->IgnoreParenCasts(); 3462 auto *Literal = dyn_cast<StringLiteral>(Arg); 3463 if (!Literal) { 3464 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 3465 Literal = ObjcLiteral->getString(); 3466 } 3467 } 3468 3469 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 3470 return ExprError( 3471 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 3472 << Arg->getSourceRange()); 3473 } 3474 3475 ExprResult Result(Literal); 3476 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 3477 InitializedEntity Entity = 3478 InitializedEntity::InitializeParameter(Context, ResultTy, false); 3479 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 3480 return Result; 3481 } 3482 3483 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 3484 /// for validity. Emit an error and return true on failure; return false 3485 /// on success. 3486 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) { 3487 Expr *Fn = TheCall->getCallee(); 3488 if (TheCall->getNumArgs() > 2) { 3489 Diag(TheCall->getArg(2)->getLocStart(), 3490 diag::err_typecheck_call_too_many_args) 3491 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3492 << Fn->getSourceRange() 3493 << SourceRange(TheCall->getArg(2)->getLocStart(), 3494 (*(TheCall->arg_end()-1))->getLocEnd()); 3495 return true; 3496 } 3497 3498 if (TheCall->getNumArgs() < 2) { 3499 return Diag(TheCall->getLocEnd(), 3500 diag::err_typecheck_call_too_few_args_at_least) 3501 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 3502 } 3503 3504 // Type-check the first argument normally. 3505 if (checkBuiltinArgument(*this, TheCall, 0)) 3506 return true; 3507 3508 // Determine whether the current function is variadic or not. 3509 BlockScopeInfo *CurBlock = getCurBlock(); 3510 bool isVariadic; 3511 if (CurBlock) 3512 isVariadic = CurBlock->TheDecl->isVariadic(); 3513 else if (FunctionDecl *FD = getCurFunctionDecl()) 3514 isVariadic = FD->isVariadic(); 3515 else 3516 isVariadic = getCurMethodDecl()->isVariadic(); 3517 3518 if (!isVariadic) { 3519 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 3520 return true; 3521 } 3522 3523 // Verify that the second argument to the builtin is the last argument of the 3524 // current function or method. 3525 bool SecondArgIsLastNamedArgument = false; 3526 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 3527 3528 // These are valid if SecondArgIsLastNamedArgument is false after the next 3529 // block. 3530 QualType Type; 3531 SourceLocation ParamLoc; 3532 bool IsCRegister = false; 3533 3534 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 3535 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 3536 // FIXME: This isn't correct for methods (results in bogus warning). 3537 // Get the last formal in the current function. 3538 const ParmVarDecl *LastArg; 3539 if (CurBlock) 3540 LastArg = CurBlock->TheDecl->parameters().back(); 3541 else if (FunctionDecl *FD = getCurFunctionDecl()) 3542 LastArg = FD->parameters().back(); 3543 else 3544 LastArg = getCurMethodDecl()->parameters().back(); 3545 SecondArgIsLastNamedArgument = PV == LastArg; 3546 3547 Type = PV->getType(); 3548 ParamLoc = PV->getLocation(); 3549 IsCRegister = 3550 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 3551 } 3552 } 3553 3554 if (!SecondArgIsLastNamedArgument) 3555 Diag(TheCall->getArg(1)->getLocStart(), 3556 diag::warn_second_arg_of_va_start_not_last_named_param); 3557 else if (IsCRegister || Type->isReferenceType() || 3558 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 3559 // Promotable integers are UB, but enumerations need a bit of 3560 // extra checking to see what their promotable type actually is. 3561 if (!Type->isPromotableIntegerType()) 3562 return false; 3563 if (!Type->isEnumeralType()) 3564 return true; 3565 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 3566 return !(ED && 3567 Context.typesAreCompatible(ED->getPromotionType(), Type)); 3568 }()) { 3569 unsigned Reason = 0; 3570 if (Type->isReferenceType()) Reason = 1; 3571 else if (IsCRegister) Reason = 2; 3572 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 3573 Diag(ParamLoc, diag::note_parameter_type) << Type; 3574 } 3575 3576 TheCall->setType(Context.VoidTy); 3577 return false; 3578 } 3579 3580 /// Check the arguments to '__builtin_va_start' for validity, and that 3581 /// it was called from a function of the native ABI. 3582 /// Emit an error and return true on failure; return false on success. 3583 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 3584 // On x86-64 Unix, don't allow this in Win64 ABI functions. 3585 // On x64 Windows, don't allow this in System V ABI functions. 3586 // (Yes, that means there's no corresponding way to support variadic 3587 // System V ABI functions on Windows.) 3588 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) { 3589 unsigned OS = Context.getTargetInfo().getTriple().getOS(); 3590 clang::CallingConv CC = CC_C; 3591 if (const FunctionDecl *FD = getCurFunctionDecl()) 3592 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3593 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) || 3594 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64)) 3595 return Diag(TheCall->getCallee()->getLocStart(), 3596 diag::err_va_start_used_in_wrong_abi_function) 3597 << (OS != llvm::Triple::Win32); 3598 } 3599 return SemaBuiltinVAStartImpl(TheCall); 3600 } 3601 3602 /// Check the arguments to '__builtin_ms_va_start' for validity, and that 3603 /// it was called from a Win64 ABI function. 3604 /// Emit an error and return true on failure; return false on success. 3605 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) { 3606 // This only makes sense for x86-64. 3607 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3608 Expr *Callee = TheCall->getCallee(); 3609 if (TT.getArch() != llvm::Triple::x86_64) 3610 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt); 3611 // Don't allow this in System V ABI functions. 3612 clang::CallingConv CC = CC_C; 3613 if (const FunctionDecl *FD = getCurFunctionDecl()) 3614 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 3615 if (CC == CC_X86_64SysV || 3616 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64)) 3617 return Diag(Callee->getLocStart(), 3618 diag::err_ms_va_start_used_in_sysv_function); 3619 return SemaBuiltinVAStartImpl(TheCall); 3620 } 3621 3622 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) { 3623 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 3624 // const char *named_addr); 3625 3626 Expr *Func = Call->getCallee(); 3627 3628 if (Call->getNumArgs() < 3) 3629 return Diag(Call->getLocEnd(), 3630 diag::err_typecheck_call_too_few_args_at_least) 3631 << 0 /*function call*/ << 3 << Call->getNumArgs(); 3632 3633 // Determine whether the current function is variadic or not. 3634 bool IsVariadic; 3635 if (BlockScopeInfo *CurBlock = getCurBlock()) 3636 IsVariadic = CurBlock->TheDecl->isVariadic(); 3637 else if (FunctionDecl *FD = getCurFunctionDecl()) 3638 IsVariadic = FD->isVariadic(); 3639 else if (ObjCMethodDecl *MD = getCurMethodDecl()) 3640 IsVariadic = MD->isVariadic(); 3641 else 3642 llvm_unreachable("unexpected statement type"); 3643 3644 if (!IsVariadic) { 3645 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 3646 return true; 3647 } 3648 3649 // Type-check the first argument normally. 3650 if (checkBuiltinArgument(*this, Call, 0)) 3651 return true; 3652 3653 const struct { 3654 unsigned ArgNo; 3655 QualType Type; 3656 } ArgumentTypes[] = { 3657 { 1, Context.getPointerType(Context.CharTy.withConst()) }, 3658 { 2, Context.getSizeType() }, 3659 }; 3660 3661 for (const auto &AT : ArgumentTypes) { 3662 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens(); 3663 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType()) 3664 continue; 3665 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible) 3666 << Arg->getType() << AT.Type << 1 /* different class */ 3667 << 0 /* qualifier difference */ << 3 /* parameter mismatch */ 3668 << AT.ArgNo + 1 << Arg->getType() << AT.Type; 3669 } 3670 3671 return false; 3672 } 3673 3674 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 3675 /// friends. This is declared to take (...), so we have to check everything. 3676 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 3677 if (TheCall->getNumArgs() < 2) 3678 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3679 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 3680 if (TheCall->getNumArgs() > 2) 3681 return Diag(TheCall->getArg(2)->getLocStart(), 3682 diag::err_typecheck_call_too_many_args) 3683 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3684 << SourceRange(TheCall->getArg(2)->getLocStart(), 3685 (*(TheCall->arg_end()-1))->getLocEnd()); 3686 3687 ExprResult OrigArg0 = TheCall->getArg(0); 3688 ExprResult OrigArg1 = TheCall->getArg(1); 3689 3690 // Do standard promotions between the two arguments, returning their common 3691 // type. 3692 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 3693 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 3694 return true; 3695 3696 // Make sure any conversions are pushed back into the call; this is 3697 // type safe since unordered compare builtins are declared as "_Bool 3698 // foo(...)". 3699 TheCall->setArg(0, OrigArg0.get()); 3700 TheCall->setArg(1, OrigArg1.get()); 3701 3702 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 3703 return false; 3704 3705 // If the common type isn't a real floating type, then the arguments were 3706 // invalid for this operation. 3707 if (Res.isNull() || !Res->isRealFloatingType()) 3708 return Diag(OrigArg0.get()->getLocStart(), 3709 diag::err_typecheck_call_invalid_ordered_compare) 3710 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 3711 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 3712 3713 return false; 3714 } 3715 3716 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 3717 /// __builtin_isnan and friends. This is declared to take (...), so we have 3718 /// to check everything. We expect the last argument to be a floating point 3719 /// value. 3720 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 3721 if (TheCall->getNumArgs() < NumArgs) 3722 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3723 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 3724 if (TheCall->getNumArgs() > NumArgs) 3725 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 3726 diag::err_typecheck_call_too_many_args) 3727 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 3728 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 3729 (*(TheCall->arg_end()-1))->getLocEnd()); 3730 3731 Expr *OrigArg = TheCall->getArg(NumArgs-1); 3732 3733 if (OrigArg->isTypeDependent()) 3734 return false; 3735 3736 // This operation requires a non-_Complex floating-point number. 3737 if (!OrigArg->getType()->isRealFloatingType()) 3738 return Diag(OrigArg->getLocStart(), 3739 diag::err_typecheck_call_invalid_unary_fp) 3740 << OrigArg->getType() << OrigArg->getSourceRange(); 3741 3742 // If this is an implicit conversion from float -> double, remove it. 3743 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 3744 Expr *CastArg = Cast->getSubExpr(); 3745 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 3746 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 3747 "promotion from float to double is the only expected cast here"); 3748 Cast->setSubExpr(nullptr); 3749 TheCall->setArg(NumArgs-1, CastArg); 3750 } 3751 } 3752 3753 return false; 3754 } 3755 3756 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 3757 // This is declared to take (...), so we have to check everything. 3758 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 3759 if (TheCall->getNumArgs() < 2) 3760 return ExprError(Diag(TheCall->getLocEnd(), 3761 diag::err_typecheck_call_too_few_args_at_least) 3762 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 3763 << TheCall->getSourceRange()); 3764 3765 // Determine which of the following types of shufflevector we're checking: 3766 // 1) unary, vector mask: (lhs, mask) 3767 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 3768 QualType resType = TheCall->getArg(0)->getType(); 3769 unsigned numElements = 0; 3770 3771 if (!TheCall->getArg(0)->isTypeDependent() && 3772 !TheCall->getArg(1)->isTypeDependent()) { 3773 QualType LHSType = TheCall->getArg(0)->getType(); 3774 QualType RHSType = TheCall->getArg(1)->getType(); 3775 3776 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 3777 return ExprError(Diag(TheCall->getLocStart(), 3778 diag::err_shufflevector_non_vector) 3779 << SourceRange(TheCall->getArg(0)->getLocStart(), 3780 TheCall->getArg(1)->getLocEnd())); 3781 3782 numElements = LHSType->getAs<VectorType>()->getNumElements(); 3783 unsigned numResElements = TheCall->getNumArgs() - 2; 3784 3785 // Check to see if we have a call with 2 vector arguments, the unary shuffle 3786 // with mask. If so, verify that RHS is an integer vector type with the 3787 // same number of elts as lhs. 3788 if (TheCall->getNumArgs() == 2) { 3789 if (!RHSType->hasIntegerRepresentation() || 3790 RHSType->getAs<VectorType>()->getNumElements() != numElements) 3791 return ExprError(Diag(TheCall->getLocStart(), 3792 diag::err_shufflevector_incompatible_vector) 3793 << SourceRange(TheCall->getArg(1)->getLocStart(), 3794 TheCall->getArg(1)->getLocEnd())); 3795 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 3796 return ExprError(Diag(TheCall->getLocStart(), 3797 diag::err_shufflevector_incompatible_vector) 3798 << SourceRange(TheCall->getArg(0)->getLocStart(), 3799 TheCall->getArg(1)->getLocEnd())); 3800 } else if (numElements != numResElements) { 3801 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 3802 resType = Context.getVectorType(eltType, numResElements, 3803 VectorType::GenericVector); 3804 } 3805 } 3806 3807 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 3808 if (TheCall->getArg(i)->isTypeDependent() || 3809 TheCall->getArg(i)->isValueDependent()) 3810 continue; 3811 3812 llvm::APSInt Result(32); 3813 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 3814 return ExprError(Diag(TheCall->getLocStart(), 3815 diag::err_shufflevector_nonconstant_argument) 3816 << TheCall->getArg(i)->getSourceRange()); 3817 3818 // Allow -1 which will be translated to undef in the IR. 3819 if (Result.isSigned() && Result.isAllOnesValue()) 3820 continue; 3821 3822 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 3823 return ExprError(Diag(TheCall->getLocStart(), 3824 diag::err_shufflevector_argument_too_large) 3825 << TheCall->getArg(i)->getSourceRange()); 3826 } 3827 3828 SmallVector<Expr*, 32> exprs; 3829 3830 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 3831 exprs.push_back(TheCall->getArg(i)); 3832 TheCall->setArg(i, nullptr); 3833 } 3834 3835 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 3836 TheCall->getCallee()->getLocStart(), 3837 TheCall->getRParenLoc()); 3838 } 3839 3840 /// SemaConvertVectorExpr - Handle __builtin_convertvector 3841 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 3842 SourceLocation BuiltinLoc, 3843 SourceLocation RParenLoc) { 3844 ExprValueKind VK = VK_RValue; 3845 ExprObjectKind OK = OK_Ordinary; 3846 QualType DstTy = TInfo->getType(); 3847 QualType SrcTy = E->getType(); 3848 3849 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 3850 return ExprError(Diag(BuiltinLoc, 3851 diag::err_convertvector_non_vector) 3852 << E->getSourceRange()); 3853 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 3854 return ExprError(Diag(BuiltinLoc, 3855 diag::err_convertvector_non_vector_type)); 3856 3857 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 3858 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 3859 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 3860 if (SrcElts != DstElts) 3861 return ExprError(Diag(BuiltinLoc, 3862 diag::err_convertvector_incompatible_vector) 3863 << E->getSourceRange()); 3864 } 3865 3866 return new (Context) 3867 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 3868 } 3869 3870 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 3871 // This is declared to take (const void*, ...) and can take two 3872 // optional constant int args. 3873 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 3874 unsigned NumArgs = TheCall->getNumArgs(); 3875 3876 if (NumArgs > 3) 3877 return Diag(TheCall->getLocEnd(), 3878 diag::err_typecheck_call_too_many_args_at_most) 3879 << 0 /*function call*/ << 3 << NumArgs 3880 << TheCall->getSourceRange(); 3881 3882 // Argument 0 is checked for us and the remaining arguments must be 3883 // constant integers. 3884 for (unsigned i = 1; i != NumArgs; ++i) 3885 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 3886 return true; 3887 3888 return false; 3889 } 3890 3891 /// SemaBuiltinAssume - Handle __assume (MS Extension). 3892 // __assume does not evaluate its arguments, and should warn if its argument 3893 // has side effects. 3894 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 3895 Expr *Arg = TheCall->getArg(0); 3896 if (Arg->isInstantiationDependent()) return false; 3897 3898 if (Arg->HasSideEffects(Context)) 3899 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 3900 << Arg->getSourceRange() 3901 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 3902 3903 return false; 3904 } 3905 3906 /// Handle __builtin_alloca_with_align. This is declared 3907 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 3908 /// than 8. 3909 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 3910 // The alignment must be a constant integer. 3911 Expr *Arg = TheCall->getArg(1); 3912 3913 // We can't check the value of a dependent argument. 3914 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 3915 if (const auto *UE = 3916 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 3917 if (UE->getKind() == UETT_AlignOf) 3918 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 3919 << Arg->getSourceRange(); 3920 3921 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 3922 3923 if (!Result.isPowerOf2()) 3924 return Diag(TheCall->getLocStart(), 3925 diag::err_alignment_not_power_of_two) 3926 << Arg->getSourceRange(); 3927 3928 if (Result < Context.getCharWidth()) 3929 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 3930 << (unsigned)Context.getCharWidth() 3931 << Arg->getSourceRange(); 3932 3933 if (Result > INT32_MAX) 3934 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 3935 << INT32_MAX 3936 << Arg->getSourceRange(); 3937 } 3938 3939 return false; 3940 } 3941 3942 /// Handle __builtin_assume_aligned. This is declared 3943 /// as (const void*, size_t, ...) and can take one optional constant int arg. 3944 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 3945 unsigned NumArgs = TheCall->getNumArgs(); 3946 3947 if (NumArgs > 3) 3948 return Diag(TheCall->getLocEnd(), 3949 diag::err_typecheck_call_too_many_args_at_most) 3950 << 0 /*function call*/ << 3 << NumArgs 3951 << TheCall->getSourceRange(); 3952 3953 // The alignment must be a constant integer. 3954 Expr *Arg = TheCall->getArg(1); 3955 3956 // We can't check the value of a dependent argument. 3957 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 3958 llvm::APSInt Result; 3959 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 3960 return true; 3961 3962 if (!Result.isPowerOf2()) 3963 return Diag(TheCall->getLocStart(), 3964 diag::err_alignment_not_power_of_two) 3965 << Arg->getSourceRange(); 3966 } 3967 3968 if (NumArgs > 2) { 3969 ExprResult Arg(TheCall->getArg(2)); 3970 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 3971 Context.getSizeType(), false); 3972 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3973 if (Arg.isInvalid()) return true; 3974 TheCall->setArg(2, Arg.get()); 3975 } 3976 3977 return false; 3978 } 3979 3980 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 3981 unsigned BuiltinID = 3982 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 3983 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 3984 3985 unsigned NumArgs = TheCall->getNumArgs(); 3986 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 3987 if (NumArgs < NumRequiredArgs) { 3988 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3989 << 0 /* function call */ << NumRequiredArgs << NumArgs 3990 << TheCall->getSourceRange(); 3991 } 3992 if (NumArgs >= NumRequiredArgs + 0x100) { 3993 return Diag(TheCall->getLocEnd(), 3994 diag::err_typecheck_call_too_many_args_at_most) 3995 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 3996 << TheCall->getSourceRange(); 3997 } 3998 unsigned i = 0; 3999 4000 // For formatting call, check buffer arg. 4001 if (!IsSizeCall) { 4002 ExprResult Arg(TheCall->getArg(i)); 4003 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4004 Context, Context.VoidPtrTy, false); 4005 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4006 if (Arg.isInvalid()) 4007 return true; 4008 TheCall->setArg(i, Arg.get()); 4009 i++; 4010 } 4011 4012 // Check string literal arg. 4013 unsigned FormatIdx = i; 4014 { 4015 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4016 if (Arg.isInvalid()) 4017 return true; 4018 TheCall->setArg(i, Arg.get()); 4019 i++; 4020 } 4021 4022 // Make sure variadic args are scalar. 4023 unsigned FirstDataArg = i; 4024 while (i < NumArgs) { 4025 ExprResult Arg = DefaultVariadicArgumentPromotion( 4026 TheCall->getArg(i), VariadicFunction, nullptr); 4027 if (Arg.isInvalid()) 4028 return true; 4029 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4030 if (ArgSize.getQuantity() >= 0x100) { 4031 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4032 << i << (int)ArgSize.getQuantity() << 0xff 4033 << TheCall->getSourceRange(); 4034 } 4035 TheCall->setArg(i, Arg.get()); 4036 i++; 4037 } 4038 4039 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4040 // call to avoid duplicate diagnostics. 4041 if (!IsSizeCall) { 4042 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4043 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4044 bool Success = CheckFormatArguments( 4045 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4046 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4047 CheckedVarArgs); 4048 if (!Success) 4049 return true; 4050 } 4051 4052 if (IsSizeCall) { 4053 TheCall->setType(Context.getSizeType()); 4054 } else { 4055 TheCall->setType(Context.VoidPtrTy); 4056 } 4057 return false; 4058 } 4059 4060 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4061 /// TheCall is a constant expression. 4062 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4063 llvm::APSInt &Result) { 4064 Expr *Arg = TheCall->getArg(ArgNum); 4065 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4066 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4067 4068 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4069 4070 if (!Arg->isIntegerConstantExpr(Result, Context)) 4071 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 4072 << FDecl->getDeclName() << Arg->getSourceRange(); 4073 4074 return false; 4075 } 4076 4077 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 4078 /// TheCall is a constant expression in the range [Low, High]. 4079 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 4080 int Low, int High) { 4081 llvm::APSInt Result; 4082 4083 // We can't check the value of a dependent argument. 4084 Expr *Arg = TheCall->getArg(ArgNum); 4085 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4086 return false; 4087 4088 // Check constant-ness first. 4089 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4090 return true; 4091 4092 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 4093 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 4094 << Low << High << Arg->getSourceRange(); 4095 4096 return false; 4097 } 4098 4099 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 4100 /// TheCall is a constant expression is a multiple of Num.. 4101 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 4102 unsigned Num) { 4103 llvm::APSInt Result; 4104 4105 // We can't check the value of a dependent argument. 4106 Expr *Arg = TheCall->getArg(ArgNum); 4107 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4108 return false; 4109 4110 // Check constant-ness first. 4111 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4112 return true; 4113 4114 if (Result.getSExtValue() % Num != 0) 4115 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 4116 << Num << Arg->getSourceRange(); 4117 4118 return false; 4119 } 4120 4121 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 4122 /// TheCall is an ARM/AArch64 special register string literal. 4123 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 4124 int ArgNum, unsigned ExpectedFieldNum, 4125 bool AllowName) { 4126 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 4127 BuiltinID == ARM::BI__builtin_arm_wsr64 || 4128 BuiltinID == ARM::BI__builtin_arm_rsr || 4129 BuiltinID == ARM::BI__builtin_arm_rsrp || 4130 BuiltinID == ARM::BI__builtin_arm_wsr || 4131 BuiltinID == ARM::BI__builtin_arm_wsrp; 4132 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 4133 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 4134 BuiltinID == AArch64::BI__builtin_arm_rsr || 4135 BuiltinID == AArch64::BI__builtin_arm_rsrp || 4136 BuiltinID == AArch64::BI__builtin_arm_wsr || 4137 BuiltinID == AArch64::BI__builtin_arm_wsrp; 4138 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 4139 4140 // We can't check the value of a dependent argument. 4141 Expr *Arg = TheCall->getArg(ArgNum); 4142 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4143 return false; 4144 4145 // Check if the argument is a string literal. 4146 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4147 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 4148 << Arg->getSourceRange(); 4149 4150 // Check the type of special register given. 4151 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4152 SmallVector<StringRef, 6> Fields; 4153 Reg.split(Fields, ":"); 4154 4155 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 4156 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4157 << Arg->getSourceRange(); 4158 4159 // If the string is the name of a register then we cannot check that it is 4160 // valid here but if the string is of one the forms described in ACLE then we 4161 // can check that the supplied fields are integers and within the valid 4162 // ranges. 4163 if (Fields.size() > 1) { 4164 bool FiveFields = Fields.size() == 5; 4165 4166 bool ValidString = true; 4167 if (IsARMBuiltin) { 4168 ValidString &= Fields[0].startswith_lower("cp") || 4169 Fields[0].startswith_lower("p"); 4170 if (ValidString) 4171 Fields[0] = 4172 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 4173 4174 ValidString &= Fields[2].startswith_lower("c"); 4175 if (ValidString) 4176 Fields[2] = Fields[2].drop_front(1); 4177 4178 if (FiveFields) { 4179 ValidString &= Fields[3].startswith_lower("c"); 4180 if (ValidString) 4181 Fields[3] = Fields[3].drop_front(1); 4182 } 4183 } 4184 4185 SmallVector<int, 5> Ranges; 4186 if (FiveFields) 4187 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15}); 4188 else 4189 Ranges.append({15, 7, 15}); 4190 4191 for (unsigned i=0; i<Fields.size(); ++i) { 4192 int IntField; 4193 ValidString &= !Fields[i].getAsInteger(10, IntField); 4194 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 4195 } 4196 4197 if (!ValidString) 4198 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 4199 << Arg->getSourceRange(); 4200 4201 } else if (IsAArch64Builtin && Fields.size() == 1) { 4202 // If the register name is one of those that appear in the condition below 4203 // and the special register builtin being used is one of the write builtins, 4204 // then we require that the argument provided for writing to the register 4205 // is an integer constant expression. This is because it will be lowered to 4206 // an MSR (immediate) instruction, so we need to know the immediate at 4207 // compile time. 4208 if (TheCall->getNumArgs() != 2) 4209 return false; 4210 4211 std::string RegLower = Reg.lower(); 4212 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 4213 RegLower != "pan" && RegLower != "uao") 4214 return false; 4215 4216 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 4217 } 4218 4219 return false; 4220 } 4221 4222 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 4223 /// This checks that the target supports __builtin_longjmp and 4224 /// that val is a constant 1. 4225 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 4226 if (!Context.getTargetInfo().hasSjLjLowering()) 4227 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 4228 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4229 4230 Expr *Arg = TheCall->getArg(1); 4231 llvm::APSInt Result; 4232 4233 // TODO: This is less than ideal. Overload this to take a value. 4234 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4235 return true; 4236 4237 if (Result != 1) 4238 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 4239 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 4240 4241 return false; 4242 } 4243 4244 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 4245 /// This checks that the target supports __builtin_setjmp. 4246 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 4247 if (!Context.getTargetInfo().hasSjLjLowering()) 4248 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 4249 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 4250 return false; 4251 } 4252 4253 namespace { 4254 class UncoveredArgHandler { 4255 enum { Unknown = -1, AllCovered = -2 }; 4256 signed FirstUncoveredArg; 4257 SmallVector<const Expr *, 4> DiagnosticExprs; 4258 4259 public: 4260 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { } 4261 4262 bool hasUncoveredArg() const { 4263 return (FirstUncoveredArg >= 0); 4264 } 4265 4266 unsigned getUncoveredArg() const { 4267 assert(hasUncoveredArg() && "no uncovered argument"); 4268 return FirstUncoveredArg; 4269 } 4270 4271 void setAllCovered() { 4272 // A string has been found with all arguments covered, so clear out 4273 // the diagnostics. 4274 DiagnosticExprs.clear(); 4275 FirstUncoveredArg = AllCovered; 4276 } 4277 4278 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 4279 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 4280 4281 // Don't update if a previous string covers all arguments. 4282 if (FirstUncoveredArg == AllCovered) 4283 return; 4284 4285 // UncoveredArgHandler tracks the highest uncovered argument index 4286 // and with it all the strings that match this index. 4287 if (NewFirstUncoveredArg == FirstUncoveredArg) 4288 DiagnosticExprs.push_back(StrExpr); 4289 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 4290 DiagnosticExprs.clear(); 4291 DiagnosticExprs.push_back(StrExpr); 4292 FirstUncoveredArg = NewFirstUncoveredArg; 4293 } 4294 } 4295 4296 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 4297 }; 4298 4299 enum StringLiteralCheckType { 4300 SLCT_NotALiteral, 4301 SLCT_UncheckedLiteral, 4302 SLCT_CheckedLiteral 4303 }; 4304 } // end anonymous namespace 4305 4306 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 4307 BinaryOperatorKind BinOpKind, 4308 bool AddendIsRight) { 4309 unsigned BitWidth = Offset.getBitWidth(); 4310 unsigned AddendBitWidth = Addend.getBitWidth(); 4311 // There might be negative interim results. 4312 if (Addend.isUnsigned()) { 4313 Addend = Addend.zext(++AddendBitWidth); 4314 Addend.setIsSigned(true); 4315 } 4316 // Adjust the bit width of the APSInts. 4317 if (AddendBitWidth > BitWidth) { 4318 Offset = Offset.sext(AddendBitWidth); 4319 BitWidth = AddendBitWidth; 4320 } else if (BitWidth > AddendBitWidth) { 4321 Addend = Addend.sext(BitWidth); 4322 } 4323 4324 bool Ov = false; 4325 llvm::APSInt ResOffset = Offset; 4326 if (BinOpKind == BO_Add) 4327 ResOffset = Offset.sadd_ov(Addend, Ov); 4328 else { 4329 assert(AddendIsRight && BinOpKind == BO_Sub && 4330 "operator must be add or sub with addend on the right"); 4331 ResOffset = Offset.ssub_ov(Addend, Ov); 4332 } 4333 4334 // We add an offset to a pointer here so we should support an offset as big as 4335 // possible. 4336 if (Ov) { 4337 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big"); 4338 Offset = Offset.sext(2 * BitWidth); 4339 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 4340 return; 4341 } 4342 4343 Offset = ResOffset; 4344 } 4345 4346 namespace { 4347 // This is a wrapper class around StringLiteral to support offsetted string 4348 // literals as format strings. It takes the offset into account when returning 4349 // the string and its length or the source locations to display notes correctly. 4350 class FormatStringLiteral { 4351 const StringLiteral *FExpr; 4352 int64_t Offset; 4353 4354 public: 4355 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 4356 : FExpr(fexpr), Offset(Offset) {} 4357 4358 StringRef getString() const { 4359 return FExpr->getString().drop_front(Offset); 4360 } 4361 4362 unsigned getByteLength() const { 4363 return FExpr->getByteLength() - getCharByteWidth() * Offset; 4364 } 4365 unsigned getLength() const { return FExpr->getLength() - Offset; } 4366 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 4367 4368 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 4369 4370 QualType getType() const { return FExpr->getType(); } 4371 4372 bool isAscii() const { return FExpr->isAscii(); } 4373 bool isWide() const { return FExpr->isWide(); } 4374 bool isUTF8() const { return FExpr->isUTF8(); } 4375 bool isUTF16() const { return FExpr->isUTF16(); } 4376 bool isUTF32() const { return FExpr->isUTF32(); } 4377 bool isPascal() const { return FExpr->isPascal(); } 4378 4379 SourceLocation getLocationOfByte( 4380 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 4381 const TargetInfo &Target, unsigned *StartToken = nullptr, 4382 unsigned *StartTokenByteOffset = nullptr) const { 4383 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 4384 StartToken, StartTokenByteOffset); 4385 } 4386 4387 SourceLocation getLocStart() const LLVM_READONLY { 4388 return FExpr->getLocStart().getLocWithOffset(Offset); 4389 } 4390 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 4391 }; 4392 } // end anonymous namespace 4393 4394 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 4395 const Expr *OrigFormatExpr, 4396 ArrayRef<const Expr *> Args, 4397 bool HasVAListArg, unsigned format_idx, 4398 unsigned firstDataArg, 4399 Sema::FormatStringType Type, 4400 bool inFunctionCall, 4401 Sema::VariadicCallType CallType, 4402 llvm::SmallBitVector &CheckedVarArgs, 4403 UncoveredArgHandler &UncoveredArg); 4404 4405 // Determine if an expression is a string literal or constant string. 4406 // If this function returns false on the arguments to a function expecting a 4407 // format string, we will usually need to emit a warning. 4408 // True string literals are then checked by CheckFormatString. 4409 static StringLiteralCheckType 4410 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 4411 bool HasVAListArg, unsigned format_idx, 4412 unsigned firstDataArg, Sema::FormatStringType Type, 4413 Sema::VariadicCallType CallType, bool InFunctionCall, 4414 llvm::SmallBitVector &CheckedVarArgs, 4415 UncoveredArgHandler &UncoveredArg, 4416 llvm::APSInt Offset) { 4417 tryAgain: 4418 assert(Offset.isSigned() && "invalid offset"); 4419 4420 if (E->isTypeDependent() || E->isValueDependent()) 4421 return SLCT_NotALiteral; 4422 4423 E = E->IgnoreParenCasts(); 4424 4425 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 4426 // Technically -Wformat-nonliteral does not warn about this case. 4427 // The behavior of printf and friends in this case is implementation 4428 // dependent. Ideally if the format string cannot be null then 4429 // it should have a 'nonnull' attribute in the function prototype. 4430 return SLCT_UncheckedLiteral; 4431 4432 switch (E->getStmtClass()) { 4433 case Stmt::BinaryConditionalOperatorClass: 4434 case Stmt::ConditionalOperatorClass: { 4435 // The expression is a literal if both sub-expressions were, and it was 4436 // completely checked only if both sub-expressions were checked. 4437 const AbstractConditionalOperator *C = 4438 cast<AbstractConditionalOperator>(E); 4439 4440 // Determine whether it is necessary to check both sub-expressions, for 4441 // example, because the condition expression is a constant that can be 4442 // evaluated at compile time. 4443 bool CheckLeft = true, CheckRight = true; 4444 4445 bool Cond; 4446 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 4447 if (Cond) 4448 CheckRight = false; 4449 else 4450 CheckLeft = false; 4451 } 4452 4453 // We need to maintain the offsets for the right and the left hand side 4454 // separately to check if every possible indexed expression is a valid 4455 // string literal. They might have different offsets for different string 4456 // literals in the end. 4457 StringLiteralCheckType Left; 4458 if (!CheckLeft) 4459 Left = SLCT_UncheckedLiteral; 4460 else { 4461 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 4462 HasVAListArg, format_idx, firstDataArg, 4463 Type, CallType, InFunctionCall, 4464 CheckedVarArgs, UncoveredArg, Offset); 4465 if (Left == SLCT_NotALiteral || !CheckRight) { 4466 return Left; 4467 } 4468 } 4469 4470 StringLiteralCheckType Right = 4471 checkFormatStringExpr(S, C->getFalseExpr(), Args, 4472 HasVAListArg, format_idx, firstDataArg, 4473 Type, CallType, InFunctionCall, CheckedVarArgs, 4474 UncoveredArg, Offset); 4475 4476 return (CheckLeft && Left < Right) ? Left : Right; 4477 } 4478 4479 case Stmt::ImplicitCastExprClass: { 4480 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4481 goto tryAgain; 4482 } 4483 4484 case Stmt::OpaqueValueExprClass: 4485 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 4486 E = src; 4487 goto tryAgain; 4488 } 4489 return SLCT_NotALiteral; 4490 4491 case Stmt::PredefinedExprClass: 4492 // While __func__, etc., are technically not string literals, they 4493 // cannot contain format specifiers and thus are not a security 4494 // liability. 4495 return SLCT_UncheckedLiteral; 4496 4497 case Stmt::DeclRefExprClass: { 4498 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 4499 4500 // As an exception, do not flag errors for variables binding to 4501 // const string literals. 4502 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 4503 bool isConstant = false; 4504 QualType T = DR->getType(); 4505 4506 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 4507 isConstant = AT->getElementType().isConstant(S.Context); 4508 } else if (const PointerType *PT = T->getAs<PointerType>()) { 4509 isConstant = T.isConstant(S.Context) && 4510 PT->getPointeeType().isConstant(S.Context); 4511 } else if (T->isObjCObjectPointerType()) { 4512 // In ObjC, there is usually no "const ObjectPointer" type, 4513 // so don't check if the pointee type is constant. 4514 isConstant = T.isConstant(S.Context); 4515 } 4516 4517 if (isConstant) { 4518 if (const Expr *Init = VD->getAnyInitializer()) { 4519 // Look through initializers like const char c[] = { "foo" } 4520 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4521 if (InitList->isStringLiteralInit()) 4522 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 4523 } 4524 return checkFormatStringExpr(S, Init, Args, 4525 HasVAListArg, format_idx, 4526 firstDataArg, Type, CallType, 4527 /*InFunctionCall*/ false, CheckedVarArgs, 4528 UncoveredArg, Offset); 4529 } 4530 } 4531 4532 // For vprintf* functions (i.e., HasVAListArg==true), we add a 4533 // special check to see if the format string is a function parameter 4534 // of the function calling the printf function. If the function 4535 // has an attribute indicating it is a printf-like function, then we 4536 // should suppress warnings concerning non-literals being used in a call 4537 // to a vprintf function. For example: 4538 // 4539 // void 4540 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 4541 // va_list ap; 4542 // va_start(ap, fmt); 4543 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 4544 // ... 4545 // } 4546 if (HasVAListArg) { 4547 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 4548 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 4549 int PVIndex = PV->getFunctionScopeIndex() + 1; 4550 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 4551 // adjust for implicit parameter 4552 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4553 if (MD->isInstance()) 4554 ++PVIndex; 4555 // We also check if the formats are compatible. 4556 // We can't pass a 'scanf' string to a 'printf' function. 4557 if (PVIndex == PVFormat->getFormatIdx() && 4558 Type == S.GetFormatStringType(PVFormat)) 4559 return SLCT_UncheckedLiteral; 4560 } 4561 } 4562 } 4563 } 4564 } 4565 4566 return SLCT_NotALiteral; 4567 } 4568 4569 case Stmt::CallExprClass: 4570 case Stmt::CXXMemberCallExprClass: { 4571 const CallExpr *CE = cast<CallExpr>(E); 4572 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 4573 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 4574 unsigned ArgIndex = FA->getFormatIdx(); 4575 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 4576 if (MD->isInstance()) 4577 --ArgIndex; 4578 const Expr *Arg = CE->getArg(ArgIndex - 1); 4579 4580 return checkFormatStringExpr(S, Arg, Args, 4581 HasVAListArg, format_idx, firstDataArg, 4582 Type, CallType, InFunctionCall, 4583 CheckedVarArgs, UncoveredArg, Offset); 4584 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 4585 unsigned BuiltinID = FD->getBuiltinID(); 4586 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 4587 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 4588 const Expr *Arg = CE->getArg(0); 4589 return checkFormatStringExpr(S, Arg, Args, 4590 HasVAListArg, format_idx, 4591 firstDataArg, Type, CallType, 4592 InFunctionCall, CheckedVarArgs, 4593 UncoveredArg, Offset); 4594 } 4595 } 4596 } 4597 4598 return SLCT_NotALiteral; 4599 } 4600 case Stmt::ObjCMessageExprClass: { 4601 const auto *ME = cast<ObjCMessageExpr>(E); 4602 if (const auto *ND = ME->getMethodDecl()) { 4603 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 4604 unsigned ArgIndex = FA->getFormatIdx(); 4605 const Expr *Arg = ME->getArg(ArgIndex - 1); 4606 return checkFormatStringExpr( 4607 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 4608 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 4609 } 4610 } 4611 4612 return SLCT_NotALiteral; 4613 } 4614 case Stmt::ObjCStringLiteralClass: 4615 case Stmt::StringLiteralClass: { 4616 const StringLiteral *StrE = nullptr; 4617 4618 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 4619 StrE = ObjCFExpr->getString(); 4620 else 4621 StrE = cast<StringLiteral>(E); 4622 4623 if (StrE) { 4624 if (Offset.isNegative() || Offset > StrE->getLength()) { 4625 // TODO: It would be better to have an explicit warning for out of 4626 // bounds literals. 4627 return SLCT_NotALiteral; 4628 } 4629 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 4630 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 4631 firstDataArg, Type, InFunctionCall, CallType, 4632 CheckedVarArgs, UncoveredArg); 4633 return SLCT_CheckedLiteral; 4634 } 4635 4636 return SLCT_NotALiteral; 4637 } 4638 case Stmt::BinaryOperatorClass: { 4639 llvm::APSInt LResult; 4640 llvm::APSInt RResult; 4641 4642 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 4643 4644 // A string literal + an int offset is still a string literal. 4645 if (BinOp->isAdditiveOp()) { 4646 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 4647 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 4648 4649 if (LIsInt != RIsInt) { 4650 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 4651 4652 if (LIsInt) { 4653 if (BinOpKind == BO_Add) { 4654 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 4655 E = BinOp->getRHS(); 4656 goto tryAgain; 4657 } 4658 } else { 4659 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 4660 E = BinOp->getLHS(); 4661 goto tryAgain; 4662 } 4663 } 4664 } 4665 4666 return SLCT_NotALiteral; 4667 } 4668 case Stmt::UnaryOperatorClass: { 4669 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 4670 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 4671 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) { 4672 llvm::APSInt IndexResult; 4673 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 4674 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 4675 E = ASE->getBase(); 4676 goto tryAgain; 4677 } 4678 } 4679 4680 return SLCT_NotALiteral; 4681 } 4682 4683 default: 4684 return SLCT_NotALiteral; 4685 } 4686 } 4687 4688 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 4689 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 4690 .Case("scanf", FST_Scanf) 4691 .Cases("printf", "printf0", FST_Printf) 4692 .Cases("NSString", "CFString", FST_NSString) 4693 .Case("strftime", FST_Strftime) 4694 .Case("strfmon", FST_Strfmon) 4695 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 4696 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 4697 .Case("os_trace", FST_OSLog) 4698 .Case("os_log", FST_OSLog) 4699 .Default(FST_Unknown); 4700 } 4701 4702 /// CheckFormatArguments - Check calls to printf and scanf (and similar 4703 /// functions) for correct use of format strings. 4704 /// Returns true if a format string has been fully checked. 4705 bool Sema::CheckFormatArguments(const FormatAttr *Format, 4706 ArrayRef<const Expr *> Args, 4707 bool IsCXXMember, 4708 VariadicCallType CallType, 4709 SourceLocation Loc, SourceRange Range, 4710 llvm::SmallBitVector &CheckedVarArgs) { 4711 FormatStringInfo FSI; 4712 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 4713 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 4714 FSI.FirstDataArg, GetFormatStringType(Format), 4715 CallType, Loc, Range, CheckedVarArgs); 4716 return false; 4717 } 4718 4719 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 4720 bool HasVAListArg, unsigned format_idx, 4721 unsigned firstDataArg, FormatStringType Type, 4722 VariadicCallType CallType, 4723 SourceLocation Loc, SourceRange Range, 4724 llvm::SmallBitVector &CheckedVarArgs) { 4725 // CHECK: printf/scanf-like function is called with no format string. 4726 if (format_idx >= Args.size()) { 4727 Diag(Loc, diag::warn_missing_format_string) << Range; 4728 return false; 4729 } 4730 4731 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 4732 4733 // CHECK: format string is not a string literal. 4734 // 4735 // Dynamically generated format strings are difficult to 4736 // automatically vet at compile time. Requiring that format strings 4737 // are string literals: (1) permits the checking of format strings by 4738 // the compiler and thereby (2) can practically remove the source of 4739 // many format string exploits. 4740 4741 // Format string can be either ObjC string (e.g. @"%d") or 4742 // C string (e.g. "%d") 4743 // ObjC string uses the same format specifiers as C string, so we can use 4744 // the same format string checking logic for both ObjC and C strings. 4745 UncoveredArgHandler UncoveredArg; 4746 StringLiteralCheckType CT = 4747 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 4748 format_idx, firstDataArg, Type, CallType, 4749 /*IsFunctionCall*/ true, CheckedVarArgs, 4750 UncoveredArg, 4751 /*no string offset*/ llvm::APSInt(64, false) = 0); 4752 4753 // Generate a diagnostic where an uncovered argument is detected. 4754 if (UncoveredArg.hasUncoveredArg()) { 4755 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 4756 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 4757 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 4758 } 4759 4760 if (CT != SLCT_NotALiteral) 4761 // Literal format string found, check done! 4762 return CT == SLCT_CheckedLiteral; 4763 4764 // Strftime is particular as it always uses a single 'time' argument, 4765 // so it is safe to pass a non-literal string. 4766 if (Type == FST_Strftime) 4767 return false; 4768 4769 // Do not emit diag when the string param is a macro expansion and the 4770 // format is either NSString or CFString. This is a hack to prevent 4771 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 4772 // which are usually used in place of NS and CF string literals. 4773 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 4774 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 4775 return false; 4776 4777 // If there are no arguments specified, warn with -Wformat-security, otherwise 4778 // warn only with -Wformat-nonliteral. 4779 if (Args.size() == firstDataArg) { 4780 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 4781 << OrigFormatExpr->getSourceRange(); 4782 switch (Type) { 4783 default: 4784 break; 4785 case FST_Kprintf: 4786 case FST_FreeBSDKPrintf: 4787 case FST_Printf: 4788 Diag(FormatLoc, diag::note_format_security_fixit) 4789 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 4790 break; 4791 case FST_NSString: 4792 Diag(FormatLoc, diag::note_format_security_fixit) 4793 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 4794 break; 4795 } 4796 } else { 4797 Diag(FormatLoc, diag::warn_format_nonliteral) 4798 << OrigFormatExpr->getSourceRange(); 4799 } 4800 return false; 4801 } 4802 4803 namespace { 4804 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 4805 protected: 4806 Sema &S; 4807 const FormatStringLiteral *FExpr; 4808 const Expr *OrigFormatExpr; 4809 const Sema::FormatStringType FSType; 4810 const unsigned FirstDataArg; 4811 const unsigned NumDataArgs; 4812 const char *Beg; // Start of format string. 4813 const bool HasVAListArg; 4814 ArrayRef<const Expr *> Args; 4815 unsigned FormatIdx; 4816 llvm::SmallBitVector CoveredArgs; 4817 bool usesPositionalArgs; 4818 bool atFirstArg; 4819 bool inFunctionCall; 4820 Sema::VariadicCallType CallType; 4821 llvm::SmallBitVector &CheckedVarArgs; 4822 UncoveredArgHandler &UncoveredArg; 4823 4824 public: 4825 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 4826 const Expr *origFormatExpr, 4827 const Sema::FormatStringType type, unsigned firstDataArg, 4828 unsigned numDataArgs, const char *beg, bool hasVAListArg, 4829 ArrayRef<const Expr *> Args, unsigned formatIdx, 4830 bool inFunctionCall, Sema::VariadicCallType callType, 4831 llvm::SmallBitVector &CheckedVarArgs, 4832 UncoveredArgHandler &UncoveredArg) 4833 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 4834 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 4835 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 4836 usesPositionalArgs(false), atFirstArg(true), 4837 inFunctionCall(inFunctionCall), CallType(callType), 4838 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 4839 CoveredArgs.resize(numDataArgs); 4840 CoveredArgs.reset(); 4841 } 4842 4843 void DoneProcessing(); 4844 4845 void HandleIncompleteSpecifier(const char *startSpecifier, 4846 unsigned specifierLen) override; 4847 4848 void HandleInvalidLengthModifier( 4849 const analyze_format_string::FormatSpecifier &FS, 4850 const analyze_format_string::ConversionSpecifier &CS, 4851 const char *startSpecifier, unsigned specifierLen, 4852 unsigned DiagID); 4853 4854 void HandleNonStandardLengthModifier( 4855 const analyze_format_string::FormatSpecifier &FS, 4856 const char *startSpecifier, unsigned specifierLen); 4857 4858 void HandleNonStandardConversionSpecifier( 4859 const analyze_format_string::ConversionSpecifier &CS, 4860 const char *startSpecifier, unsigned specifierLen); 4861 4862 void HandlePosition(const char *startPos, unsigned posLen) override; 4863 4864 void HandleInvalidPosition(const char *startSpecifier, 4865 unsigned specifierLen, 4866 analyze_format_string::PositionContext p) override; 4867 4868 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 4869 4870 void HandleNullChar(const char *nullCharacter) override; 4871 4872 template <typename Range> 4873 static void 4874 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 4875 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 4876 bool IsStringLocation, Range StringRange, 4877 ArrayRef<FixItHint> Fixit = None); 4878 4879 protected: 4880 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 4881 const char *startSpec, 4882 unsigned specifierLen, 4883 const char *csStart, unsigned csLen); 4884 4885 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 4886 const char *startSpec, 4887 unsigned specifierLen); 4888 4889 SourceRange getFormatStringRange(); 4890 CharSourceRange getSpecifierRange(const char *startSpecifier, 4891 unsigned specifierLen); 4892 SourceLocation getLocationOfByte(const char *x); 4893 4894 const Expr *getDataArg(unsigned i) const; 4895 4896 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 4897 const analyze_format_string::ConversionSpecifier &CS, 4898 const char *startSpecifier, unsigned specifierLen, 4899 unsigned argIndex); 4900 4901 template <typename Range> 4902 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 4903 bool IsStringLocation, Range StringRange, 4904 ArrayRef<FixItHint> Fixit = None); 4905 }; 4906 } // end anonymous namespace 4907 4908 SourceRange CheckFormatHandler::getFormatStringRange() { 4909 return OrigFormatExpr->getSourceRange(); 4910 } 4911 4912 CharSourceRange CheckFormatHandler:: 4913 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 4914 SourceLocation Start = getLocationOfByte(startSpecifier); 4915 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 4916 4917 // Advance the end SourceLocation by one due to half-open ranges. 4918 End = End.getLocWithOffset(1); 4919 4920 return CharSourceRange::getCharRange(Start, End); 4921 } 4922 4923 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 4924 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 4925 S.getLangOpts(), S.Context.getTargetInfo()); 4926 } 4927 4928 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 4929 unsigned specifierLen){ 4930 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 4931 getLocationOfByte(startSpecifier), 4932 /*IsStringLocation*/true, 4933 getSpecifierRange(startSpecifier, specifierLen)); 4934 } 4935 4936 void CheckFormatHandler::HandleInvalidLengthModifier( 4937 const analyze_format_string::FormatSpecifier &FS, 4938 const analyze_format_string::ConversionSpecifier &CS, 4939 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 4940 using namespace analyze_format_string; 4941 4942 const LengthModifier &LM = FS.getLengthModifier(); 4943 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 4944 4945 // See if we know how to fix this length modifier. 4946 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 4947 if (FixedLM) { 4948 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 4949 getLocationOfByte(LM.getStart()), 4950 /*IsStringLocation*/true, 4951 getSpecifierRange(startSpecifier, specifierLen)); 4952 4953 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 4954 << FixedLM->toString() 4955 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 4956 4957 } else { 4958 FixItHint Hint; 4959 if (DiagID == diag::warn_format_nonsensical_length) 4960 Hint = FixItHint::CreateRemoval(LMRange); 4961 4962 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 4963 getLocationOfByte(LM.getStart()), 4964 /*IsStringLocation*/true, 4965 getSpecifierRange(startSpecifier, specifierLen), 4966 Hint); 4967 } 4968 } 4969 4970 void CheckFormatHandler::HandleNonStandardLengthModifier( 4971 const analyze_format_string::FormatSpecifier &FS, 4972 const char *startSpecifier, unsigned specifierLen) { 4973 using namespace analyze_format_string; 4974 4975 const LengthModifier &LM = FS.getLengthModifier(); 4976 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 4977 4978 // See if we know how to fix this length modifier. 4979 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 4980 if (FixedLM) { 4981 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4982 << LM.toString() << 0, 4983 getLocationOfByte(LM.getStart()), 4984 /*IsStringLocation*/true, 4985 getSpecifierRange(startSpecifier, specifierLen)); 4986 4987 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 4988 << FixedLM->toString() 4989 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 4990 4991 } else { 4992 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4993 << LM.toString() << 0, 4994 getLocationOfByte(LM.getStart()), 4995 /*IsStringLocation*/true, 4996 getSpecifierRange(startSpecifier, specifierLen)); 4997 } 4998 } 4999 5000 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5001 const analyze_format_string::ConversionSpecifier &CS, 5002 const char *startSpecifier, unsigned specifierLen) { 5003 using namespace analyze_format_string; 5004 5005 // See if we know how to fix this conversion specifier. 5006 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5007 if (FixedCS) { 5008 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5009 << CS.toString() << /*conversion specifier*/1, 5010 getLocationOfByte(CS.getStart()), 5011 /*IsStringLocation*/true, 5012 getSpecifierRange(startSpecifier, specifierLen)); 5013 5014 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5015 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5016 << FixedCS->toString() 5017 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5018 } else { 5019 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5020 << CS.toString() << /*conversion specifier*/1, 5021 getLocationOfByte(CS.getStart()), 5022 /*IsStringLocation*/true, 5023 getSpecifierRange(startSpecifier, specifierLen)); 5024 } 5025 } 5026 5027 void CheckFormatHandler::HandlePosition(const char *startPos, 5028 unsigned posLen) { 5029 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5030 getLocationOfByte(startPos), 5031 /*IsStringLocation*/true, 5032 getSpecifierRange(startPos, posLen)); 5033 } 5034 5035 void 5036 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5037 analyze_format_string::PositionContext p) { 5038 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5039 << (unsigned) p, 5040 getLocationOfByte(startPos), /*IsStringLocation*/true, 5041 getSpecifierRange(startPos, posLen)); 5042 } 5043 5044 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5045 unsigned posLen) { 5046 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5047 getLocationOfByte(startPos), 5048 /*IsStringLocation*/true, 5049 getSpecifierRange(startPos, posLen)); 5050 } 5051 5052 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5053 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5054 // The presence of a null character is likely an error. 5055 EmitFormatDiagnostic( 5056 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5057 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5058 getFormatStringRange()); 5059 } 5060 } 5061 5062 // Note that this may return NULL if there was an error parsing or building 5063 // one of the argument expressions. 5064 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5065 return Args[FirstDataArg + i]; 5066 } 5067 5068 void CheckFormatHandler::DoneProcessing() { 5069 // Does the number of data arguments exceed the number of 5070 // format conversions in the format string? 5071 if (!HasVAListArg) { 5072 // Find any arguments that weren't covered. 5073 CoveredArgs.flip(); 5074 signed notCoveredArg = CoveredArgs.find_first(); 5075 if (notCoveredArg >= 0) { 5076 assert((unsigned)notCoveredArg < NumDataArgs); 5077 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 5078 } else { 5079 UncoveredArg.setAllCovered(); 5080 } 5081 } 5082 } 5083 5084 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 5085 const Expr *ArgExpr) { 5086 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 5087 "Invalid state"); 5088 5089 if (!ArgExpr) 5090 return; 5091 5092 SourceLocation Loc = ArgExpr->getLocStart(); 5093 5094 if (S.getSourceManager().isInSystemMacro(Loc)) 5095 return; 5096 5097 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 5098 for (auto E : DiagnosticExprs) 5099 PDiag << E->getSourceRange(); 5100 5101 CheckFormatHandler::EmitFormatDiagnostic( 5102 S, IsFunctionCall, DiagnosticExprs[0], 5103 PDiag, Loc, /*IsStringLocation*/false, 5104 DiagnosticExprs[0]->getSourceRange()); 5105 } 5106 5107 bool 5108 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 5109 SourceLocation Loc, 5110 const char *startSpec, 5111 unsigned specifierLen, 5112 const char *csStart, 5113 unsigned csLen) { 5114 bool keepGoing = true; 5115 if (argIndex < NumDataArgs) { 5116 // Consider the argument coverered, even though the specifier doesn't 5117 // make sense. 5118 CoveredArgs.set(argIndex); 5119 } 5120 else { 5121 // If argIndex exceeds the number of data arguments we 5122 // don't issue a warning because that is just a cascade of warnings (and 5123 // they may have intended '%%' anyway). We don't want to continue processing 5124 // the format string after this point, however, as we will like just get 5125 // gibberish when trying to match arguments. 5126 keepGoing = false; 5127 } 5128 5129 StringRef Specifier(csStart, csLen); 5130 5131 // If the specifier in non-printable, it could be the first byte of a UTF-8 5132 // sequence. In that case, print the UTF-8 code point. If not, print the byte 5133 // hex value. 5134 std::string CodePointStr; 5135 if (!llvm::sys::locale::isPrint(*csStart)) { 5136 llvm::UTF32 CodePoint; 5137 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 5138 const llvm::UTF8 *E = 5139 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 5140 llvm::ConversionResult Result = 5141 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 5142 5143 if (Result != llvm::conversionOK) { 5144 unsigned char FirstChar = *csStart; 5145 CodePoint = (llvm::UTF32)FirstChar; 5146 } 5147 5148 llvm::raw_string_ostream OS(CodePointStr); 5149 if (CodePoint < 256) 5150 OS << "\\x" << llvm::format("%02x", CodePoint); 5151 else if (CodePoint <= 0xFFFF) 5152 OS << "\\u" << llvm::format("%04x", CodePoint); 5153 else 5154 OS << "\\U" << llvm::format("%08x", CodePoint); 5155 OS.flush(); 5156 Specifier = CodePointStr; 5157 } 5158 5159 EmitFormatDiagnostic( 5160 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 5161 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 5162 5163 return keepGoing; 5164 } 5165 5166 void 5167 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 5168 const char *startSpec, 5169 unsigned specifierLen) { 5170 EmitFormatDiagnostic( 5171 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 5172 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 5173 } 5174 5175 bool 5176 CheckFormatHandler::CheckNumArgs( 5177 const analyze_format_string::FormatSpecifier &FS, 5178 const analyze_format_string::ConversionSpecifier &CS, 5179 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 5180 5181 if (argIndex >= NumDataArgs) { 5182 PartialDiagnostic PDiag = FS.usesPositionalArg() 5183 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 5184 << (argIndex+1) << NumDataArgs) 5185 : S.PDiag(diag::warn_printf_insufficient_data_args); 5186 EmitFormatDiagnostic( 5187 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 5188 getSpecifierRange(startSpecifier, specifierLen)); 5189 5190 // Since more arguments than conversion tokens are given, by extension 5191 // all arguments are covered, so mark this as so. 5192 UncoveredArg.setAllCovered(); 5193 return false; 5194 } 5195 return true; 5196 } 5197 5198 template<typename Range> 5199 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 5200 SourceLocation Loc, 5201 bool IsStringLocation, 5202 Range StringRange, 5203 ArrayRef<FixItHint> FixIt) { 5204 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 5205 Loc, IsStringLocation, StringRange, FixIt); 5206 } 5207 5208 /// \brief If the format string is not within the funcion call, emit a note 5209 /// so that the function call and string are in diagnostic messages. 5210 /// 5211 /// \param InFunctionCall if true, the format string is within the function 5212 /// call and only one diagnostic message will be produced. Otherwise, an 5213 /// extra note will be emitted pointing to location of the format string. 5214 /// 5215 /// \param ArgumentExpr the expression that is passed as the format string 5216 /// argument in the function call. Used for getting locations when two 5217 /// diagnostics are emitted. 5218 /// 5219 /// \param PDiag the callee should already have provided any strings for the 5220 /// diagnostic message. This function only adds locations and fixits 5221 /// to diagnostics. 5222 /// 5223 /// \param Loc primary location for diagnostic. If two diagnostics are 5224 /// required, one will be at Loc and a new SourceLocation will be created for 5225 /// the other one. 5226 /// 5227 /// \param IsStringLocation if true, Loc points to the format string should be 5228 /// used for the note. Otherwise, Loc points to the argument list and will 5229 /// be used with PDiag. 5230 /// 5231 /// \param StringRange some or all of the string to highlight. This is 5232 /// templated so it can accept either a CharSourceRange or a SourceRange. 5233 /// 5234 /// \param FixIt optional fix it hint for the format string. 5235 template <typename Range> 5236 void CheckFormatHandler::EmitFormatDiagnostic( 5237 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 5238 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 5239 Range StringRange, ArrayRef<FixItHint> FixIt) { 5240 if (InFunctionCall) { 5241 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 5242 D << StringRange; 5243 D << FixIt; 5244 } else { 5245 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 5246 << ArgumentExpr->getSourceRange(); 5247 5248 const Sema::SemaDiagnosticBuilder &Note = 5249 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 5250 diag::note_format_string_defined); 5251 5252 Note << StringRange; 5253 Note << FixIt; 5254 } 5255 } 5256 5257 //===--- CHECK: Printf format string checking ------------------------------===// 5258 5259 namespace { 5260 class CheckPrintfHandler : public CheckFormatHandler { 5261 public: 5262 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 5263 const Expr *origFormatExpr, 5264 const Sema::FormatStringType type, unsigned firstDataArg, 5265 unsigned numDataArgs, bool isObjC, const char *beg, 5266 bool hasVAListArg, ArrayRef<const Expr *> Args, 5267 unsigned formatIdx, bool inFunctionCall, 5268 Sema::VariadicCallType CallType, 5269 llvm::SmallBitVector &CheckedVarArgs, 5270 UncoveredArgHandler &UncoveredArg) 5271 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 5272 numDataArgs, beg, hasVAListArg, Args, formatIdx, 5273 inFunctionCall, CallType, CheckedVarArgs, 5274 UncoveredArg) {} 5275 5276 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 5277 5278 /// Returns true if '%@' specifiers are allowed in the format string. 5279 bool allowsObjCArg() const { 5280 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 5281 FSType == Sema::FST_OSTrace; 5282 } 5283 5284 bool HandleInvalidPrintfConversionSpecifier( 5285 const analyze_printf::PrintfSpecifier &FS, 5286 const char *startSpecifier, 5287 unsigned specifierLen) override; 5288 5289 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 5290 const char *startSpecifier, 5291 unsigned specifierLen) override; 5292 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5293 const char *StartSpecifier, 5294 unsigned SpecifierLen, 5295 const Expr *E); 5296 5297 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 5298 const char *startSpecifier, unsigned specifierLen); 5299 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 5300 const analyze_printf::OptionalAmount &Amt, 5301 unsigned type, 5302 const char *startSpecifier, unsigned specifierLen); 5303 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5304 const analyze_printf::OptionalFlag &flag, 5305 const char *startSpecifier, unsigned specifierLen); 5306 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 5307 const analyze_printf::OptionalFlag &ignoredFlag, 5308 const analyze_printf::OptionalFlag &flag, 5309 const char *startSpecifier, unsigned specifierLen); 5310 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 5311 const Expr *E); 5312 5313 void HandleEmptyObjCModifierFlag(const char *startFlag, 5314 unsigned flagLen) override; 5315 5316 void HandleInvalidObjCModifierFlag(const char *startFlag, 5317 unsigned flagLen) override; 5318 5319 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 5320 const char *flagsEnd, 5321 const char *conversionPosition) 5322 override; 5323 }; 5324 } // end anonymous namespace 5325 5326 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 5327 const analyze_printf::PrintfSpecifier &FS, 5328 const char *startSpecifier, 5329 unsigned specifierLen) { 5330 const analyze_printf::PrintfConversionSpecifier &CS = 5331 FS.getConversionSpecifier(); 5332 5333 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5334 getLocationOfByte(CS.getStart()), 5335 startSpecifier, specifierLen, 5336 CS.getStart(), CS.getLength()); 5337 } 5338 5339 bool CheckPrintfHandler::HandleAmount( 5340 const analyze_format_string::OptionalAmount &Amt, 5341 unsigned k, const char *startSpecifier, 5342 unsigned specifierLen) { 5343 if (Amt.hasDataArgument()) { 5344 if (!HasVAListArg) { 5345 unsigned argIndex = Amt.getArgIndex(); 5346 if (argIndex >= NumDataArgs) { 5347 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 5348 << k, 5349 getLocationOfByte(Amt.getStart()), 5350 /*IsStringLocation*/true, 5351 getSpecifierRange(startSpecifier, specifierLen)); 5352 // Don't do any more checking. We will just emit 5353 // spurious errors. 5354 return false; 5355 } 5356 5357 // Type check the data argument. It should be an 'int'. 5358 // Although not in conformance with C99, we also allow the argument to be 5359 // an 'unsigned int' as that is a reasonably safe case. GCC also 5360 // doesn't emit a warning for that case. 5361 CoveredArgs.set(argIndex); 5362 const Expr *Arg = getDataArg(argIndex); 5363 if (!Arg) 5364 return false; 5365 5366 QualType T = Arg->getType(); 5367 5368 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 5369 assert(AT.isValid()); 5370 5371 if (!AT.matchesType(S.Context, T)) { 5372 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 5373 << k << AT.getRepresentativeTypeName(S.Context) 5374 << T << Arg->getSourceRange(), 5375 getLocationOfByte(Amt.getStart()), 5376 /*IsStringLocation*/true, 5377 getSpecifierRange(startSpecifier, specifierLen)); 5378 // Don't do any more checking. We will just emit 5379 // spurious errors. 5380 return false; 5381 } 5382 } 5383 } 5384 return true; 5385 } 5386 5387 void CheckPrintfHandler::HandleInvalidAmount( 5388 const analyze_printf::PrintfSpecifier &FS, 5389 const analyze_printf::OptionalAmount &Amt, 5390 unsigned type, 5391 const char *startSpecifier, 5392 unsigned specifierLen) { 5393 const analyze_printf::PrintfConversionSpecifier &CS = 5394 FS.getConversionSpecifier(); 5395 5396 FixItHint fixit = 5397 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 5398 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 5399 Amt.getConstantLength())) 5400 : FixItHint(); 5401 5402 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 5403 << type << CS.toString(), 5404 getLocationOfByte(Amt.getStart()), 5405 /*IsStringLocation*/true, 5406 getSpecifierRange(startSpecifier, specifierLen), 5407 fixit); 5408 } 5409 5410 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 5411 const analyze_printf::OptionalFlag &flag, 5412 const char *startSpecifier, 5413 unsigned specifierLen) { 5414 // Warn about pointless flag with a fixit removal. 5415 const analyze_printf::PrintfConversionSpecifier &CS = 5416 FS.getConversionSpecifier(); 5417 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 5418 << flag.toString() << CS.toString(), 5419 getLocationOfByte(flag.getPosition()), 5420 /*IsStringLocation*/true, 5421 getSpecifierRange(startSpecifier, specifierLen), 5422 FixItHint::CreateRemoval( 5423 getSpecifierRange(flag.getPosition(), 1))); 5424 } 5425 5426 void CheckPrintfHandler::HandleIgnoredFlag( 5427 const analyze_printf::PrintfSpecifier &FS, 5428 const analyze_printf::OptionalFlag &ignoredFlag, 5429 const analyze_printf::OptionalFlag &flag, 5430 const char *startSpecifier, 5431 unsigned specifierLen) { 5432 // Warn about ignored flag with a fixit removal. 5433 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 5434 << ignoredFlag.toString() << flag.toString(), 5435 getLocationOfByte(ignoredFlag.getPosition()), 5436 /*IsStringLocation*/true, 5437 getSpecifierRange(startSpecifier, specifierLen), 5438 FixItHint::CreateRemoval( 5439 getSpecifierRange(ignoredFlag.getPosition(), 1))); 5440 } 5441 5442 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5443 // bool IsStringLocation, Range StringRange, 5444 // ArrayRef<FixItHint> Fixit = None); 5445 5446 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 5447 unsigned flagLen) { 5448 // Warn about an empty flag. 5449 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 5450 getLocationOfByte(startFlag), 5451 /*IsStringLocation*/true, 5452 getSpecifierRange(startFlag, flagLen)); 5453 } 5454 5455 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 5456 unsigned flagLen) { 5457 // Warn about an invalid flag. 5458 auto Range = getSpecifierRange(startFlag, flagLen); 5459 StringRef flag(startFlag, flagLen); 5460 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 5461 getLocationOfByte(startFlag), 5462 /*IsStringLocation*/true, 5463 Range, FixItHint::CreateRemoval(Range)); 5464 } 5465 5466 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 5467 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 5468 // Warn about using '[...]' without a '@' conversion. 5469 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 5470 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 5471 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 5472 getLocationOfByte(conversionPosition), 5473 /*IsStringLocation*/true, 5474 Range, FixItHint::CreateRemoval(Range)); 5475 } 5476 5477 // Determines if the specified is a C++ class or struct containing 5478 // a member with the specified name and kind (e.g. a CXXMethodDecl named 5479 // "c_str()"). 5480 template<typename MemberKind> 5481 static llvm::SmallPtrSet<MemberKind*, 1> 5482 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 5483 const RecordType *RT = Ty->getAs<RecordType>(); 5484 llvm::SmallPtrSet<MemberKind*, 1> Results; 5485 5486 if (!RT) 5487 return Results; 5488 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 5489 if (!RD || !RD->getDefinition()) 5490 return Results; 5491 5492 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 5493 Sema::LookupMemberName); 5494 R.suppressDiagnostics(); 5495 5496 // We just need to include all members of the right kind turned up by the 5497 // filter, at this point. 5498 if (S.LookupQualifiedName(R, RT->getDecl())) 5499 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 5500 NamedDecl *decl = (*I)->getUnderlyingDecl(); 5501 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 5502 Results.insert(FK); 5503 } 5504 return Results; 5505 } 5506 5507 /// Check if we could call '.c_str()' on an object. 5508 /// 5509 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 5510 /// allow the call, or if it would be ambiguous). 5511 bool Sema::hasCStrMethod(const Expr *E) { 5512 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5513 MethodSet Results = 5514 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 5515 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5516 MI != ME; ++MI) 5517 if ((*MI)->getMinRequiredArguments() == 0) 5518 return true; 5519 return false; 5520 } 5521 5522 // Check if a (w)string was passed when a (w)char* was needed, and offer a 5523 // better diagnostic if so. AT is assumed to be valid. 5524 // Returns true when a c_str() conversion method is found. 5525 bool CheckPrintfHandler::checkForCStrMembers( 5526 const analyze_printf::ArgType &AT, const Expr *E) { 5527 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 5528 5529 MethodSet Results = 5530 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 5531 5532 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 5533 MI != ME; ++MI) { 5534 const CXXMethodDecl *Method = *MI; 5535 if (Method->getMinRequiredArguments() == 0 && 5536 AT.matchesType(S.Context, Method->getReturnType())) { 5537 // FIXME: Suggest parens if the expression needs them. 5538 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 5539 S.Diag(E->getLocStart(), diag::note_printf_c_str) 5540 << "c_str()" 5541 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 5542 return true; 5543 } 5544 } 5545 5546 return false; 5547 } 5548 5549 bool 5550 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 5551 &FS, 5552 const char *startSpecifier, 5553 unsigned specifierLen) { 5554 using namespace analyze_format_string; 5555 using namespace analyze_printf; 5556 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 5557 5558 if (FS.consumesDataArgument()) { 5559 if (atFirstArg) { 5560 atFirstArg = false; 5561 usesPositionalArgs = FS.usesPositionalArg(); 5562 } 5563 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5564 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5565 startSpecifier, specifierLen); 5566 return false; 5567 } 5568 } 5569 5570 // First check if the field width, precision, and conversion specifier 5571 // have matching data arguments. 5572 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 5573 startSpecifier, specifierLen)) { 5574 return false; 5575 } 5576 5577 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 5578 startSpecifier, specifierLen)) { 5579 return false; 5580 } 5581 5582 if (!CS.consumesDataArgument()) { 5583 // FIXME: Technically specifying a precision or field width here 5584 // makes no sense. Worth issuing a warning at some point. 5585 return true; 5586 } 5587 5588 // Consume the argument. 5589 unsigned argIndex = FS.getArgIndex(); 5590 if (argIndex < NumDataArgs) { 5591 // The check to see if the argIndex is valid will come later. 5592 // We set the bit here because we may exit early from this 5593 // function if we encounter some other error. 5594 CoveredArgs.set(argIndex); 5595 } 5596 5597 // FreeBSD kernel extensions. 5598 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 5599 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 5600 // We need at least two arguments. 5601 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 5602 return false; 5603 5604 // Claim the second argument. 5605 CoveredArgs.set(argIndex + 1); 5606 5607 // Type check the first argument (int for %b, pointer for %D) 5608 const Expr *Ex = getDataArg(argIndex); 5609 const analyze_printf::ArgType &AT = 5610 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 5611 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 5612 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 5613 EmitFormatDiagnostic( 5614 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5615 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 5616 << false << Ex->getSourceRange(), 5617 Ex->getLocStart(), /*IsStringLocation*/false, 5618 getSpecifierRange(startSpecifier, specifierLen)); 5619 5620 // Type check the second argument (char * for both %b and %D) 5621 Ex = getDataArg(argIndex + 1); 5622 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 5623 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 5624 EmitFormatDiagnostic( 5625 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5626 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 5627 << false << Ex->getSourceRange(), 5628 Ex->getLocStart(), /*IsStringLocation*/false, 5629 getSpecifierRange(startSpecifier, specifierLen)); 5630 5631 return true; 5632 } 5633 5634 // Check for using an Objective-C specific conversion specifier 5635 // in a non-ObjC literal. 5636 if (!allowsObjCArg() && CS.isObjCArg()) { 5637 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5638 specifierLen); 5639 } 5640 5641 // %P can only be used with os_log. 5642 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 5643 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5644 specifierLen); 5645 } 5646 5647 // %n is not allowed with os_log. 5648 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 5649 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 5650 getLocationOfByte(CS.getStart()), 5651 /*IsStringLocation*/ false, 5652 getSpecifierRange(startSpecifier, specifierLen)); 5653 5654 return true; 5655 } 5656 5657 // Only scalars are allowed for os_trace. 5658 if (FSType == Sema::FST_OSTrace && 5659 (CS.getKind() == ConversionSpecifier::PArg || 5660 CS.getKind() == ConversionSpecifier::sArg || 5661 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 5662 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 5663 specifierLen); 5664 } 5665 5666 // Check for use of public/private annotation outside of os_log(). 5667 if (FSType != Sema::FST_OSLog) { 5668 if (FS.isPublic().isSet()) { 5669 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 5670 << "public", 5671 getLocationOfByte(FS.isPublic().getPosition()), 5672 /*IsStringLocation*/ false, 5673 getSpecifierRange(startSpecifier, specifierLen)); 5674 } 5675 if (FS.isPrivate().isSet()) { 5676 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 5677 << "private", 5678 getLocationOfByte(FS.isPrivate().getPosition()), 5679 /*IsStringLocation*/ false, 5680 getSpecifierRange(startSpecifier, specifierLen)); 5681 } 5682 } 5683 5684 // Check for invalid use of field width 5685 if (!FS.hasValidFieldWidth()) { 5686 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 5687 startSpecifier, specifierLen); 5688 } 5689 5690 // Check for invalid use of precision 5691 if (!FS.hasValidPrecision()) { 5692 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 5693 startSpecifier, specifierLen); 5694 } 5695 5696 // Precision is mandatory for %P specifier. 5697 if (CS.getKind() == ConversionSpecifier::PArg && 5698 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 5699 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 5700 getLocationOfByte(startSpecifier), 5701 /*IsStringLocation*/ false, 5702 getSpecifierRange(startSpecifier, specifierLen)); 5703 } 5704 5705 // Check each flag does not conflict with any other component. 5706 if (!FS.hasValidThousandsGroupingPrefix()) 5707 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 5708 if (!FS.hasValidLeadingZeros()) 5709 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 5710 if (!FS.hasValidPlusPrefix()) 5711 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 5712 if (!FS.hasValidSpacePrefix()) 5713 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 5714 if (!FS.hasValidAlternativeForm()) 5715 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 5716 if (!FS.hasValidLeftJustified()) 5717 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 5718 5719 // Check that flags are not ignored by another flag 5720 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 5721 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 5722 startSpecifier, specifierLen); 5723 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 5724 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 5725 startSpecifier, specifierLen); 5726 5727 // Check the length modifier is valid with the given conversion specifier. 5728 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 5729 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5730 diag::warn_format_nonsensical_length); 5731 else if (!FS.hasStandardLengthModifier()) 5732 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 5733 else if (!FS.hasStandardLengthConversionCombination()) 5734 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5735 diag::warn_format_non_standard_conversion_spec); 5736 5737 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 5738 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 5739 5740 // The remaining checks depend on the data arguments. 5741 if (HasVAListArg) 5742 return true; 5743 5744 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 5745 return false; 5746 5747 const Expr *Arg = getDataArg(argIndex); 5748 if (!Arg) 5749 return true; 5750 5751 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 5752 } 5753 5754 static bool requiresParensToAddCast(const Expr *E) { 5755 // FIXME: We should have a general way to reason about operator 5756 // precedence and whether parens are actually needed here. 5757 // Take care of a few common cases where they aren't. 5758 const Expr *Inside = E->IgnoreImpCasts(); 5759 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 5760 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 5761 5762 switch (Inside->getStmtClass()) { 5763 case Stmt::ArraySubscriptExprClass: 5764 case Stmt::CallExprClass: 5765 case Stmt::CharacterLiteralClass: 5766 case Stmt::CXXBoolLiteralExprClass: 5767 case Stmt::DeclRefExprClass: 5768 case Stmt::FloatingLiteralClass: 5769 case Stmt::IntegerLiteralClass: 5770 case Stmt::MemberExprClass: 5771 case Stmt::ObjCArrayLiteralClass: 5772 case Stmt::ObjCBoolLiteralExprClass: 5773 case Stmt::ObjCBoxedExprClass: 5774 case Stmt::ObjCDictionaryLiteralClass: 5775 case Stmt::ObjCEncodeExprClass: 5776 case Stmt::ObjCIvarRefExprClass: 5777 case Stmt::ObjCMessageExprClass: 5778 case Stmt::ObjCPropertyRefExprClass: 5779 case Stmt::ObjCStringLiteralClass: 5780 case Stmt::ObjCSubscriptRefExprClass: 5781 case Stmt::ParenExprClass: 5782 case Stmt::StringLiteralClass: 5783 case Stmt::UnaryOperatorClass: 5784 return false; 5785 default: 5786 return true; 5787 } 5788 } 5789 5790 static std::pair<QualType, StringRef> 5791 shouldNotPrintDirectly(const ASTContext &Context, 5792 QualType IntendedTy, 5793 const Expr *E) { 5794 // Use a 'while' to peel off layers of typedefs. 5795 QualType TyTy = IntendedTy; 5796 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 5797 StringRef Name = UserTy->getDecl()->getName(); 5798 QualType CastTy = llvm::StringSwitch<QualType>(Name) 5799 .Case("NSInteger", Context.LongTy) 5800 .Case("NSUInteger", Context.UnsignedLongTy) 5801 .Case("SInt32", Context.IntTy) 5802 .Case("UInt32", Context.UnsignedIntTy) 5803 .Default(QualType()); 5804 5805 if (!CastTy.isNull()) 5806 return std::make_pair(CastTy, Name); 5807 5808 TyTy = UserTy->desugar(); 5809 } 5810 5811 // Strip parens if necessary. 5812 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 5813 return shouldNotPrintDirectly(Context, 5814 PE->getSubExpr()->getType(), 5815 PE->getSubExpr()); 5816 5817 // If this is a conditional expression, then its result type is constructed 5818 // via usual arithmetic conversions and thus there might be no necessary 5819 // typedef sugar there. Recurse to operands to check for NSInteger & 5820 // Co. usage condition. 5821 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 5822 QualType TrueTy, FalseTy; 5823 StringRef TrueName, FalseName; 5824 5825 std::tie(TrueTy, TrueName) = 5826 shouldNotPrintDirectly(Context, 5827 CO->getTrueExpr()->getType(), 5828 CO->getTrueExpr()); 5829 std::tie(FalseTy, FalseName) = 5830 shouldNotPrintDirectly(Context, 5831 CO->getFalseExpr()->getType(), 5832 CO->getFalseExpr()); 5833 5834 if (TrueTy == FalseTy) 5835 return std::make_pair(TrueTy, TrueName); 5836 else if (TrueTy.isNull()) 5837 return std::make_pair(FalseTy, FalseName); 5838 else if (FalseTy.isNull()) 5839 return std::make_pair(TrueTy, TrueName); 5840 } 5841 5842 return std::make_pair(QualType(), StringRef()); 5843 } 5844 5845 bool 5846 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 5847 const char *StartSpecifier, 5848 unsigned SpecifierLen, 5849 const Expr *E) { 5850 using namespace analyze_format_string; 5851 using namespace analyze_printf; 5852 // Now type check the data expression that matches the 5853 // format specifier. 5854 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 5855 if (!AT.isValid()) 5856 return true; 5857 5858 QualType ExprTy = E->getType(); 5859 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 5860 ExprTy = TET->getUnderlyingExpr()->getType(); 5861 } 5862 5863 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 5864 5865 if (match == analyze_printf::ArgType::Match) { 5866 return true; 5867 } 5868 5869 // Look through argument promotions for our error message's reported type. 5870 // This includes the integral and floating promotions, but excludes array 5871 // and function pointer decay; seeing that an argument intended to be a 5872 // string has type 'char [6]' is probably more confusing than 'char *'. 5873 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5874 if (ICE->getCastKind() == CK_IntegralCast || 5875 ICE->getCastKind() == CK_FloatingCast) { 5876 E = ICE->getSubExpr(); 5877 ExprTy = E->getType(); 5878 5879 // Check if we didn't match because of an implicit cast from a 'char' 5880 // or 'short' to an 'int'. This is done because printf is a varargs 5881 // function. 5882 if (ICE->getType() == S.Context.IntTy || 5883 ICE->getType() == S.Context.UnsignedIntTy) { 5884 // All further checking is done on the subexpression. 5885 if (AT.matchesType(S.Context, ExprTy)) 5886 return true; 5887 } 5888 } 5889 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 5890 // Special case for 'a', which has type 'int' in C. 5891 // Note, however, that we do /not/ want to treat multibyte constants like 5892 // 'MooV' as characters! This form is deprecated but still exists. 5893 if (ExprTy == S.Context.IntTy) 5894 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 5895 ExprTy = S.Context.CharTy; 5896 } 5897 5898 // Look through enums to their underlying type. 5899 bool IsEnum = false; 5900 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 5901 ExprTy = EnumTy->getDecl()->getIntegerType(); 5902 IsEnum = true; 5903 } 5904 5905 // %C in an Objective-C context prints a unichar, not a wchar_t. 5906 // If the argument is an integer of some kind, believe the %C and suggest 5907 // a cast instead of changing the conversion specifier. 5908 QualType IntendedTy = ExprTy; 5909 if (isObjCContext() && 5910 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 5911 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 5912 !ExprTy->isCharType()) { 5913 // 'unichar' is defined as a typedef of unsigned short, but we should 5914 // prefer using the typedef if it is visible. 5915 IntendedTy = S.Context.UnsignedShortTy; 5916 5917 // While we are here, check if the value is an IntegerLiteral that happens 5918 // to be within the valid range. 5919 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 5920 const llvm::APInt &V = IL->getValue(); 5921 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 5922 return true; 5923 } 5924 5925 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 5926 Sema::LookupOrdinaryName); 5927 if (S.LookupName(Result, S.getCurScope())) { 5928 NamedDecl *ND = Result.getFoundDecl(); 5929 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 5930 if (TD->getUnderlyingType() == IntendedTy) 5931 IntendedTy = S.Context.getTypedefType(TD); 5932 } 5933 } 5934 } 5935 5936 // Special-case some of Darwin's platform-independence types by suggesting 5937 // casts to primitive types that are known to be large enough. 5938 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 5939 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 5940 QualType CastTy; 5941 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 5942 if (!CastTy.isNull()) { 5943 IntendedTy = CastTy; 5944 ShouldNotPrintDirectly = true; 5945 } 5946 } 5947 5948 // We may be able to offer a FixItHint if it is a supported type. 5949 PrintfSpecifier fixedFS = FS; 5950 bool success = 5951 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 5952 5953 if (success) { 5954 // Get the fix string from the fixed format specifier 5955 SmallString<16> buf; 5956 llvm::raw_svector_ostream os(buf); 5957 fixedFS.toString(os); 5958 5959 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 5960 5961 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 5962 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 5963 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 5964 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 5965 } 5966 // In this case, the specifier is wrong and should be changed to match 5967 // the argument. 5968 EmitFormatDiagnostic(S.PDiag(diag) 5969 << AT.getRepresentativeTypeName(S.Context) 5970 << IntendedTy << IsEnum << E->getSourceRange(), 5971 E->getLocStart(), 5972 /*IsStringLocation*/ false, SpecRange, 5973 FixItHint::CreateReplacement(SpecRange, os.str())); 5974 } else { 5975 // The canonical type for formatting this value is different from the 5976 // actual type of the expression. (This occurs, for example, with Darwin's 5977 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 5978 // should be printed as 'long' for 64-bit compatibility.) 5979 // Rather than emitting a normal format/argument mismatch, we want to 5980 // add a cast to the recommended type (and correct the format string 5981 // if necessary). 5982 SmallString<16> CastBuf; 5983 llvm::raw_svector_ostream CastFix(CastBuf); 5984 CastFix << "("; 5985 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 5986 CastFix << ")"; 5987 5988 SmallVector<FixItHint,4> Hints; 5989 if (!AT.matchesType(S.Context, IntendedTy)) 5990 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 5991 5992 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 5993 // If there's already a cast present, just replace it. 5994 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 5995 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 5996 5997 } else if (!requiresParensToAddCast(E)) { 5998 // If the expression has high enough precedence, 5999 // just write the C-style cast. 6000 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6001 CastFix.str())); 6002 } else { 6003 // Otherwise, add parens around the expression as well as the cast. 6004 CastFix << "("; 6005 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6006 CastFix.str())); 6007 6008 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6009 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6010 } 6011 6012 if (ShouldNotPrintDirectly) { 6013 // The expression has a type that should not be printed directly. 6014 // We extract the name from the typedef because we don't want to show 6015 // the underlying type in the diagnostic. 6016 StringRef Name; 6017 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6018 Name = TypedefTy->getDecl()->getName(); 6019 else 6020 Name = CastTyName; 6021 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6022 << Name << IntendedTy << IsEnum 6023 << E->getSourceRange(), 6024 E->getLocStart(), /*IsStringLocation=*/false, 6025 SpecRange, Hints); 6026 } else { 6027 // In this case, the expression could be printed using a different 6028 // specifier, but we've decided that the specifier is probably correct 6029 // and we should cast instead. Just use the normal warning message. 6030 EmitFormatDiagnostic( 6031 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6032 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6033 << E->getSourceRange(), 6034 E->getLocStart(), /*IsStringLocation*/false, 6035 SpecRange, Hints); 6036 } 6037 } 6038 } else { 6039 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6040 SpecifierLen); 6041 // Since the warning for passing non-POD types to variadic functions 6042 // was deferred until now, we emit a warning for non-POD 6043 // arguments here. 6044 switch (S.isValidVarArgType(ExprTy)) { 6045 case Sema::VAK_Valid: 6046 case Sema::VAK_ValidInCXX11: { 6047 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6048 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6049 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6050 } 6051 6052 EmitFormatDiagnostic( 6053 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6054 << IsEnum << CSR << E->getSourceRange(), 6055 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6056 break; 6057 } 6058 case Sema::VAK_Undefined: 6059 case Sema::VAK_MSVCUndefined: 6060 EmitFormatDiagnostic( 6061 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6062 << S.getLangOpts().CPlusPlus11 6063 << ExprTy 6064 << CallType 6065 << AT.getRepresentativeTypeName(S.Context) 6066 << CSR 6067 << E->getSourceRange(), 6068 E->getLocStart(), /*IsStringLocation*/false, CSR); 6069 checkForCStrMembers(AT, E); 6070 break; 6071 6072 case Sema::VAK_Invalid: 6073 if (ExprTy->isObjCObjectType()) 6074 EmitFormatDiagnostic( 6075 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 6076 << S.getLangOpts().CPlusPlus11 6077 << ExprTy 6078 << CallType 6079 << AT.getRepresentativeTypeName(S.Context) 6080 << CSR 6081 << E->getSourceRange(), 6082 E->getLocStart(), /*IsStringLocation*/false, CSR); 6083 else 6084 // FIXME: If this is an initializer list, suggest removing the braces 6085 // or inserting a cast to the target type. 6086 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 6087 << isa<InitListExpr>(E) << ExprTy << CallType 6088 << AT.getRepresentativeTypeName(S.Context) 6089 << E->getSourceRange(); 6090 break; 6091 } 6092 6093 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 6094 "format string specifier index out of range"); 6095 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 6096 } 6097 6098 return true; 6099 } 6100 6101 //===--- CHECK: Scanf format string checking ------------------------------===// 6102 6103 namespace { 6104 class CheckScanfHandler : public CheckFormatHandler { 6105 public: 6106 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 6107 const Expr *origFormatExpr, Sema::FormatStringType type, 6108 unsigned firstDataArg, unsigned numDataArgs, 6109 const char *beg, bool hasVAListArg, 6110 ArrayRef<const Expr *> Args, unsigned formatIdx, 6111 bool inFunctionCall, Sema::VariadicCallType CallType, 6112 llvm::SmallBitVector &CheckedVarArgs, 6113 UncoveredArgHandler &UncoveredArg) 6114 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6115 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6116 inFunctionCall, CallType, CheckedVarArgs, 6117 UncoveredArg) {} 6118 6119 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 6120 const char *startSpecifier, 6121 unsigned specifierLen) override; 6122 6123 bool HandleInvalidScanfConversionSpecifier( 6124 const analyze_scanf::ScanfSpecifier &FS, 6125 const char *startSpecifier, 6126 unsigned specifierLen) override; 6127 6128 void HandleIncompleteScanList(const char *start, const char *end) override; 6129 }; 6130 } // end anonymous namespace 6131 6132 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 6133 const char *end) { 6134 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 6135 getLocationOfByte(end), /*IsStringLocation*/true, 6136 getSpecifierRange(start, end - start)); 6137 } 6138 6139 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 6140 const analyze_scanf::ScanfSpecifier &FS, 6141 const char *startSpecifier, 6142 unsigned specifierLen) { 6143 6144 const analyze_scanf::ScanfConversionSpecifier &CS = 6145 FS.getConversionSpecifier(); 6146 6147 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6148 getLocationOfByte(CS.getStart()), 6149 startSpecifier, specifierLen, 6150 CS.getStart(), CS.getLength()); 6151 } 6152 6153 bool CheckScanfHandler::HandleScanfSpecifier( 6154 const analyze_scanf::ScanfSpecifier &FS, 6155 const char *startSpecifier, 6156 unsigned specifierLen) { 6157 using namespace analyze_scanf; 6158 using namespace analyze_format_string; 6159 6160 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 6161 6162 // Handle case where '%' and '*' don't consume an argument. These shouldn't 6163 // be used to decide if we are using positional arguments consistently. 6164 if (FS.consumesDataArgument()) { 6165 if (atFirstArg) { 6166 atFirstArg = false; 6167 usesPositionalArgs = FS.usesPositionalArg(); 6168 } 6169 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6170 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6171 startSpecifier, specifierLen); 6172 return false; 6173 } 6174 } 6175 6176 // Check if the field with is non-zero. 6177 const OptionalAmount &Amt = FS.getFieldWidth(); 6178 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 6179 if (Amt.getConstantAmount() == 0) { 6180 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 6181 Amt.getConstantLength()); 6182 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 6183 getLocationOfByte(Amt.getStart()), 6184 /*IsStringLocation*/true, R, 6185 FixItHint::CreateRemoval(R)); 6186 } 6187 } 6188 6189 if (!FS.consumesDataArgument()) { 6190 // FIXME: Technically specifying a precision or field width here 6191 // makes no sense. Worth issuing a warning at some point. 6192 return true; 6193 } 6194 6195 // Consume the argument. 6196 unsigned argIndex = FS.getArgIndex(); 6197 if (argIndex < NumDataArgs) { 6198 // The check to see if the argIndex is valid will come later. 6199 // We set the bit here because we may exit early from this 6200 // function if we encounter some other error. 6201 CoveredArgs.set(argIndex); 6202 } 6203 6204 // Check the length modifier is valid with the given conversion specifier. 6205 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6206 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6207 diag::warn_format_nonsensical_length); 6208 else if (!FS.hasStandardLengthModifier()) 6209 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6210 else if (!FS.hasStandardLengthConversionCombination()) 6211 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6212 diag::warn_format_non_standard_conversion_spec); 6213 6214 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6215 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6216 6217 // The remaining checks depend on the data arguments. 6218 if (HasVAListArg) 6219 return true; 6220 6221 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6222 return false; 6223 6224 // Check that the argument type matches the format specifier. 6225 const Expr *Ex = getDataArg(argIndex); 6226 if (!Ex) 6227 return true; 6228 6229 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 6230 6231 if (!AT.isValid()) { 6232 return true; 6233 } 6234 6235 analyze_format_string::ArgType::MatchKind match = 6236 AT.matchesType(S.Context, Ex->getType()); 6237 if (match == analyze_format_string::ArgType::Match) { 6238 return true; 6239 } 6240 6241 ScanfSpecifier fixedFS = FS; 6242 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 6243 S.getLangOpts(), S.Context); 6244 6245 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6246 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6247 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6248 } 6249 6250 if (success) { 6251 // Get the fix string from the fixed format specifier. 6252 SmallString<128> buf; 6253 llvm::raw_svector_ostream os(buf); 6254 fixedFS.toString(os); 6255 6256 EmitFormatDiagnostic( 6257 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 6258 << Ex->getType() << false << Ex->getSourceRange(), 6259 Ex->getLocStart(), 6260 /*IsStringLocation*/ false, 6261 getSpecifierRange(startSpecifier, specifierLen), 6262 FixItHint::CreateReplacement( 6263 getSpecifierRange(startSpecifier, specifierLen), os.str())); 6264 } else { 6265 EmitFormatDiagnostic(S.PDiag(diag) 6266 << AT.getRepresentativeTypeName(S.Context) 6267 << Ex->getType() << false << Ex->getSourceRange(), 6268 Ex->getLocStart(), 6269 /*IsStringLocation*/ false, 6270 getSpecifierRange(startSpecifier, specifierLen)); 6271 } 6272 6273 return true; 6274 } 6275 6276 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6277 const Expr *OrigFormatExpr, 6278 ArrayRef<const Expr *> Args, 6279 bool HasVAListArg, unsigned format_idx, 6280 unsigned firstDataArg, 6281 Sema::FormatStringType Type, 6282 bool inFunctionCall, 6283 Sema::VariadicCallType CallType, 6284 llvm::SmallBitVector &CheckedVarArgs, 6285 UncoveredArgHandler &UncoveredArg) { 6286 // CHECK: is the format string a wide literal? 6287 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 6288 CheckFormatHandler::EmitFormatDiagnostic( 6289 S, inFunctionCall, Args[format_idx], 6290 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 6291 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6292 return; 6293 } 6294 6295 // Str - The format string. NOTE: this is NOT null-terminated! 6296 StringRef StrRef = FExpr->getString(); 6297 const char *Str = StrRef.data(); 6298 // Account for cases where the string literal is truncated in a declaration. 6299 const ConstantArrayType *T = 6300 S.Context.getAsConstantArrayType(FExpr->getType()); 6301 assert(T && "String literal not of constant array type!"); 6302 size_t TypeSize = T->getSize().getZExtValue(); 6303 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6304 const unsigned numDataArgs = Args.size() - firstDataArg; 6305 6306 // Emit a warning if the string literal is truncated and does not contain an 6307 // embedded null character. 6308 if (TypeSize <= StrRef.size() && 6309 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 6310 CheckFormatHandler::EmitFormatDiagnostic( 6311 S, inFunctionCall, Args[format_idx], 6312 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 6313 FExpr->getLocStart(), 6314 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 6315 return; 6316 } 6317 6318 // CHECK: empty format string? 6319 if (StrLen == 0 && numDataArgs > 0) { 6320 CheckFormatHandler::EmitFormatDiagnostic( 6321 S, inFunctionCall, Args[format_idx], 6322 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 6323 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 6324 return; 6325 } 6326 6327 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 6328 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 6329 Type == Sema::FST_OSTrace) { 6330 CheckPrintfHandler H( 6331 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 6332 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 6333 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 6334 CheckedVarArgs, UncoveredArg); 6335 6336 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 6337 S.getLangOpts(), 6338 S.Context.getTargetInfo(), 6339 Type == Sema::FST_FreeBSDKPrintf)) 6340 H.DoneProcessing(); 6341 } else if (Type == Sema::FST_Scanf) { 6342 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 6343 numDataArgs, Str, HasVAListArg, Args, format_idx, 6344 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 6345 6346 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 6347 S.getLangOpts(), 6348 S.Context.getTargetInfo())) 6349 H.DoneProcessing(); 6350 } // TODO: handle other formats 6351 } 6352 6353 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 6354 // Str - The format string. NOTE: this is NOT null-terminated! 6355 StringRef StrRef = FExpr->getString(); 6356 const char *Str = StrRef.data(); 6357 // Account for cases where the string literal is truncated in a declaration. 6358 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 6359 assert(T && "String literal not of constant array type!"); 6360 size_t TypeSize = T->getSize().getZExtValue(); 6361 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 6362 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 6363 getLangOpts(), 6364 Context.getTargetInfo()); 6365 } 6366 6367 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 6368 6369 // Returns the related absolute value function that is larger, of 0 if one 6370 // does not exist. 6371 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 6372 switch (AbsFunction) { 6373 default: 6374 return 0; 6375 6376 case Builtin::BI__builtin_abs: 6377 return Builtin::BI__builtin_labs; 6378 case Builtin::BI__builtin_labs: 6379 return Builtin::BI__builtin_llabs; 6380 case Builtin::BI__builtin_llabs: 6381 return 0; 6382 6383 case Builtin::BI__builtin_fabsf: 6384 return Builtin::BI__builtin_fabs; 6385 case Builtin::BI__builtin_fabs: 6386 return Builtin::BI__builtin_fabsl; 6387 case Builtin::BI__builtin_fabsl: 6388 return 0; 6389 6390 case Builtin::BI__builtin_cabsf: 6391 return Builtin::BI__builtin_cabs; 6392 case Builtin::BI__builtin_cabs: 6393 return Builtin::BI__builtin_cabsl; 6394 case Builtin::BI__builtin_cabsl: 6395 return 0; 6396 6397 case Builtin::BIabs: 6398 return Builtin::BIlabs; 6399 case Builtin::BIlabs: 6400 return Builtin::BIllabs; 6401 case Builtin::BIllabs: 6402 return 0; 6403 6404 case Builtin::BIfabsf: 6405 return Builtin::BIfabs; 6406 case Builtin::BIfabs: 6407 return Builtin::BIfabsl; 6408 case Builtin::BIfabsl: 6409 return 0; 6410 6411 case Builtin::BIcabsf: 6412 return Builtin::BIcabs; 6413 case Builtin::BIcabs: 6414 return Builtin::BIcabsl; 6415 case Builtin::BIcabsl: 6416 return 0; 6417 } 6418 } 6419 6420 // Returns the argument type of the absolute value function. 6421 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 6422 unsigned AbsType) { 6423 if (AbsType == 0) 6424 return QualType(); 6425 6426 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 6427 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 6428 if (Error != ASTContext::GE_None) 6429 return QualType(); 6430 6431 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 6432 if (!FT) 6433 return QualType(); 6434 6435 if (FT->getNumParams() != 1) 6436 return QualType(); 6437 6438 return FT->getParamType(0); 6439 } 6440 6441 // Returns the best absolute value function, or zero, based on type and 6442 // current absolute value function. 6443 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 6444 unsigned AbsFunctionKind) { 6445 unsigned BestKind = 0; 6446 uint64_t ArgSize = Context.getTypeSize(ArgType); 6447 for (unsigned Kind = AbsFunctionKind; Kind != 0; 6448 Kind = getLargerAbsoluteValueFunction(Kind)) { 6449 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 6450 if (Context.getTypeSize(ParamType) >= ArgSize) { 6451 if (BestKind == 0) 6452 BestKind = Kind; 6453 else if (Context.hasSameType(ParamType, ArgType)) { 6454 BestKind = Kind; 6455 break; 6456 } 6457 } 6458 } 6459 return BestKind; 6460 } 6461 6462 enum AbsoluteValueKind { 6463 AVK_Integer, 6464 AVK_Floating, 6465 AVK_Complex 6466 }; 6467 6468 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 6469 if (T->isIntegralOrEnumerationType()) 6470 return AVK_Integer; 6471 if (T->isRealFloatingType()) 6472 return AVK_Floating; 6473 if (T->isAnyComplexType()) 6474 return AVK_Complex; 6475 6476 llvm_unreachable("Type not integer, floating, or complex"); 6477 } 6478 6479 // Changes the absolute value function to a different type. Preserves whether 6480 // the function is a builtin. 6481 static unsigned changeAbsFunction(unsigned AbsKind, 6482 AbsoluteValueKind ValueKind) { 6483 switch (ValueKind) { 6484 case AVK_Integer: 6485 switch (AbsKind) { 6486 default: 6487 return 0; 6488 case Builtin::BI__builtin_fabsf: 6489 case Builtin::BI__builtin_fabs: 6490 case Builtin::BI__builtin_fabsl: 6491 case Builtin::BI__builtin_cabsf: 6492 case Builtin::BI__builtin_cabs: 6493 case Builtin::BI__builtin_cabsl: 6494 return Builtin::BI__builtin_abs; 6495 case Builtin::BIfabsf: 6496 case Builtin::BIfabs: 6497 case Builtin::BIfabsl: 6498 case Builtin::BIcabsf: 6499 case Builtin::BIcabs: 6500 case Builtin::BIcabsl: 6501 return Builtin::BIabs; 6502 } 6503 case AVK_Floating: 6504 switch (AbsKind) { 6505 default: 6506 return 0; 6507 case Builtin::BI__builtin_abs: 6508 case Builtin::BI__builtin_labs: 6509 case Builtin::BI__builtin_llabs: 6510 case Builtin::BI__builtin_cabsf: 6511 case Builtin::BI__builtin_cabs: 6512 case Builtin::BI__builtin_cabsl: 6513 return Builtin::BI__builtin_fabsf; 6514 case Builtin::BIabs: 6515 case Builtin::BIlabs: 6516 case Builtin::BIllabs: 6517 case Builtin::BIcabsf: 6518 case Builtin::BIcabs: 6519 case Builtin::BIcabsl: 6520 return Builtin::BIfabsf; 6521 } 6522 case AVK_Complex: 6523 switch (AbsKind) { 6524 default: 6525 return 0; 6526 case Builtin::BI__builtin_abs: 6527 case Builtin::BI__builtin_labs: 6528 case Builtin::BI__builtin_llabs: 6529 case Builtin::BI__builtin_fabsf: 6530 case Builtin::BI__builtin_fabs: 6531 case Builtin::BI__builtin_fabsl: 6532 return Builtin::BI__builtin_cabsf; 6533 case Builtin::BIabs: 6534 case Builtin::BIlabs: 6535 case Builtin::BIllabs: 6536 case Builtin::BIfabsf: 6537 case Builtin::BIfabs: 6538 case Builtin::BIfabsl: 6539 return Builtin::BIcabsf; 6540 } 6541 } 6542 llvm_unreachable("Unable to convert function"); 6543 } 6544 6545 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 6546 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 6547 if (!FnInfo) 6548 return 0; 6549 6550 switch (FDecl->getBuiltinID()) { 6551 default: 6552 return 0; 6553 case Builtin::BI__builtin_abs: 6554 case Builtin::BI__builtin_fabs: 6555 case Builtin::BI__builtin_fabsf: 6556 case Builtin::BI__builtin_fabsl: 6557 case Builtin::BI__builtin_labs: 6558 case Builtin::BI__builtin_llabs: 6559 case Builtin::BI__builtin_cabs: 6560 case Builtin::BI__builtin_cabsf: 6561 case Builtin::BI__builtin_cabsl: 6562 case Builtin::BIabs: 6563 case Builtin::BIlabs: 6564 case Builtin::BIllabs: 6565 case Builtin::BIfabs: 6566 case Builtin::BIfabsf: 6567 case Builtin::BIfabsl: 6568 case Builtin::BIcabs: 6569 case Builtin::BIcabsf: 6570 case Builtin::BIcabsl: 6571 return FDecl->getBuiltinID(); 6572 } 6573 llvm_unreachable("Unknown Builtin type"); 6574 } 6575 6576 // If the replacement is valid, emit a note with replacement function. 6577 // Additionally, suggest including the proper header if not already included. 6578 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 6579 unsigned AbsKind, QualType ArgType) { 6580 bool EmitHeaderHint = true; 6581 const char *HeaderName = nullptr; 6582 const char *FunctionName = nullptr; 6583 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 6584 FunctionName = "std::abs"; 6585 if (ArgType->isIntegralOrEnumerationType()) { 6586 HeaderName = "cstdlib"; 6587 } else if (ArgType->isRealFloatingType()) { 6588 HeaderName = "cmath"; 6589 } else { 6590 llvm_unreachable("Invalid Type"); 6591 } 6592 6593 // Lookup all std::abs 6594 if (NamespaceDecl *Std = S.getStdNamespace()) { 6595 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 6596 R.suppressDiagnostics(); 6597 S.LookupQualifiedName(R, Std); 6598 6599 for (const auto *I : R) { 6600 const FunctionDecl *FDecl = nullptr; 6601 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 6602 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 6603 } else { 6604 FDecl = dyn_cast<FunctionDecl>(I); 6605 } 6606 if (!FDecl) 6607 continue; 6608 6609 // Found std::abs(), check that they are the right ones. 6610 if (FDecl->getNumParams() != 1) 6611 continue; 6612 6613 // Check that the parameter type can handle the argument. 6614 QualType ParamType = FDecl->getParamDecl(0)->getType(); 6615 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 6616 S.Context.getTypeSize(ArgType) <= 6617 S.Context.getTypeSize(ParamType)) { 6618 // Found a function, don't need the header hint. 6619 EmitHeaderHint = false; 6620 break; 6621 } 6622 } 6623 } 6624 } else { 6625 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 6626 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 6627 6628 if (HeaderName) { 6629 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 6630 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 6631 R.suppressDiagnostics(); 6632 S.LookupName(R, S.getCurScope()); 6633 6634 if (R.isSingleResult()) { 6635 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 6636 if (FD && FD->getBuiltinID() == AbsKind) { 6637 EmitHeaderHint = false; 6638 } else { 6639 return; 6640 } 6641 } else if (!R.empty()) { 6642 return; 6643 } 6644 } 6645 } 6646 6647 S.Diag(Loc, diag::note_replace_abs_function) 6648 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 6649 6650 if (!HeaderName) 6651 return; 6652 6653 if (!EmitHeaderHint) 6654 return; 6655 6656 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 6657 << FunctionName; 6658 } 6659 6660 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) { 6661 if (!FDecl) 6662 return false; 6663 6664 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs")) 6665 return false; 6666 6667 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext()); 6668 6669 while (ND && ND->isInlineNamespace()) { 6670 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext()); 6671 } 6672 6673 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std")) 6674 return false; 6675 6676 if (!isa<TranslationUnitDecl>(ND->getDeclContext())) 6677 return false; 6678 6679 return true; 6680 } 6681 6682 // Warn when using the wrong abs() function. 6683 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 6684 const FunctionDecl *FDecl, 6685 IdentifierInfo *FnInfo) { 6686 if (Call->getNumArgs() != 1) 6687 return; 6688 6689 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 6690 bool IsStdAbs = IsFunctionStdAbs(FDecl); 6691 if (AbsKind == 0 && !IsStdAbs) 6692 return; 6693 6694 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 6695 QualType ParamType = Call->getArg(0)->getType(); 6696 6697 // Unsigned types cannot be negative. Suggest removing the absolute value 6698 // function call. 6699 if (ArgType->isUnsignedIntegerType()) { 6700 const char *FunctionName = 6701 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 6702 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 6703 Diag(Call->getExprLoc(), diag::note_remove_abs) 6704 << FunctionName 6705 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 6706 return; 6707 } 6708 6709 // Taking the absolute value of a pointer is very suspicious, they probably 6710 // wanted to index into an array, dereference a pointer, call a function, etc. 6711 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 6712 unsigned DiagType = 0; 6713 if (ArgType->isFunctionType()) 6714 DiagType = 1; 6715 else if (ArgType->isArrayType()) 6716 DiagType = 2; 6717 6718 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 6719 return; 6720 } 6721 6722 // std::abs has overloads which prevent most of the absolute value problems 6723 // from occurring. 6724 if (IsStdAbs) 6725 return; 6726 6727 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 6728 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 6729 6730 // The argument and parameter are the same kind. Check if they are the right 6731 // size. 6732 if (ArgValueKind == ParamValueKind) { 6733 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 6734 return; 6735 6736 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 6737 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 6738 << FDecl << ArgType << ParamType; 6739 6740 if (NewAbsKind == 0) 6741 return; 6742 6743 emitReplacement(*this, Call->getExprLoc(), 6744 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6745 return; 6746 } 6747 6748 // ArgValueKind != ParamValueKind 6749 // The wrong type of absolute value function was used. Attempt to find the 6750 // proper one. 6751 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 6752 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 6753 if (NewAbsKind == 0) 6754 return; 6755 6756 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 6757 << FDecl << ParamValueKind << ArgValueKind; 6758 6759 emitReplacement(*this, Call->getExprLoc(), 6760 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 6761 } 6762 6763 //===--- CHECK: Standard memory functions ---------------------------------===// 6764 6765 /// \brief Takes the expression passed to the size_t parameter of functions 6766 /// such as memcmp, strncat, etc and warns if it's a comparison. 6767 /// 6768 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 6769 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 6770 IdentifierInfo *FnName, 6771 SourceLocation FnLoc, 6772 SourceLocation RParenLoc) { 6773 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 6774 if (!Size) 6775 return false; 6776 6777 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 6778 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 6779 return false; 6780 6781 SourceRange SizeRange = Size->getSourceRange(); 6782 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 6783 << SizeRange << FnName; 6784 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 6785 << FnName << FixItHint::CreateInsertion( 6786 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 6787 << FixItHint::CreateRemoval(RParenLoc); 6788 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 6789 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 6790 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 6791 ")"); 6792 6793 return true; 6794 } 6795 6796 /// \brief Determine whether the given type is or contains a dynamic class type 6797 /// (e.g., whether it has a vtable). 6798 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 6799 bool &IsContained) { 6800 // Look through array types while ignoring qualifiers. 6801 const Type *Ty = T->getBaseElementTypeUnsafe(); 6802 IsContained = false; 6803 6804 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 6805 RD = RD ? RD->getDefinition() : nullptr; 6806 if (!RD || RD->isInvalidDecl()) 6807 return nullptr; 6808 6809 if (RD->isDynamicClass()) 6810 return RD; 6811 6812 // Check all the fields. If any bases were dynamic, the class is dynamic. 6813 // It's impossible for a class to transitively contain itself by value, so 6814 // infinite recursion is impossible. 6815 for (auto *FD : RD->fields()) { 6816 bool SubContained; 6817 if (const CXXRecordDecl *ContainedRD = 6818 getContainedDynamicClass(FD->getType(), SubContained)) { 6819 IsContained = true; 6820 return ContainedRD; 6821 } 6822 } 6823 6824 return nullptr; 6825 } 6826 6827 /// \brief If E is a sizeof expression, returns its argument expression, 6828 /// otherwise returns NULL. 6829 static const Expr *getSizeOfExprArg(const Expr *E) { 6830 if (const UnaryExprOrTypeTraitExpr *SizeOf = 6831 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 6832 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 6833 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 6834 6835 return nullptr; 6836 } 6837 6838 /// \brief If E is a sizeof expression, returns its argument type. 6839 static QualType getSizeOfArgType(const Expr *E) { 6840 if (const UnaryExprOrTypeTraitExpr *SizeOf = 6841 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 6842 if (SizeOf->getKind() == clang::UETT_SizeOf) 6843 return SizeOf->getTypeOfArgument(); 6844 6845 return QualType(); 6846 } 6847 6848 /// \brief Check for dangerous or invalid arguments to memset(). 6849 /// 6850 /// This issues warnings on known problematic, dangerous or unspecified 6851 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 6852 /// function calls. 6853 /// 6854 /// \param Call The call expression to diagnose. 6855 void Sema::CheckMemaccessArguments(const CallExpr *Call, 6856 unsigned BId, 6857 IdentifierInfo *FnName) { 6858 assert(BId != 0); 6859 6860 // It is possible to have a non-standard definition of memset. Validate 6861 // we have enough arguments, and if not, abort further checking. 6862 unsigned ExpectedNumArgs = 6863 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 6864 if (Call->getNumArgs() < ExpectedNumArgs) 6865 return; 6866 6867 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 6868 BId == Builtin::BIstrndup ? 1 : 2); 6869 unsigned LenArg = 6870 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 6871 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 6872 6873 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 6874 Call->getLocStart(), Call->getRParenLoc())) 6875 return; 6876 6877 // We have special checking when the length is a sizeof expression. 6878 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 6879 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 6880 llvm::FoldingSetNodeID SizeOfArgID; 6881 6882 // Although widely used, 'bzero' is not a standard function. Be more strict 6883 // with the argument types before allowing diagnostics and only allow the 6884 // form bzero(ptr, sizeof(...)). 6885 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 6886 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 6887 return; 6888 6889 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 6890 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 6891 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 6892 6893 QualType DestTy = Dest->getType(); 6894 QualType PointeeTy; 6895 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 6896 PointeeTy = DestPtrTy->getPointeeType(); 6897 6898 // Never warn about void type pointers. This can be used to suppress 6899 // false positives. 6900 if (PointeeTy->isVoidType()) 6901 continue; 6902 6903 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 6904 // actually comparing the expressions for equality. Because computing the 6905 // expression IDs can be expensive, we only do this if the diagnostic is 6906 // enabled. 6907 if (SizeOfArg && 6908 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 6909 SizeOfArg->getExprLoc())) { 6910 // We only compute IDs for expressions if the warning is enabled, and 6911 // cache the sizeof arg's ID. 6912 if (SizeOfArgID == llvm::FoldingSetNodeID()) 6913 SizeOfArg->Profile(SizeOfArgID, Context, true); 6914 llvm::FoldingSetNodeID DestID; 6915 Dest->Profile(DestID, Context, true); 6916 if (DestID == SizeOfArgID) { 6917 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 6918 // over sizeof(src) as well. 6919 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 6920 StringRef ReadableName = FnName->getName(); 6921 6922 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 6923 if (UnaryOp->getOpcode() == UO_AddrOf) 6924 ActionIdx = 1; // If its an address-of operator, just remove it. 6925 if (!PointeeTy->isIncompleteType() && 6926 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 6927 ActionIdx = 2; // If the pointee's size is sizeof(char), 6928 // suggest an explicit length. 6929 6930 // If the function is defined as a builtin macro, do not show macro 6931 // expansion. 6932 SourceLocation SL = SizeOfArg->getExprLoc(); 6933 SourceRange DSR = Dest->getSourceRange(); 6934 SourceRange SSR = SizeOfArg->getSourceRange(); 6935 SourceManager &SM = getSourceManager(); 6936 6937 if (SM.isMacroArgExpansion(SL)) { 6938 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 6939 SL = SM.getSpellingLoc(SL); 6940 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 6941 SM.getSpellingLoc(DSR.getEnd())); 6942 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 6943 SM.getSpellingLoc(SSR.getEnd())); 6944 } 6945 6946 DiagRuntimeBehavior(SL, SizeOfArg, 6947 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 6948 << ReadableName 6949 << PointeeTy 6950 << DestTy 6951 << DSR 6952 << SSR); 6953 DiagRuntimeBehavior(SL, SizeOfArg, 6954 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 6955 << ActionIdx 6956 << SSR); 6957 6958 break; 6959 } 6960 } 6961 6962 // Also check for cases where the sizeof argument is the exact same 6963 // type as the memory argument, and where it points to a user-defined 6964 // record type. 6965 if (SizeOfArgTy != QualType()) { 6966 if (PointeeTy->isRecordType() && 6967 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 6968 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 6969 PDiag(diag::warn_sizeof_pointer_type_memaccess) 6970 << FnName << SizeOfArgTy << ArgIdx 6971 << PointeeTy << Dest->getSourceRange() 6972 << LenExpr->getSourceRange()); 6973 break; 6974 } 6975 } 6976 } else if (DestTy->isArrayType()) { 6977 PointeeTy = DestTy; 6978 } 6979 6980 if (PointeeTy == QualType()) 6981 continue; 6982 6983 // Always complain about dynamic classes. 6984 bool IsContained; 6985 if (const CXXRecordDecl *ContainedRD = 6986 getContainedDynamicClass(PointeeTy, IsContained)) { 6987 6988 unsigned OperationType = 0; 6989 // "overwritten" if we're warning about the destination for any call 6990 // but memcmp; otherwise a verb appropriate to the call. 6991 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 6992 if (BId == Builtin::BImemcpy) 6993 OperationType = 1; 6994 else if(BId == Builtin::BImemmove) 6995 OperationType = 2; 6996 else if (BId == Builtin::BImemcmp) 6997 OperationType = 3; 6998 } 6999 7000 DiagRuntimeBehavior( 7001 Dest->getExprLoc(), Dest, 7002 PDiag(diag::warn_dyn_class_memaccess) 7003 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 7004 << FnName << IsContained << ContainedRD << OperationType 7005 << Call->getCallee()->getSourceRange()); 7006 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 7007 BId != Builtin::BImemset) 7008 DiagRuntimeBehavior( 7009 Dest->getExprLoc(), Dest, 7010 PDiag(diag::warn_arc_object_memaccess) 7011 << ArgIdx << FnName << PointeeTy 7012 << Call->getCallee()->getSourceRange()); 7013 else 7014 continue; 7015 7016 DiagRuntimeBehavior( 7017 Dest->getExprLoc(), Dest, 7018 PDiag(diag::note_bad_memaccess_silence) 7019 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 7020 break; 7021 } 7022 } 7023 7024 // A little helper routine: ignore addition and subtraction of integer literals. 7025 // This intentionally does not ignore all integer constant expressions because 7026 // we don't want to remove sizeof(). 7027 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 7028 Ex = Ex->IgnoreParenCasts(); 7029 7030 for (;;) { 7031 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 7032 if (!BO || !BO->isAdditiveOp()) 7033 break; 7034 7035 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 7036 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 7037 7038 if (isa<IntegerLiteral>(RHS)) 7039 Ex = LHS; 7040 else if (isa<IntegerLiteral>(LHS)) 7041 Ex = RHS; 7042 else 7043 break; 7044 } 7045 7046 return Ex; 7047 } 7048 7049 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 7050 ASTContext &Context) { 7051 // Only handle constant-sized or VLAs, but not flexible members. 7052 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 7053 // Only issue the FIXIT for arrays of size > 1. 7054 if (CAT->getSize().getSExtValue() <= 1) 7055 return false; 7056 } else if (!Ty->isVariableArrayType()) { 7057 return false; 7058 } 7059 return true; 7060 } 7061 7062 // Warn if the user has made the 'size' argument to strlcpy or strlcat 7063 // be the size of the source, instead of the destination. 7064 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 7065 IdentifierInfo *FnName) { 7066 7067 // Don't crash if the user has the wrong number of arguments 7068 unsigned NumArgs = Call->getNumArgs(); 7069 if ((NumArgs != 3) && (NumArgs != 4)) 7070 return; 7071 7072 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 7073 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 7074 const Expr *CompareWithSrc = nullptr; 7075 7076 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 7077 Call->getLocStart(), Call->getRParenLoc())) 7078 return; 7079 7080 // Look for 'strlcpy(dst, x, sizeof(x))' 7081 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 7082 CompareWithSrc = Ex; 7083 else { 7084 // Look for 'strlcpy(dst, x, strlen(x))' 7085 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 7086 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 7087 SizeCall->getNumArgs() == 1) 7088 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 7089 } 7090 } 7091 7092 if (!CompareWithSrc) 7093 return; 7094 7095 // Determine if the argument to sizeof/strlen is equal to the source 7096 // argument. In principle there's all kinds of things you could do 7097 // here, for instance creating an == expression and evaluating it with 7098 // EvaluateAsBooleanCondition, but this uses a more direct technique: 7099 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 7100 if (!SrcArgDRE) 7101 return; 7102 7103 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 7104 if (!CompareWithSrcDRE || 7105 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 7106 return; 7107 7108 const Expr *OriginalSizeArg = Call->getArg(2); 7109 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 7110 << OriginalSizeArg->getSourceRange() << FnName; 7111 7112 // Output a FIXIT hint if the destination is an array (rather than a 7113 // pointer to an array). This could be enhanced to handle some 7114 // pointers if we know the actual size, like if DstArg is 'array+2' 7115 // we could say 'sizeof(array)-2'. 7116 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 7117 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 7118 return; 7119 7120 SmallString<128> sizeString; 7121 llvm::raw_svector_ostream OS(sizeString); 7122 OS << "sizeof("; 7123 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7124 OS << ")"; 7125 7126 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 7127 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 7128 OS.str()); 7129 } 7130 7131 /// Check if two expressions refer to the same declaration. 7132 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 7133 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 7134 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 7135 return D1->getDecl() == D2->getDecl(); 7136 return false; 7137 } 7138 7139 static const Expr *getStrlenExprArg(const Expr *E) { 7140 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7141 const FunctionDecl *FD = CE->getDirectCallee(); 7142 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 7143 return nullptr; 7144 return CE->getArg(0)->IgnoreParenCasts(); 7145 } 7146 return nullptr; 7147 } 7148 7149 // Warn on anti-patterns as the 'size' argument to strncat. 7150 // The correct size argument should look like following: 7151 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 7152 void Sema::CheckStrncatArguments(const CallExpr *CE, 7153 IdentifierInfo *FnName) { 7154 // Don't crash if the user has the wrong number of arguments. 7155 if (CE->getNumArgs() < 3) 7156 return; 7157 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 7158 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 7159 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 7160 7161 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 7162 CE->getRParenLoc())) 7163 return; 7164 7165 // Identify common expressions, which are wrongly used as the size argument 7166 // to strncat and may lead to buffer overflows. 7167 unsigned PatternType = 0; 7168 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 7169 // - sizeof(dst) 7170 if (referToTheSameDecl(SizeOfArg, DstArg)) 7171 PatternType = 1; 7172 // - sizeof(src) 7173 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 7174 PatternType = 2; 7175 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 7176 if (BE->getOpcode() == BO_Sub) { 7177 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 7178 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 7179 // - sizeof(dst) - strlen(dst) 7180 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 7181 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 7182 PatternType = 1; 7183 // - sizeof(src) - (anything) 7184 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 7185 PatternType = 2; 7186 } 7187 } 7188 7189 if (PatternType == 0) 7190 return; 7191 7192 // Generate the diagnostic. 7193 SourceLocation SL = LenArg->getLocStart(); 7194 SourceRange SR = LenArg->getSourceRange(); 7195 SourceManager &SM = getSourceManager(); 7196 7197 // If the function is defined as a builtin macro, do not show macro expansion. 7198 if (SM.isMacroArgExpansion(SL)) { 7199 SL = SM.getSpellingLoc(SL); 7200 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 7201 SM.getSpellingLoc(SR.getEnd())); 7202 } 7203 7204 // Check if the destination is an array (rather than a pointer to an array). 7205 QualType DstTy = DstArg->getType(); 7206 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 7207 Context); 7208 if (!isKnownSizeArray) { 7209 if (PatternType == 1) 7210 Diag(SL, diag::warn_strncat_wrong_size) << SR; 7211 else 7212 Diag(SL, diag::warn_strncat_src_size) << SR; 7213 return; 7214 } 7215 7216 if (PatternType == 1) 7217 Diag(SL, diag::warn_strncat_large_size) << SR; 7218 else 7219 Diag(SL, diag::warn_strncat_src_size) << SR; 7220 7221 SmallString<128> sizeString; 7222 llvm::raw_svector_ostream OS(sizeString); 7223 OS << "sizeof("; 7224 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7225 OS << ") - "; 7226 OS << "strlen("; 7227 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 7228 OS << ") - 1"; 7229 7230 Diag(SL, diag::note_strncat_wrong_size) 7231 << FixItHint::CreateReplacement(SR, OS.str()); 7232 } 7233 7234 //===--- CHECK: Return Address of Stack Variable --------------------------===// 7235 7236 static const Expr *EvalVal(const Expr *E, 7237 SmallVectorImpl<const DeclRefExpr *> &refVars, 7238 const Decl *ParentDecl); 7239 static const Expr *EvalAddr(const Expr *E, 7240 SmallVectorImpl<const DeclRefExpr *> &refVars, 7241 const Decl *ParentDecl); 7242 7243 /// CheckReturnStackAddr - Check if a return statement returns the address 7244 /// of a stack variable. 7245 static void 7246 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 7247 SourceLocation ReturnLoc) { 7248 7249 const Expr *stackE = nullptr; 7250 SmallVector<const DeclRefExpr *, 8> refVars; 7251 7252 // Perform checking for returned stack addresses, local blocks, 7253 // label addresses or references to temporaries. 7254 if (lhsType->isPointerType() || 7255 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 7256 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 7257 } else if (lhsType->isReferenceType()) { 7258 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 7259 } 7260 7261 if (!stackE) 7262 return; // Nothing suspicious was found. 7263 7264 // Parameters are initalized in the calling scope, so taking the address 7265 // of a parameter reference doesn't need a warning. 7266 for (auto *DRE : refVars) 7267 if (isa<ParmVarDecl>(DRE->getDecl())) 7268 return; 7269 7270 SourceLocation diagLoc; 7271 SourceRange diagRange; 7272 if (refVars.empty()) { 7273 diagLoc = stackE->getLocStart(); 7274 diagRange = stackE->getSourceRange(); 7275 } else { 7276 // We followed through a reference variable. 'stackE' contains the 7277 // problematic expression but we will warn at the return statement pointing 7278 // at the reference variable. We will later display the "trail" of 7279 // reference variables using notes. 7280 diagLoc = refVars[0]->getLocStart(); 7281 diagRange = refVars[0]->getSourceRange(); 7282 } 7283 7284 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 7285 // address of local var 7286 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 7287 << DR->getDecl()->getDeclName() << diagRange; 7288 } else if (isa<BlockExpr>(stackE)) { // local block. 7289 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 7290 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 7291 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 7292 } else { // local temporary. 7293 // If there is an LValue->RValue conversion, then the value of the 7294 // reference type is used, not the reference. 7295 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 7296 if (ICE->getCastKind() == CK_LValueToRValue) { 7297 return; 7298 } 7299 } 7300 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 7301 << lhsType->isReferenceType() << diagRange; 7302 } 7303 7304 // Display the "trail" of reference variables that we followed until we 7305 // found the problematic expression using notes. 7306 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 7307 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 7308 // If this var binds to another reference var, show the range of the next 7309 // var, otherwise the var binds to the problematic expression, in which case 7310 // show the range of the expression. 7311 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 7312 : stackE->getSourceRange(); 7313 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 7314 << VD->getDeclName() << range; 7315 } 7316 } 7317 7318 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 7319 /// check if the expression in a return statement evaluates to an address 7320 /// to a location on the stack, a local block, an address of a label, or a 7321 /// reference to local temporary. The recursion is used to traverse the 7322 /// AST of the return expression, with recursion backtracking when we 7323 /// encounter a subexpression that (1) clearly does not lead to one of the 7324 /// above problematic expressions (2) is something we cannot determine leads to 7325 /// a problematic expression based on such local checking. 7326 /// 7327 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 7328 /// the expression that they point to. Such variables are added to the 7329 /// 'refVars' vector so that we know what the reference variable "trail" was. 7330 /// 7331 /// EvalAddr processes expressions that are pointers that are used as 7332 /// references (and not L-values). EvalVal handles all other values. 7333 /// At the base case of the recursion is a check for the above problematic 7334 /// expressions. 7335 /// 7336 /// This implementation handles: 7337 /// 7338 /// * pointer-to-pointer casts 7339 /// * implicit conversions from array references to pointers 7340 /// * taking the address of fields 7341 /// * arbitrary interplay between "&" and "*" operators 7342 /// * pointer arithmetic from an address of a stack variable 7343 /// * taking the address of an array element where the array is on the stack 7344 static const Expr *EvalAddr(const Expr *E, 7345 SmallVectorImpl<const DeclRefExpr *> &refVars, 7346 const Decl *ParentDecl) { 7347 if (E->isTypeDependent()) 7348 return nullptr; 7349 7350 // We should only be called for evaluating pointer expressions. 7351 assert((E->getType()->isAnyPointerType() || 7352 E->getType()->isBlockPointerType() || 7353 E->getType()->isObjCQualifiedIdType()) && 7354 "EvalAddr only works on pointers"); 7355 7356 E = E->IgnoreParens(); 7357 7358 // Our "symbolic interpreter" is just a dispatch off the currently 7359 // viewed AST node. We then recursively traverse the AST by calling 7360 // EvalAddr and EvalVal appropriately. 7361 switch (E->getStmtClass()) { 7362 case Stmt::DeclRefExprClass: { 7363 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7364 7365 // If we leave the immediate function, the lifetime isn't about to end. 7366 if (DR->refersToEnclosingVariableOrCapture()) 7367 return nullptr; 7368 7369 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 7370 // If this is a reference variable, follow through to the expression that 7371 // it points to. 7372 if (V->hasLocalStorage() && 7373 V->getType()->isReferenceType() && V->hasInit()) { 7374 // Add the reference variable to the "trail". 7375 refVars.push_back(DR); 7376 return EvalAddr(V->getInit(), refVars, ParentDecl); 7377 } 7378 7379 return nullptr; 7380 } 7381 7382 case Stmt::UnaryOperatorClass: { 7383 // The only unary operator that make sense to handle here 7384 // is AddrOf. All others don't make sense as pointers. 7385 const UnaryOperator *U = cast<UnaryOperator>(E); 7386 7387 if (U->getOpcode() == UO_AddrOf) 7388 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 7389 return nullptr; 7390 } 7391 7392 case Stmt::BinaryOperatorClass: { 7393 // Handle pointer arithmetic. All other binary operators are not valid 7394 // in this context. 7395 const BinaryOperator *B = cast<BinaryOperator>(E); 7396 BinaryOperatorKind op = B->getOpcode(); 7397 7398 if (op != BO_Add && op != BO_Sub) 7399 return nullptr; 7400 7401 const Expr *Base = B->getLHS(); 7402 7403 // Determine which argument is the real pointer base. It could be 7404 // the RHS argument instead of the LHS. 7405 if (!Base->getType()->isPointerType()) 7406 Base = B->getRHS(); 7407 7408 assert(Base->getType()->isPointerType()); 7409 return EvalAddr(Base, refVars, ParentDecl); 7410 } 7411 7412 // For conditional operators we need to see if either the LHS or RHS are 7413 // valid DeclRefExpr*s. If one of them is valid, we return it. 7414 case Stmt::ConditionalOperatorClass: { 7415 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7416 7417 // Handle the GNU extension for missing LHS. 7418 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 7419 if (const Expr *LHSExpr = C->getLHS()) { 7420 // In C++, we can have a throw-expression, which has 'void' type. 7421 if (!LHSExpr->getType()->isVoidType()) 7422 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 7423 return LHS; 7424 } 7425 7426 // In C++, we can have a throw-expression, which has 'void' type. 7427 if (C->getRHS()->getType()->isVoidType()) 7428 return nullptr; 7429 7430 return EvalAddr(C->getRHS(), refVars, ParentDecl); 7431 } 7432 7433 case Stmt::BlockExprClass: 7434 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 7435 return E; // local block. 7436 return nullptr; 7437 7438 case Stmt::AddrLabelExprClass: 7439 return E; // address of label. 7440 7441 case Stmt::ExprWithCleanupsClass: 7442 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7443 ParentDecl); 7444 7445 // For casts, we need to handle conversions from arrays to 7446 // pointer values, and pointer-to-pointer conversions. 7447 case Stmt::ImplicitCastExprClass: 7448 case Stmt::CStyleCastExprClass: 7449 case Stmt::CXXFunctionalCastExprClass: 7450 case Stmt::ObjCBridgedCastExprClass: 7451 case Stmt::CXXStaticCastExprClass: 7452 case Stmt::CXXDynamicCastExprClass: 7453 case Stmt::CXXConstCastExprClass: 7454 case Stmt::CXXReinterpretCastExprClass: { 7455 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 7456 switch (cast<CastExpr>(E)->getCastKind()) { 7457 case CK_LValueToRValue: 7458 case CK_NoOp: 7459 case CK_BaseToDerived: 7460 case CK_DerivedToBase: 7461 case CK_UncheckedDerivedToBase: 7462 case CK_Dynamic: 7463 case CK_CPointerToObjCPointerCast: 7464 case CK_BlockPointerToObjCPointerCast: 7465 case CK_AnyPointerToBlockPointerCast: 7466 return EvalAddr(SubExpr, refVars, ParentDecl); 7467 7468 case CK_ArrayToPointerDecay: 7469 return EvalVal(SubExpr, refVars, ParentDecl); 7470 7471 case CK_BitCast: 7472 if (SubExpr->getType()->isAnyPointerType() || 7473 SubExpr->getType()->isBlockPointerType() || 7474 SubExpr->getType()->isObjCQualifiedIdType()) 7475 return EvalAddr(SubExpr, refVars, ParentDecl); 7476 else 7477 return nullptr; 7478 7479 default: 7480 return nullptr; 7481 } 7482 } 7483 7484 case Stmt::MaterializeTemporaryExprClass: 7485 if (const Expr *Result = 7486 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7487 refVars, ParentDecl)) 7488 return Result; 7489 return E; 7490 7491 // Everything else: we simply don't reason about them. 7492 default: 7493 return nullptr; 7494 } 7495 } 7496 7497 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 7498 /// See the comments for EvalAddr for more details. 7499 static const Expr *EvalVal(const Expr *E, 7500 SmallVectorImpl<const DeclRefExpr *> &refVars, 7501 const Decl *ParentDecl) { 7502 do { 7503 // We should only be called for evaluating non-pointer expressions, or 7504 // expressions with a pointer type that are not used as references but 7505 // instead 7506 // are l-values (e.g., DeclRefExpr with a pointer type). 7507 7508 // Our "symbolic interpreter" is just a dispatch off the currently 7509 // viewed AST node. We then recursively traverse the AST by calling 7510 // EvalAddr and EvalVal appropriately. 7511 7512 E = E->IgnoreParens(); 7513 switch (E->getStmtClass()) { 7514 case Stmt::ImplicitCastExprClass: { 7515 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 7516 if (IE->getValueKind() == VK_LValue) { 7517 E = IE->getSubExpr(); 7518 continue; 7519 } 7520 return nullptr; 7521 } 7522 7523 case Stmt::ExprWithCleanupsClass: 7524 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 7525 ParentDecl); 7526 7527 case Stmt::DeclRefExprClass: { 7528 // When we hit a DeclRefExpr we are looking at code that refers to a 7529 // variable's name. If it's not a reference variable we check if it has 7530 // local storage within the function, and if so, return the expression. 7531 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7532 7533 // If we leave the immediate function, the lifetime isn't about to end. 7534 if (DR->refersToEnclosingVariableOrCapture()) 7535 return nullptr; 7536 7537 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 7538 // Check if it refers to itself, e.g. "int& i = i;". 7539 if (V == ParentDecl) 7540 return DR; 7541 7542 if (V->hasLocalStorage()) { 7543 if (!V->getType()->isReferenceType()) 7544 return DR; 7545 7546 // Reference variable, follow through to the expression that 7547 // it points to. 7548 if (V->hasInit()) { 7549 // Add the reference variable to the "trail". 7550 refVars.push_back(DR); 7551 return EvalVal(V->getInit(), refVars, V); 7552 } 7553 } 7554 } 7555 7556 return nullptr; 7557 } 7558 7559 case Stmt::UnaryOperatorClass: { 7560 // The only unary operator that make sense to handle here 7561 // is Deref. All others don't resolve to a "name." This includes 7562 // handling all sorts of rvalues passed to a unary operator. 7563 const UnaryOperator *U = cast<UnaryOperator>(E); 7564 7565 if (U->getOpcode() == UO_Deref) 7566 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 7567 7568 return nullptr; 7569 } 7570 7571 case Stmt::ArraySubscriptExprClass: { 7572 // Array subscripts are potential references to data on the stack. We 7573 // retrieve the DeclRefExpr* for the array variable if it indeed 7574 // has local storage. 7575 const auto *ASE = cast<ArraySubscriptExpr>(E); 7576 if (ASE->isTypeDependent()) 7577 return nullptr; 7578 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 7579 } 7580 7581 case Stmt::OMPArraySectionExprClass: { 7582 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 7583 ParentDecl); 7584 } 7585 7586 case Stmt::ConditionalOperatorClass: { 7587 // For conditional operators we need to see if either the LHS or RHS are 7588 // non-NULL Expr's. If one is non-NULL, we return it. 7589 const ConditionalOperator *C = cast<ConditionalOperator>(E); 7590 7591 // Handle the GNU extension for missing LHS. 7592 if (const Expr *LHSExpr = C->getLHS()) { 7593 // In C++, we can have a throw-expression, which has 'void' type. 7594 if (!LHSExpr->getType()->isVoidType()) 7595 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 7596 return LHS; 7597 } 7598 7599 // In C++, we can have a throw-expression, which has 'void' type. 7600 if (C->getRHS()->getType()->isVoidType()) 7601 return nullptr; 7602 7603 return EvalVal(C->getRHS(), refVars, ParentDecl); 7604 } 7605 7606 // Accesses to members are potential references to data on the stack. 7607 case Stmt::MemberExprClass: { 7608 const MemberExpr *M = cast<MemberExpr>(E); 7609 7610 // Check for indirect access. We only want direct field accesses. 7611 if (M->isArrow()) 7612 return nullptr; 7613 7614 // Check whether the member type is itself a reference, in which case 7615 // we're not going to refer to the member, but to what the member refers 7616 // to. 7617 if (M->getMemberDecl()->getType()->isReferenceType()) 7618 return nullptr; 7619 7620 return EvalVal(M->getBase(), refVars, ParentDecl); 7621 } 7622 7623 case Stmt::MaterializeTemporaryExprClass: 7624 if (const Expr *Result = 7625 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 7626 refVars, ParentDecl)) 7627 return Result; 7628 return E; 7629 7630 default: 7631 // Check that we don't return or take the address of a reference to a 7632 // temporary. This is only useful in C++. 7633 if (!E->isTypeDependent() && E->isRValue()) 7634 return E; 7635 7636 // Everything else: we simply don't reason about them. 7637 return nullptr; 7638 } 7639 } while (true); 7640 } 7641 7642 void 7643 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 7644 SourceLocation ReturnLoc, 7645 bool isObjCMethod, 7646 const AttrVec *Attrs, 7647 const FunctionDecl *FD) { 7648 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 7649 7650 // Check if the return value is null but should not be. 7651 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 7652 (!isObjCMethod && isNonNullType(Context, lhsType))) && 7653 CheckNonNullExpr(*this, RetValExp)) 7654 Diag(ReturnLoc, diag::warn_null_ret) 7655 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 7656 7657 // C++11 [basic.stc.dynamic.allocation]p4: 7658 // If an allocation function declared with a non-throwing 7659 // exception-specification fails to allocate storage, it shall return 7660 // a null pointer. Any other allocation function that fails to allocate 7661 // storage shall indicate failure only by throwing an exception [...] 7662 if (FD) { 7663 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 7664 if (Op == OO_New || Op == OO_Array_New) { 7665 const FunctionProtoType *Proto 7666 = FD->getType()->castAs<FunctionProtoType>(); 7667 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 7668 CheckNonNullExpr(*this, RetValExp)) 7669 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 7670 << FD << getLangOpts().CPlusPlus11; 7671 } 7672 } 7673 } 7674 7675 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 7676 7677 /// Check for comparisons of floating point operands using != and ==. 7678 /// Issue a warning if these are no self-comparisons, as they are not likely 7679 /// to do what the programmer intended. 7680 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 7681 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 7682 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 7683 7684 // Special case: check for x == x (which is OK). 7685 // Do not emit warnings for such cases. 7686 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 7687 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 7688 if (DRL->getDecl() == DRR->getDecl()) 7689 return; 7690 7691 // Special case: check for comparisons against literals that can be exactly 7692 // represented by APFloat. In such cases, do not emit a warning. This 7693 // is a heuristic: often comparison against such literals are used to 7694 // detect if a value in a variable has not changed. This clearly can 7695 // lead to false negatives. 7696 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 7697 if (FLL->isExact()) 7698 return; 7699 } else 7700 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 7701 if (FLR->isExact()) 7702 return; 7703 7704 // Check for comparisons with builtin types. 7705 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 7706 if (CL->getBuiltinCallee()) 7707 return; 7708 7709 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 7710 if (CR->getBuiltinCallee()) 7711 return; 7712 7713 // Emit the diagnostic. 7714 Diag(Loc, diag::warn_floatingpoint_eq) 7715 << LHS->getSourceRange() << RHS->getSourceRange(); 7716 } 7717 7718 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 7719 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 7720 7721 namespace { 7722 7723 /// Structure recording the 'active' range of an integer-valued 7724 /// expression. 7725 struct IntRange { 7726 /// The number of bits active in the int. 7727 unsigned Width; 7728 7729 /// True if the int is known not to have negative values. 7730 bool NonNegative; 7731 7732 IntRange(unsigned Width, bool NonNegative) 7733 : Width(Width), NonNegative(NonNegative) 7734 {} 7735 7736 /// Returns the range of the bool type. 7737 static IntRange forBoolType() { 7738 return IntRange(1, true); 7739 } 7740 7741 /// Returns the range of an opaque value of the given integral type. 7742 static IntRange forValueOfType(ASTContext &C, QualType T) { 7743 return forValueOfCanonicalType(C, 7744 T->getCanonicalTypeInternal().getTypePtr()); 7745 } 7746 7747 /// Returns the range of an opaque value of a canonical integral type. 7748 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 7749 assert(T->isCanonicalUnqualified()); 7750 7751 if (const VectorType *VT = dyn_cast<VectorType>(T)) 7752 T = VT->getElementType().getTypePtr(); 7753 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 7754 T = CT->getElementType().getTypePtr(); 7755 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 7756 T = AT->getValueType().getTypePtr(); 7757 7758 // For enum types, use the known bit width of the enumerators. 7759 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 7760 EnumDecl *Enum = ET->getDecl(); 7761 if (!Enum->isCompleteDefinition()) 7762 return IntRange(C.getIntWidth(QualType(T, 0)), false); 7763 7764 unsigned NumPositive = Enum->getNumPositiveBits(); 7765 unsigned NumNegative = Enum->getNumNegativeBits(); 7766 7767 if (NumNegative == 0) 7768 return IntRange(NumPositive, true/*NonNegative*/); 7769 else 7770 return IntRange(std::max(NumPositive + 1, NumNegative), 7771 false/*NonNegative*/); 7772 } 7773 7774 const BuiltinType *BT = cast<BuiltinType>(T); 7775 assert(BT->isInteger()); 7776 7777 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 7778 } 7779 7780 /// Returns the "target" range of a canonical integral type, i.e. 7781 /// the range of values expressible in the type. 7782 /// 7783 /// This matches forValueOfCanonicalType except that enums have the 7784 /// full range of their type, not the range of their enumerators. 7785 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 7786 assert(T->isCanonicalUnqualified()); 7787 7788 if (const VectorType *VT = dyn_cast<VectorType>(T)) 7789 T = VT->getElementType().getTypePtr(); 7790 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 7791 T = CT->getElementType().getTypePtr(); 7792 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 7793 T = AT->getValueType().getTypePtr(); 7794 if (const EnumType *ET = dyn_cast<EnumType>(T)) 7795 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 7796 7797 const BuiltinType *BT = cast<BuiltinType>(T); 7798 assert(BT->isInteger()); 7799 7800 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 7801 } 7802 7803 /// Returns the supremum of two ranges: i.e. their conservative merge. 7804 static IntRange join(IntRange L, IntRange R) { 7805 return IntRange(std::max(L.Width, R.Width), 7806 L.NonNegative && R.NonNegative); 7807 } 7808 7809 /// Returns the infinum of two ranges: i.e. their aggressive merge. 7810 static IntRange meet(IntRange L, IntRange R) { 7811 return IntRange(std::min(L.Width, R.Width), 7812 L.NonNegative || R.NonNegative); 7813 } 7814 }; 7815 7816 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 7817 if (value.isSigned() && value.isNegative()) 7818 return IntRange(value.getMinSignedBits(), false); 7819 7820 if (value.getBitWidth() > MaxWidth) 7821 value = value.trunc(MaxWidth); 7822 7823 // isNonNegative() just checks the sign bit without considering 7824 // signedness. 7825 return IntRange(value.getActiveBits(), true); 7826 } 7827 7828 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 7829 unsigned MaxWidth) { 7830 if (result.isInt()) 7831 return GetValueRange(C, result.getInt(), MaxWidth); 7832 7833 if (result.isVector()) { 7834 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 7835 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 7836 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 7837 R = IntRange::join(R, El); 7838 } 7839 return R; 7840 } 7841 7842 if (result.isComplexInt()) { 7843 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 7844 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 7845 return IntRange::join(R, I); 7846 } 7847 7848 // This can happen with lossless casts to intptr_t of "based" lvalues. 7849 // Assume it might use arbitrary bits. 7850 // FIXME: The only reason we need to pass the type in here is to get 7851 // the sign right on this one case. It would be nice if APValue 7852 // preserved this. 7853 assert(result.isLValue() || result.isAddrLabelDiff()); 7854 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 7855 } 7856 7857 QualType GetExprType(const Expr *E) { 7858 QualType Ty = E->getType(); 7859 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 7860 Ty = AtomicRHS->getValueType(); 7861 return Ty; 7862 } 7863 7864 /// Pseudo-evaluate the given integer expression, estimating the 7865 /// range of values it might take. 7866 /// 7867 /// \param MaxWidth - the width to which the value will be truncated 7868 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 7869 E = E->IgnoreParens(); 7870 7871 // Try a full evaluation first. 7872 Expr::EvalResult result; 7873 if (E->EvaluateAsRValue(result, C)) 7874 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 7875 7876 // I think we only want to look through implicit casts here; if the 7877 // user has an explicit widening cast, we should treat the value as 7878 // being of the new, wider type. 7879 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 7880 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 7881 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 7882 7883 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 7884 7885 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 7886 CE->getCastKind() == CK_BooleanToSignedIntegral; 7887 7888 // Assume that non-integer casts can span the full range of the type. 7889 if (!isIntegerCast) 7890 return OutputTypeRange; 7891 7892 IntRange SubRange 7893 = GetExprRange(C, CE->getSubExpr(), 7894 std::min(MaxWidth, OutputTypeRange.Width)); 7895 7896 // Bail out if the subexpr's range is as wide as the cast type. 7897 if (SubRange.Width >= OutputTypeRange.Width) 7898 return OutputTypeRange; 7899 7900 // Otherwise, we take the smaller width, and we're non-negative if 7901 // either the output type or the subexpr is. 7902 return IntRange(SubRange.Width, 7903 SubRange.NonNegative || OutputTypeRange.NonNegative); 7904 } 7905 7906 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 7907 // If we can fold the condition, just take that operand. 7908 bool CondResult; 7909 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 7910 return GetExprRange(C, CondResult ? CO->getTrueExpr() 7911 : CO->getFalseExpr(), 7912 MaxWidth); 7913 7914 // Otherwise, conservatively merge. 7915 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 7916 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 7917 return IntRange::join(L, R); 7918 } 7919 7920 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 7921 switch (BO->getOpcode()) { 7922 7923 // Boolean-valued operations are single-bit and positive. 7924 case BO_LAnd: 7925 case BO_LOr: 7926 case BO_LT: 7927 case BO_GT: 7928 case BO_LE: 7929 case BO_GE: 7930 case BO_EQ: 7931 case BO_NE: 7932 return IntRange::forBoolType(); 7933 7934 // The type of the assignments is the type of the LHS, so the RHS 7935 // is not necessarily the same type. 7936 case BO_MulAssign: 7937 case BO_DivAssign: 7938 case BO_RemAssign: 7939 case BO_AddAssign: 7940 case BO_SubAssign: 7941 case BO_XorAssign: 7942 case BO_OrAssign: 7943 // TODO: bitfields? 7944 return IntRange::forValueOfType(C, GetExprType(E)); 7945 7946 // Simple assignments just pass through the RHS, which will have 7947 // been coerced to the LHS type. 7948 case BO_Assign: 7949 // TODO: bitfields? 7950 return GetExprRange(C, BO->getRHS(), MaxWidth); 7951 7952 // Operations with opaque sources are black-listed. 7953 case BO_PtrMemD: 7954 case BO_PtrMemI: 7955 return IntRange::forValueOfType(C, GetExprType(E)); 7956 7957 // Bitwise-and uses the *infinum* of the two source ranges. 7958 case BO_And: 7959 case BO_AndAssign: 7960 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 7961 GetExprRange(C, BO->getRHS(), MaxWidth)); 7962 7963 // Left shift gets black-listed based on a judgement call. 7964 case BO_Shl: 7965 // ...except that we want to treat '1 << (blah)' as logically 7966 // positive. It's an important idiom. 7967 if (IntegerLiteral *I 7968 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 7969 if (I->getValue() == 1) { 7970 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 7971 return IntRange(R.Width, /*NonNegative*/ true); 7972 } 7973 } 7974 // fallthrough 7975 7976 case BO_ShlAssign: 7977 return IntRange::forValueOfType(C, GetExprType(E)); 7978 7979 // Right shift by a constant can narrow its left argument. 7980 case BO_Shr: 7981 case BO_ShrAssign: { 7982 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 7983 7984 // If the shift amount is a positive constant, drop the width by 7985 // that much. 7986 llvm::APSInt shift; 7987 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 7988 shift.isNonNegative()) { 7989 unsigned zext = shift.getZExtValue(); 7990 if (zext >= L.Width) 7991 L.Width = (L.NonNegative ? 0 : 1); 7992 else 7993 L.Width -= zext; 7994 } 7995 7996 return L; 7997 } 7998 7999 // Comma acts as its right operand. 8000 case BO_Comma: 8001 return GetExprRange(C, BO->getRHS(), MaxWidth); 8002 8003 // Black-list pointer subtractions. 8004 case BO_Sub: 8005 if (BO->getLHS()->getType()->isPointerType()) 8006 return IntRange::forValueOfType(C, GetExprType(E)); 8007 break; 8008 8009 // The width of a division result is mostly determined by the size 8010 // of the LHS. 8011 case BO_Div: { 8012 // Don't 'pre-truncate' the operands. 8013 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8014 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8015 8016 // If the divisor is constant, use that. 8017 llvm::APSInt divisor; 8018 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 8019 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 8020 if (log2 >= L.Width) 8021 L.Width = (L.NonNegative ? 0 : 1); 8022 else 8023 L.Width = std::min(L.Width - log2, MaxWidth); 8024 return L; 8025 } 8026 8027 // Otherwise, just use the LHS's width. 8028 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8029 return IntRange(L.Width, L.NonNegative && R.NonNegative); 8030 } 8031 8032 // The result of a remainder can't be larger than the result of 8033 // either side. 8034 case BO_Rem: { 8035 // Don't 'pre-truncate' the operands. 8036 unsigned opWidth = C.getIntWidth(GetExprType(E)); 8037 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 8038 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 8039 8040 IntRange meet = IntRange::meet(L, R); 8041 meet.Width = std::min(meet.Width, MaxWidth); 8042 return meet; 8043 } 8044 8045 // The default behavior is okay for these. 8046 case BO_Mul: 8047 case BO_Add: 8048 case BO_Xor: 8049 case BO_Or: 8050 break; 8051 } 8052 8053 // The default case is to treat the operation as if it were closed 8054 // on the narrowest type that encompasses both operands. 8055 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 8056 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 8057 return IntRange::join(L, R); 8058 } 8059 8060 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 8061 switch (UO->getOpcode()) { 8062 // Boolean-valued operations are white-listed. 8063 case UO_LNot: 8064 return IntRange::forBoolType(); 8065 8066 // Operations with opaque sources are black-listed. 8067 case UO_Deref: 8068 case UO_AddrOf: // should be impossible 8069 return IntRange::forValueOfType(C, GetExprType(E)); 8070 8071 default: 8072 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 8073 } 8074 } 8075 8076 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 8077 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 8078 8079 if (const auto *BitField = E->getSourceBitField()) 8080 return IntRange(BitField->getBitWidthValue(C), 8081 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 8082 8083 return IntRange::forValueOfType(C, GetExprType(E)); 8084 } 8085 8086 IntRange GetExprRange(ASTContext &C, const Expr *E) { 8087 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 8088 } 8089 8090 /// Checks whether the given value, which currently has the given 8091 /// source semantics, has the same value when coerced through the 8092 /// target semantics. 8093 bool IsSameFloatAfterCast(const llvm::APFloat &value, 8094 const llvm::fltSemantics &Src, 8095 const llvm::fltSemantics &Tgt) { 8096 llvm::APFloat truncated = value; 8097 8098 bool ignored; 8099 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 8100 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 8101 8102 return truncated.bitwiseIsEqual(value); 8103 } 8104 8105 /// Checks whether the given value, which currently has the given 8106 /// source semantics, has the same value when coerced through the 8107 /// target semantics. 8108 /// 8109 /// The value might be a vector of floats (or a complex number). 8110 bool IsSameFloatAfterCast(const APValue &value, 8111 const llvm::fltSemantics &Src, 8112 const llvm::fltSemantics &Tgt) { 8113 if (value.isFloat()) 8114 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 8115 8116 if (value.isVector()) { 8117 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 8118 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 8119 return false; 8120 return true; 8121 } 8122 8123 assert(value.isComplexFloat()); 8124 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 8125 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 8126 } 8127 8128 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 8129 8130 bool IsZero(Sema &S, Expr *E) { 8131 // Suppress cases where we are comparing against an enum constant. 8132 if (const DeclRefExpr *DR = 8133 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 8134 if (isa<EnumConstantDecl>(DR->getDecl())) 8135 return false; 8136 8137 // Suppress cases where the '0' value is expanded from a macro. 8138 if (E->getLocStart().isMacroID()) 8139 return false; 8140 8141 llvm::APSInt Value; 8142 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 8143 } 8144 8145 bool HasEnumType(Expr *E) { 8146 // Strip off implicit integral promotions. 8147 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8148 if (ICE->getCastKind() != CK_IntegralCast && 8149 ICE->getCastKind() != CK_NoOp) 8150 break; 8151 E = ICE->getSubExpr(); 8152 } 8153 8154 return E->getType()->isEnumeralType(); 8155 } 8156 8157 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 8158 // Disable warning in template instantiations. 8159 if (!S.ActiveTemplateInstantiations.empty()) 8160 return; 8161 8162 BinaryOperatorKind op = E->getOpcode(); 8163 if (E->isValueDependent()) 8164 return; 8165 8166 if (op == BO_LT && IsZero(S, E->getRHS())) { 8167 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8168 << "< 0" << "false" << HasEnumType(E->getLHS()) 8169 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8170 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 8171 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 8172 << ">= 0" << "true" << HasEnumType(E->getLHS()) 8173 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8174 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 8175 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8176 << "0 >" << "false" << HasEnumType(E->getRHS()) 8177 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8178 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 8179 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 8180 << "0 <=" << "true" << HasEnumType(E->getRHS()) 8181 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 8182 } 8183 } 8184 8185 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant, 8186 Expr *Other, const llvm::APSInt &Value, 8187 bool RhsConstant) { 8188 // Disable warning in template instantiations. 8189 if (!S.ActiveTemplateInstantiations.empty()) 8190 return; 8191 8192 // TODO: Investigate using GetExprRange() to get tighter bounds 8193 // on the bit ranges. 8194 QualType OtherT = Other->getType(); 8195 if (const auto *AT = OtherT->getAs<AtomicType>()) 8196 OtherT = AT->getValueType(); 8197 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 8198 unsigned OtherWidth = OtherRange.Width; 8199 8200 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 8201 8202 // 0 values are handled later by CheckTrivialUnsignedComparison(). 8203 if ((Value == 0) && (!OtherIsBooleanType)) 8204 return; 8205 8206 BinaryOperatorKind op = E->getOpcode(); 8207 bool IsTrue = true; 8208 8209 // Used for diagnostic printout. 8210 enum { 8211 LiteralConstant = 0, 8212 CXXBoolLiteralTrue, 8213 CXXBoolLiteralFalse 8214 } LiteralOrBoolConstant = LiteralConstant; 8215 8216 if (!OtherIsBooleanType) { 8217 QualType ConstantT = Constant->getType(); 8218 QualType CommonT = E->getLHS()->getType(); 8219 8220 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 8221 return; 8222 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 8223 "comparison with non-integer type"); 8224 8225 bool ConstantSigned = ConstantT->isSignedIntegerType(); 8226 bool CommonSigned = CommonT->isSignedIntegerType(); 8227 8228 bool EqualityOnly = false; 8229 8230 if (CommonSigned) { 8231 // The common type is signed, therefore no signed to unsigned conversion. 8232 if (!OtherRange.NonNegative) { 8233 // Check that the constant is representable in type OtherT. 8234 if (ConstantSigned) { 8235 if (OtherWidth >= Value.getMinSignedBits()) 8236 return; 8237 } else { // !ConstantSigned 8238 if (OtherWidth >= Value.getActiveBits() + 1) 8239 return; 8240 } 8241 } else { // !OtherSigned 8242 // Check that the constant is representable in type OtherT. 8243 // Negative values are out of range. 8244 if (ConstantSigned) { 8245 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 8246 return; 8247 } else { // !ConstantSigned 8248 if (OtherWidth >= Value.getActiveBits()) 8249 return; 8250 } 8251 } 8252 } else { // !CommonSigned 8253 if (OtherRange.NonNegative) { 8254 if (OtherWidth >= Value.getActiveBits()) 8255 return; 8256 } else { // OtherSigned 8257 assert(!ConstantSigned && 8258 "Two signed types converted to unsigned types."); 8259 // Check to see if the constant is representable in OtherT. 8260 if (OtherWidth > Value.getActiveBits()) 8261 return; 8262 // Check to see if the constant is equivalent to a negative value 8263 // cast to CommonT. 8264 if (S.Context.getIntWidth(ConstantT) == 8265 S.Context.getIntWidth(CommonT) && 8266 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 8267 return; 8268 // The constant value rests between values that OtherT can represent 8269 // after conversion. Relational comparison still works, but equality 8270 // comparisons will be tautological. 8271 EqualityOnly = true; 8272 } 8273 } 8274 8275 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 8276 8277 if (op == BO_EQ || op == BO_NE) { 8278 IsTrue = op == BO_NE; 8279 } else if (EqualityOnly) { 8280 return; 8281 } else if (RhsConstant) { 8282 if (op == BO_GT || op == BO_GE) 8283 IsTrue = !PositiveConstant; 8284 else // op == BO_LT || op == BO_LE 8285 IsTrue = PositiveConstant; 8286 } else { 8287 if (op == BO_LT || op == BO_LE) 8288 IsTrue = !PositiveConstant; 8289 else // op == BO_GT || op == BO_GE 8290 IsTrue = PositiveConstant; 8291 } 8292 } else { 8293 // Other isKnownToHaveBooleanValue 8294 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 8295 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 8296 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 8297 8298 static const struct LinkedConditions { 8299 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 8300 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 8301 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 8302 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 8303 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 8304 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 8305 8306 } TruthTable = { 8307 // Constant on LHS. | Constant on RHS. | 8308 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 8309 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 8310 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 8311 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 8312 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 8313 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 8314 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 8315 }; 8316 8317 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 8318 8319 enum ConstantValue ConstVal = Zero; 8320 if (Value.isUnsigned() || Value.isNonNegative()) { 8321 if (Value == 0) { 8322 LiteralOrBoolConstant = 8323 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 8324 ConstVal = Zero; 8325 } else if (Value == 1) { 8326 LiteralOrBoolConstant = 8327 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 8328 ConstVal = One; 8329 } else { 8330 LiteralOrBoolConstant = LiteralConstant; 8331 ConstVal = GT_One; 8332 } 8333 } else { 8334 ConstVal = LT_Zero; 8335 } 8336 8337 CompareBoolWithConstantResult CmpRes; 8338 8339 switch (op) { 8340 case BO_LT: 8341 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 8342 break; 8343 case BO_GT: 8344 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 8345 break; 8346 case BO_LE: 8347 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 8348 break; 8349 case BO_GE: 8350 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 8351 break; 8352 case BO_EQ: 8353 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 8354 break; 8355 case BO_NE: 8356 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 8357 break; 8358 default: 8359 CmpRes = Unkwn; 8360 break; 8361 } 8362 8363 if (CmpRes == AFals) { 8364 IsTrue = false; 8365 } else if (CmpRes == ATrue) { 8366 IsTrue = true; 8367 } else { 8368 return; 8369 } 8370 } 8371 8372 // If this is a comparison to an enum constant, include that 8373 // constant in the diagnostic. 8374 const EnumConstantDecl *ED = nullptr; 8375 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 8376 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 8377 8378 SmallString<64> PrettySourceValue; 8379 llvm::raw_svector_ostream OS(PrettySourceValue); 8380 if (ED) 8381 OS << '\'' << *ED << "' (" << Value << ")"; 8382 else 8383 OS << Value; 8384 8385 S.DiagRuntimeBehavior( 8386 E->getOperatorLoc(), E, 8387 S.PDiag(diag::warn_out_of_range_compare) 8388 << OS.str() << LiteralOrBoolConstant 8389 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 8390 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 8391 } 8392 8393 /// Analyze the operands of the given comparison. Implements the 8394 /// fallback case from AnalyzeComparison. 8395 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 8396 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8397 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8398 } 8399 8400 /// \brief Implements -Wsign-compare. 8401 /// 8402 /// \param E the binary operator to check for warnings 8403 void AnalyzeComparison(Sema &S, BinaryOperator *E) { 8404 // The type the comparison is being performed in. 8405 QualType T = E->getLHS()->getType(); 8406 8407 // Only analyze comparison operators where both sides have been converted to 8408 // the same type. 8409 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 8410 return AnalyzeImpConvsInComparison(S, E); 8411 8412 // Don't analyze value-dependent comparisons directly. 8413 if (E->isValueDependent()) 8414 return AnalyzeImpConvsInComparison(S, E); 8415 8416 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 8417 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 8418 8419 bool IsComparisonConstant = false; 8420 8421 // Check whether an integer constant comparison results in a value 8422 // of 'true' or 'false'. 8423 if (T->isIntegralType(S.Context)) { 8424 llvm::APSInt RHSValue; 8425 bool IsRHSIntegralLiteral = 8426 RHS->isIntegerConstantExpr(RHSValue, S.Context); 8427 llvm::APSInt LHSValue; 8428 bool IsLHSIntegralLiteral = 8429 LHS->isIntegerConstantExpr(LHSValue, S.Context); 8430 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 8431 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 8432 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 8433 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 8434 else 8435 IsComparisonConstant = 8436 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 8437 } else if (!T->hasUnsignedIntegerRepresentation()) 8438 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 8439 8440 // We don't do anything special if this isn't an unsigned integral 8441 // comparison: we're only interested in integral comparisons, and 8442 // signed comparisons only happen in cases we don't care to warn about. 8443 // 8444 // We also don't care about value-dependent expressions or expressions 8445 // whose result is a constant. 8446 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 8447 return AnalyzeImpConvsInComparison(S, E); 8448 8449 // Check to see if one of the (unmodified) operands is of different 8450 // signedness. 8451 Expr *signedOperand, *unsignedOperand; 8452 if (LHS->getType()->hasSignedIntegerRepresentation()) { 8453 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 8454 "unsigned comparison between two signed integer expressions?"); 8455 signedOperand = LHS; 8456 unsignedOperand = RHS; 8457 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 8458 signedOperand = RHS; 8459 unsignedOperand = LHS; 8460 } else { 8461 CheckTrivialUnsignedComparison(S, E); 8462 return AnalyzeImpConvsInComparison(S, E); 8463 } 8464 8465 // Otherwise, calculate the effective range of the signed operand. 8466 IntRange signedRange = GetExprRange(S.Context, signedOperand); 8467 8468 // Go ahead and analyze implicit conversions in the operands. Note 8469 // that we skip the implicit conversions on both sides. 8470 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 8471 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 8472 8473 // If the signed range is non-negative, -Wsign-compare won't fire, 8474 // but we should still check for comparisons which are always true 8475 // or false. 8476 if (signedRange.NonNegative) 8477 return CheckTrivialUnsignedComparison(S, E); 8478 8479 // For (in)equality comparisons, if the unsigned operand is a 8480 // constant which cannot collide with a overflowed signed operand, 8481 // then reinterpreting the signed operand as unsigned will not 8482 // change the result of the comparison. 8483 if (E->isEqualityOp()) { 8484 unsigned comparisonWidth = S.Context.getIntWidth(T); 8485 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 8486 8487 // We should never be unable to prove that the unsigned operand is 8488 // non-negative. 8489 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 8490 8491 if (unsignedRange.Width < comparisonWidth) 8492 return; 8493 } 8494 8495 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 8496 S.PDiag(diag::warn_mixed_sign_comparison) 8497 << LHS->getType() << RHS->getType() 8498 << LHS->getSourceRange() << RHS->getSourceRange()); 8499 } 8500 8501 /// Analyzes an attempt to assign the given value to a bitfield. 8502 /// 8503 /// Returns true if there was something fishy about the attempt. 8504 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 8505 SourceLocation InitLoc) { 8506 assert(Bitfield->isBitField()); 8507 if (Bitfield->isInvalidDecl()) 8508 return false; 8509 8510 // White-list bool bitfields. 8511 if (Bitfield->getType()->isBooleanType()) 8512 return false; 8513 8514 // Ignore value- or type-dependent expressions. 8515 if (Bitfield->getBitWidth()->isValueDependent() || 8516 Bitfield->getBitWidth()->isTypeDependent() || 8517 Init->isValueDependent() || 8518 Init->isTypeDependent()) 8519 return false; 8520 8521 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 8522 8523 llvm::APSInt Value; 8524 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 8525 return false; 8526 8527 unsigned OriginalWidth = Value.getBitWidth(); 8528 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 8529 8530 if (!Value.isSigned() || Value.isNegative()) 8531 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 8532 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 8533 OriginalWidth = Value.getMinSignedBits(); 8534 8535 if (OriginalWidth <= FieldWidth) 8536 return false; 8537 8538 // Compute the value which the bitfield will contain. 8539 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 8540 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType()); 8541 8542 // Check whether the stored value is equal to the original value. 8543 TruncatedValue = TruncatedValue.extend(OriginalWidth); 8544 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 8545 return false; 8546 8547 // Special-case bitfields of width 1: booleans are naturally 0/1, and 8548 // therefore don't strictly fit into a signed bitfield of width 1. 8549 if (FieldWidth == 1 && Value == 1) 8550 return false; 8551 8552 std::string PrettyValue = Value.toString(10); 8553 std::string PrettyTrunc = TruncatedValue.toString(10); 8554 8555 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 8556 << PrettyValue << PrettyTrunc << OriginalInit->getType() 8557 << Init->getSourceRange(); 8558 8559 return true; 8560 } 8561 8562 /// Analyze the given simple or compound assignment for warning-worthy 8563 /// operations. 8564 void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 8565 // Just recurse on the LHS. 8566 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 8567 8568 // We want to recurse on the RHS as normal unless we're assigning to 8569 // a bitfield. 8570 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 8571 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 8572 E->getOperatorLoc())) { 8573 // Recurse, ignoring any implicit conversions on the RHS. 8574 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 8575 E->getOperatorLoc()); 8576 } 8577 } 8578 8579 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 8580 } 8581 8582 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 8583 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 8584 SourceLocation CContext, unsigned diag, 8585 bool pruneControlFlow = false) { 8586 if (pruneControlFlow) { 8587 S.DiagRuntimeBehavior(E->getExprLoc(), E, 8588 S.PDiag(diag) 8589 << SourceType << T << E->getSourceRange() 8590 << SourceRange(CContext)); 8591 return; 8592 } 8593 S.Diag(E->getExprLoc(), diag) 8594 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 8595 } 8596 8597 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 8598 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 8599 unsigned diag, bool pruneControlFlow = false) { 8600 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 8601 } 8602 8603 8604 /// Diagnose an implicit cast from a floating point value to an integer value. 8605 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 8606 8607 SourceLocation CContext) { 8608 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 8609 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty(); 8610 8611 Expr *InnerE = E->IgnoreParenImpCasts(); 8612 // We also want to warn on, e.g., "int i = -1.234" 8613 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 8614 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 8615 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 8616 8617 const bool IsLiteral = 8618 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 8619 8620 llvm::APFloat Value(0.0); 8621 bool IsConstant = 8622 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 8623 if (!IsConstant) { 8624 return DiagnoseImpCast(S, E, T, CContext, 8625 diag::warn_impcast_float_integer, PruneWarnings); 8626 } 8627 8628 bool isExact = false; 8629 8630 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 8631 T->hasUnsignedIntegerRepresentation()); 8632 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 8633 &isExact) == llvm::APFloat::opOK && 8634 isExact) { 8635 if (IsLiteral) return; 8636 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 8637 PruneWarnings); 8638 } 8639 8640 unsigned DiagID = 0; 8641 if (IsLiteral) { 8642 // Warn on floating point literal to integer. 8643 DiagID = diag::warn_impcast_literal_float_to_integer; 8644 } else if (IntegerValue == 0) { 8645 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 8646 return DiagnoseImpCast(S, E, T, CContext, 8647 diag::warn_impcast_float_integer, PruneWarnings); 8648 } 8649 // Warn on non-zero to zero conversion. 8650 DiagID = diag::warn_impcast_float_to_integer_zero; 8651 } else { 8652 if (IntegerValue.isUnsigned()) { 8653 if (!IntegerValue.isMaxValue()) { 8654 return DiagnoseImpCast(S, E, T, CContext, 8655 diag::warn_impcast_float_integer, PruneWarnings); 8656 } 8657 } else { // IntegerValue.isSigned() 8658 if (!IntegerValue.isMaxSignedValue() && 8659 !IntegerValue.isMinSignedValue()) { 8660 return DiagnoseImpCast(S, E, T, CContext, 8661 diag::warn_impcast_float_integer, PruneWarnings); 8662 } 8663 } 8664 // Warn on evaluatable floating point expression to integer conversion. 8665 DiagID = diag::warn_impcast_float_to_integer; 8666 } 8667 8668 // FIXME: Force the precision of the source value down so we don't print 8669 // digits which are usually useless (we don't really care here if we 8670 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 8671 // would automatically print the shortest representation, but it's a bit 8672 // tricky to implement. 8673 SmallString<16> PrettySourceValue; 8674 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 8675 precision = (precision * 59 + 195) / 196; 8676 Value.toString(PrettySourceValue, precision); 8677 8678 SmallString<16> PrettyTargetValue; 8679 if (IsBool) 8680 PrettyTargetValue = Value.isZero() ? "false" : "true"; 8681 else 8682 IntegerValue.toString(PrettyTargetValue); 8683 8684 if (PruneWarnings) { 8685 S.DiagRuntimeBehavior(E->getExprLoc(), E, 8686 S.PDiag(DiagID) 8687 << E->getType() << T.getUnqualifiedType() 8688 << PrettySourceValue << PrettyTargetValue 8689 << E->getSourceRange() << SourceRange(CContext)); 8690 } else { 8691 S.Diag(E->getExprLoc(), DiagID) 8692 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 8693 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 8694 } 8695 } 8696 8697 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 8698 if (!Range.Width) return "0"; 8699 8700 llvm::APSInt ValueInRange = Value; 8701 ValueInRange.setIsSigned(!Range.NonNegative); 8702 ValueInRange = ValueInRange.trunc(Range.Width); 8703 return ValueInRange.toString(10); 8704 } 8705 8706 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 8707 if (!isa<ImplicitCastExpr>(Ex)) 8708 return false; 8709 8710 Expr *InnerE = Ex->IgnoreParenImpCasts(); 8711 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 8712 const Type *Source = 8713 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 8714 if (Target->isDependentType()) 8715 return false; 8716 8717 const BuiltinType *FloatCandidateBT = 8718 dyn_cast<BuiltinType>(ToBool ? Source : Target); 8719 const Type *BoolCandidateType = ToBool ? Target : Source; 8720 8721 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 8722 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 8723 } 8724 8725 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 8726 SourceLocation CC) { 8727 unsigned NumArgs = TheCall->getNumArgs(); 8728 for (unsigned i = 0; i < NumArgs; ++i) { 8729 Expr *CurrA = TheCall->getArg(i); 8730 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 8731 continue; 8732 8733 bool IsSwapped = ((i > 0) && 8734 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 8735 IsSwapped |= ((i < (NumArgs - 1)) && 8736 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 8737 if (IsSwapped) { 8738 // Warn on this floating-point to bool conversion. 8739 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 8740 CurrA->getType(), CC, 8741 diag::warn_impcast_floating_point_to_bool); 8742 } 8743 } 8744 } 8745 8746 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) { 8747 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 8748 E->getExprLoc())) 8749 return; 8750 8751 // Don't warn on functions which have return type nullptr_t. 8752 if (isa<CallExpr>(E)) 8753 return; 8754 8755 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 8756 const Expr::NullPointerConstantKind NullKind = 8757 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 8758 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 8759 return; 8760 8761 // Return if target type is a safe conversion. 8762 if (T->isAnyPointerType() || T->isBlockPointerType() || 8763 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 8764 return; 8765 8766 SourceLocation Loc = E->getSourceRange().getBegin(); 8767 8768 // Venture through the macro stacks to get to the source of macro arguments. 8769 // The new location is a better location than the complete location that was 8770 // passed in. 8771 while (S.SourceMgr.isMacroArgExpansion(Loc)) 8772 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); 8773 8774 while (S.SourceMgr.isMacroArgExpansion(CC)) 8775 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); 8776 8777 // __null is usually wrapped in a macro. Go up a macro if that is the case. 8778 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 8779 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 8780 Loc, S.SourceMgr, S.getLangOpts()); 8781 if (MacroName == "NULL") 8782 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 8783 } 8784 8785 // Only warn if the null and context location are in the same macro expansion. 8786 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 8787 return; 8788 8789 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 8790 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) 8791 << FixItHint::CreateReplacement(Loc, 8792 S.getFixItZeroLiteralForType(T, Loc)); 8793 } 8794 8795 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 8796 ObjCArrayLiteral *ArrayLiteral); 8797 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 8798 ObjCDictionaryLiteral *DictionaryLiteral); 8799 8800 /// Check a single element within a collection literal against the 8801 /// target element type. 8802 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, 8803 Expr *Element, unsigned ElementKind) { 8804 // Skip a bitcast to 'id' or qualified 'id'. 8805 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 8806 if (ICE->getCastKind() == CK_BitCast && 8807 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 8808 Element = ICE->getSubExpr(); 8809 } 8810 8811 QualType ElementType = Element->getType(); 8812 ExprResult ElementResult(Element); 8813 if (ElementType->getAs<ObjCObjectPointerType>() && 8814 S.CheckSingleAssignmentConstraints(TargetElementType, 8815 ElementResult, 8816 false, false) 8817 != Sema::Compatible) { 8818 S.Diag(Element->getLocStart(), 8819 diag::warn_objc_collection_literal_element) 8820 << ElementType << ElementKind << TargetElementType 8821 << Element->getSourceRange(); 8822 } 8823 8824 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 8825 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 8826 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 8827 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 8828 } 8829 8830 /// Check an Objective-C array literal being converted to the given 8831 /// target type. 8832 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 8833 ObjCArrayLiteral *ArrayLiteral) { 8834 if (!S.NSArrayDecl) 8835 return; 8836 8837 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 8838 if (!TargetObjCPtr) 8839 return; 8840 8841 if (TargetObjCPtr->isUnspecialized() || 8842 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 8843 != S.NSArrayDecl->getCanonicalDecl()) 8844 return; 8845 8846 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 8847 if (TypeArgs.size() != 1) 8848 return; 8849 8850 QualType TargetElementType = TypeArgs[0]; 8851 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 8852 checkObjCCollectionLiteralElement(S, TargetElementType, 8853 ArrayLiteral->getElement(I), 8854 0); 8855 } 8856 } 8857 8858 /// Check an Objective-C dictionary literal being converted to the given 8859 /// target type. 8860 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 8861 ObjCDictionaryLiteral *DictionaryLiteral) { 8862 if (!S.NSDictionaryDecl) 8863 return; 8864 8865 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 8866 if (!TargetObjCPtr) 8867 return; 8868 8869 if (TargetObjCPtr->isUnspecialized() || 8870 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 8871 != S.NSDictionaryDecl->getCanonicalDecl()) 8872 return; 8873 8874 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 8875 if (TypeArgs.size() != 2) 8876 return; 8877 8878 QualType TargetKeyType = TypeArgs[0]; 8879 QualType TargetObjectType = TypeArgs[1]; 8880 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 8881 auto Element = DictionaryLiteral->getKeyValueElement(I); 8882 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 8883 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 8884 } 8885 } 8886 8887 // Helper function to filter out cases for constant width constant conversion. 8888 // Don't warn on char array initialization or for non-decimal values. 8889 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 8890 SourceLocation CC) { 8891 // If initializing from a constant, and the constant starts with '0', 8892 // then it is a binary, octal, or hexadecimal. Allow these constants 8893 // to fill all the bits, even if there is a sign change. 8894 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 8895 const char FirstLiteralCharacter = 8896 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 8897 if (FirstLiteralCharacter == '0') 8898 return false; 8899 } 8900 8901 // If the CC location points to a '{', and the type is char, then assume 8902 // assume it is an array initialization. 8903 if (CC.isValid() && T->isCharType()) { 8904 const char FirstContextCharacter = 8905 S.getSourceManager().getCharacterData(CC)[0]; 8906 if (FirstContextCharacter == '{') 8907 return false; 8908 } 8909 8910 return true; 8911 } 8912 8913 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 8914 SourceLocation CC, bool *ICContext = nullptr) { 8915 if (E->isTypeDependent() || E->isValueDependent()) return; 8916 8917 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 8918 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 8919 if (Source == Target) return; 8920 if (Target->isDependentType()) return; 8921 8922 // If the conversion context location is invalid don't complain. We also 8923 // don't want to emit a warning if the issue occurs from the expansion of 8924 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 8925 // delay this check as long as possible. Once we detect we are in that 8926 // scenario, we just return. 8927 if (CC.isInvalid()) 8928 return; 8929 8930 // Diagnose implicit casts to bool. 8931 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 8932 if (isa<StringLiteral>(E)) 8933 // Warn on string literal to bool. Checks for string literals in logical 8934 // and expressions, for instance, assert(0 && "error here"), are 8935 // prevented by a check in AnalyzeImplicitConversions(). 8936 return DiagnoseImpCast(S, E, T, CC, 8937 diag::warn_impcast_string_literal_to_bool); 8938 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 8939 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 8940 // This covers the literal expressions that evaluate to Objective-C 8941 // objects. 8942 return DiagnoseImpCast(S, E, T, CC, 8943 diag::warn_impcast_objective_c_literal_to_bool); 8944 } 8945 if (Source->isPointerType() || Source->canDecayToPointerType()) { 8946 // Warn on pointer to bool conversion that is always true. 8947 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 8948 SourceRange(CC)); 8949 } 8950 } 8951 8952 // Check implicit casts from Objective-C collection literals to specialized 8953 // collection types, e.g., NSArray<NSString *> *. 8954 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 8955 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 8956 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 8957 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 8958 8959 // Strip vector types. 8960 if (isa<VectorType>(Source)) { 8961 if (!isa<VectorType>(Target)) { 8962 if (S.SourceMgr.isInSystemMacro(CC)) 8963 return; 8964 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 8965 } 8966 8967 // If the vector cast is cast between two vectors of the same size, it is 8968 // a bitcast, not a conversion. 8969 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 8970 return; 8971 8972 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 8973 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 8974 } 8975 if (auto VecTy = dyn_cast<VectorType>(Target)) 8976 Target = VecTy->getElementType().getTypePtr(); 8977 8978 // Strip complex types. 8979 if (isa<ComplexType>(Source)) { 8980 if (!isa<ComplexType>(Target)) { 8981 if (S.SourceMgr.isInSystemMacro(CC)) 8982 return; 8983 8984 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 8985 } 8986 8987 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 8988 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 8989 } 8990 8991 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 8992 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 8993 8994 // If the source is floating point... 8995 if (SourceBT && SourceBT->isFloatingPoint()) { 8996 // ...and the target is floating point... 8997 if (TargetBT && TargetBT->isFloatingPoint()) { 8998 // ...then warn if we're dropping FP rank. 8999 9000 // Builtin FP kinds are ordered by increasing FP rank. 9001 if (SourceBT->getKind() > TargetBT->getKind()) { 9002 // Don't warn about float constants that are precisely 9003 // representable in the target type. 9004 Expr::EvalResult result; 9005 if (E->EvaluateAsRValue(result, S.Context)) { 9006 // Value might be a float, a float vector, or a float complex. 9007 if (IsSameFloatAfterCast(result.Val, 9008 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 9009 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 9010 return; 9011 } 9012 9013 if (S.SourceMgr.isInSystemMacro(CC)) 9014 return; 9015 9016 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 9017 } 9018 // ... or possibly if we're increasing rank, too 9019 else if (TargetBT->getKind() > SourceBT->getKind()) { 9020 if (S.SourceMgr.isInSystemMacro(CC)) 9021 return; 9022 9023 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 9024 } 9025 return; 9026 } 9027 9028 // If the target is integral, always warn. 9029 if (TargetBT && TargetBT->isInteger()) { 9030 if (S.SourceMgr.isInSystemMacro(CC)) 9031 return; 9032 9033 DiagnoseFloatingImpCast(S, E, T, CC); 9034 } 9035 9036 // Detect the case where a call result is converted from floating-point to 9037 // to bool, and the final argument to the call is converted from bool, to 9038 // discover this typo: 9039 // 9040 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 9041 // 9042 // FIXME: This is an incredibly special case; is there some more general 9043 // way to detect this class of misplaced-parentheses bug? 9044 if (Target->isBooleanType() && isa<CallExpr>(E)) { 9045 // Check last argument of function call to see if it is an 9046 // implicit cast from a type matching the type the result 9047 // is being cast to. 9048 CallExpr *CEx = cast<CallExpr>(E); 9049 if (unsigned NumArgs = CEx->getNumArgs()) { 9050 Expr *LastA = CEx->getArg(NumArgs - 1); 9051 Expr *InnerE = LastA->IgnoreParenImpCasts(); 9052 if (isa<ImplicitCastExpr>(LastA) && 9053 InnerE->getType()->isBooleanType()) { 9054 // Warn on this floating-point to bool conversion 9055 DiagnoseImpCast(S, E, T, CC, 9056 diag::warn_impcast_floating_point_to_bool); 9057 } 9058 } 9059 } 9060 return; 9061 } 9062 9063 DiagnoseNullConversion(S, E, T, CC); 9064 9065 S.DiscardMisalignedMemberAddress(Target, E); 9066 9067 if (!Source->isIntegerType() || !Target->isIntegerType()) 9068 return; 9069 9070 // TODO: remove this early return once the false positives for constant->bool 9071 // in templates, macros, etc, are reduced or removed. 9072 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 9073 return; 9074 9075 IntRange SourceRange = GetExprRange(S.Context, E); 9076 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 9077 9078 if (SourceRange.Width > TargetRange.Width) { 9079 // If the source is a constant, use a default-on diagnostic. 9080 // TODO: this should happen for bitfield stores, too. 9081 llvm::APSInt Value(32); 9082 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 9083 if (S.SourceMgr.isInSystemMacro(CC)) 9084 return; 9085 9086 std::string PrettySourceValue = Value.toString(10); 9087 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9088 9089 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9090 S.PDiag(diag::warn_impcast_integer_precision_constant) 9091 << PrettySourceValue << PrettyTargetValue 9092 << E->getType() << T << E->getSourceRange() 9093 << clang::SourceRange(CC)); 9094 return; 9095 } 9096 9097 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 9098 if (S.SourceMgr.isInSystemMacro(CC)) 9099 return; 9100 9101 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 9102 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 9103 /* pruneControlFlow */ true); 9104 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 9105 } 9106 9107 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 9108 SourceRange.NonNegative && Source->isSignedIntegerType()) { 9109 // Warn when doing a signed to signed conversion, warn if the positive 9110 // source value is exactly the width of the target type, which will 9111 // cause a negative value to be stored. 9112 9113 llvm::APSInt Value; 9114 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 9115 !S.SourceMgr.isInSystemMacro(CC)) { 9116 if (isSameWidthConstantConversion(S, E, T, CC)) { 9117 std::string PrettySourceValue = Value.toString(10); 9118 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 9119 9120 S.DiagRuntimeBehavior( 9121 E->getExprLoc(), E, 9122 S.PDiag(diag::warn_impcast_integer_precision_constant) 9123 << PrettySourceValue << PrettyTargetValue << E->getType() << T 9124 << E->getSourceRange() << clang::SourceRange(CC)); 9125 return; 9126 } 9127 } 9128 9129 // Fall through for non-constants to give a sign conversion warning. 9130 } 9131 9132 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 9133 (!TargetRange.NonNegative && SourceRange.NonNegative && 9134 SourceRange.Width == TargetRange.Width)) { 9135 if (S.SourceMgr.isInSystemMacro(CC)) 9136 return; 9137 9138 unsigned DiagID = diag::warn_impcast_integer_sign; 9139 9140 // Traditionally, gcc has warned about this under -Wsign-compare. 9141 // We also want to warn about it in -Wconversion. 9142 // So if -Wconversion is off, use a completely identical diagnostic 9143 // in the sign-compare group. 9144 // The conditional-checking code will 9145 if (ICContext) { 9146 DiagID = diag::warn_impcast_integer_sign_conditional; 9147 *ICContext = true; 9148 } 9149 9150 return DiagnoseImpCast(S, E, T, CC, DiagID); 9151 } 9152 9153 // Diagnose conversions between different enumeration types. 9154 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 9155 // type, to give us better diagnostics. 9156 QualType SourceType = E->getType(); 9157 if (!S.getLangOpts().CPlusPlus) { 9158 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9159 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 9160 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 9161 SourceType = S.Context.getTypeDeclType(Enum); 9162 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 9163 } 9164 } 9165 9166 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 9167 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 9168 if (SourceEnum->getDecl()->hasNameForLinkage() && 9169 TargetEnum->getDecl()->hasNameForLinkage() && 9170 SourceEnum != TargetEnum) { 9171 if (S.SourceMgr.isInSystemMacro(CC)) 9172 return; 9173 9174 return DiagnoseImpCast(S, E, SourceType, T, CC, 9175 diag::warn_impcast_different_enum_types); 9176 } 9177 } 9178 9179 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9180 SourceLocation CC, QualType T); 9181 9182 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 9183 SourceLocation CC, bool &ICContext) { 9184 E = E->IgnoreParenImpCasts(); 9185 9186 if (isa<ConditionalOperator>(E)) 9187 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 9188 9189 AnalyzeImplicitConversions(S, E, CC); 9190 if (E->getType() != T) 9191 return CheckImplicitConversion(S, E, T, CC, &ICContext); 9192 } 9193 9194 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 9195 SourceLocation CC, QualType T) { 9196 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 9197 9198 bool Suspicious = false; 9199 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 9200 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 9201 9202 // If -Wconversion would have warned about either of the candidates 9203 // for a signedness conversion to the context type... 9204 if (!Suspicious) return; 9205 9206 // ...but it's currently ignored... 9207 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 9208 return; 9209 9210 // ...then check whether it would have warned about either of the 9211 // candidates for a signedness conversion to the condition type. 9212 if (E->getType() == T) return; 9213 9214 Suspicious = false; 9215 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 9216 E->getType(), CC, &Suspicious); 9217 if (!Suspicious) 9218 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 9219 E->getType(), CC, &Suspicious); 9220 } 9221 9222 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9223 /// Input argument E is a logical expression. 9224 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 9225 if (S.getLangOpts().Bool) 9226 return; 9227 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 9228 } 9229 9230 /// AnalyzeImplicitConversions - Find and report any interesting 9231 /// implicit conversions in the given expression. There are a couple 9232 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 9233 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 9234 QualType T = OrigE->getType(); 9235 Expr *E = OrigE->IgnoreParenImpCasts(); 9236 9237 if (E->isTypeDependent() || E->isValueDependent()) 9238 return; 9239 9240 // For conditional operators, we analyze the arguments as if they 9241 // were being fed directly into the output. 9242 if (isa<ConditionalOperator>(E)) { 9243 ConditionalOperator *CO = cast<ConditionalOperator>(E); 9244 CheckConditionalOperator(S, CO, CC, T); 9245 return; 9246 } 9247 9248 // Check implicit argument conversions for function calls. 9249 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 9250 CheckImplicitArgumentConversions(S, Call, CC); 9251 9252 // Go ahead and check any implicit conversions we might have skipped. 9253 // The non-canonical typecheck is just an optimization; 9254 // CheckImplicitConversion will filter out dead implicit conversions. 9255 if (E->getType() != T) 9256 CheckImplicitConversion(S, E, T, CC); 9257 9258 // Now continue drilling into this expression. 9259 9260 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 9261 // The bound subexpressions in a PseudoObjectExpr are not reachable 9262 // as transitive children. 9263 // FIXME: Use a more uniform representation for this. 9264 for (auto *SE : POE->semantics()) 9265 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 9266 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 9267 } 9268 9269 // Skip past explicit casts. 9270 if (isa<ExplicitCastExpr>(E)) { 9271 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 9272 return AnalyzeImplicitConversions(S, E, CC); 9273 } 9274 9275 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9276 // Do a somewhat different check with comparison operators. 9277 if (BO->isComparisonOp()) 9278 return AnalyzeComparison(S, BO); 9279 9280 // And with simple assignments. 9281 if (BO->getOpcode() == BO_Assign) 9282 return AnalyzeAssignment(S, BO); 9283 } 9284 9285 // These break the otherwise-useful invariant below. Fortunately, 9286 // we don't really need to recurse into them, because any internal 9287 // expressions should have been analyzed already when they were 9288 // built into statements. 9289 if (isa<StmtExpr>(E)) return; 9290 9291 // Don't descend into unevaluated contexts. 9292 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 9293 9294 // Now just recurse over the expression's children. 9295 CC = E->getExprLoc(); 9296 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 9297 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 9298 for (Stmt *SubStmt : E->children()) { 9299 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 9300 if (!ChildExpr) 9301 continue; 9302 9303 if (IsLogicalAndOperator && 9304 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 9305 // Ignore checking string literals that are in logical and operators. 9306 // This is a common pattern for asserts. 9307 continue; 9308 AnalyzeImplicitConversions(S, ChildExpr, CC); 9309 } 9310 9311 if (BO && BO->isLogicalOp()) { 9312 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 9313 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9314 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9315 9316 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 9317 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 9318 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 9319 } 9320 9321 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 9322 if (U->getOpcode() == UO_LNot) 9323 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 9324 } 9325 9326 } // end anonymous namespace 9327 9328 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 9329 unsigned Start, unsigned End) { 9330 bool IllegalParams = false; 9331 for (unsigned I = Start; I <= End; ++I) { 9332 QualType Ty = TheCall->getArg(I)->getType(); 9333 // Taking into account implicit conversions, 9334 // allow any integer within 32 bits range 9335 if (!Ty->isIntegerType() || 9336 S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) { 9337 S.Diag(TheCall->getArg(I)->getLocStart(), 9338 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 9339 IllegalParams = true; 9340 } 9341 // Potentially emit standard warnings for implicit conversions if enabled 9342 // using -Wconversion. 9343 CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy, 9344 TheCall->getArg(I)->getLocStart()); 9345 } 9346 return IllegalParams; 9347 } 9348 9349 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 9350 // Returns true when emitting a warning about taking the address of a reference. 9351 static bool CheckForReference(Sema &SemaRef, const Expr *E, 9352 const PartialDiagnostic &PD) { 9353 E = E->IgnoreParenImpCasts(); 9354 9355 const FunctionDecl *FD = nullptr; 9356 9357 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9358 if (!DRE->getDecl()->getType()->isReferenceType()) 9359 return false; 9360 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9361 if (!M->getMemberDecl()->getType()->isReferenceType()) 9362 return false; 9363 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 9364 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 9365 return false; 9366 FD = Call->getDirectCallee(); 9367 } else { 9368 return false; 9369 } 9370 9371 SemaRef.Diag(E->getExprLoc(), PD); 9372 9373 // If possible, point to location of function. 9374 if (FD) { 9375 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 9376 } 9377 9378 return true; 9379 } 9380 9381 // Returns true if the SourceLocation is expanded from any macro body. 9382 // Returns false if the SourceLocation is invalid, is from not in a macro 9383 // expansion, or is from expanded from a top-level macro argument. 9384 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 9385 if (Loc.isInvalid()) 9386 return false; 9387 9388 while (Loc.isMacroID()) { 9389 if (SM.isMacroBodyExpansion(Loc)) 9390 return true; 9391 Loc = SM.getImmediateMacroCallerLoc(Loc); 9392 } 9393 9394 return false; 9395 } 9396 9397 /// \brief Diagnose pointers that are always non-null. 9398 /// \param E the expression containing the pointer 9399 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 9400 /// compared to a null pointer 9401 /// \param IsEqual True when the comparison is equal to a null pointer 9402 /// \param Range Extra SourceRange to highlight in the diagnostic 9403 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 9404 Expr::NullPointerConstantKind NullKind, 9405 bool IsEqual, SourceRange Range) { 9406 if (!E) 9407 return; 9408 9409 // Don't warn inside macros. 9410 if (E->getExprLoc().isMacroID()) { 9411 const SourceManager &SM = getSourceManager(); 9412 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 9413 IsInAnyMacroBody(SM, Range.getBegin())) 9414 return; 9415 } 9416 E = E->IgnoreImpCasts(); 9417 9418 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 9419 9420 if (isa<CXXThisExpr>(E)) { 9421 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 9422 : diag::warn_this_bool_conversion; 9423 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 9424 return; 9425 } 9426 9427 bool IsAddressOf = false; 9428 9429 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9430 if (UO->getOpcode() != UO_AddrOf) 9431 return; 9432 IsAddressOf = true; 9433 E = UO->getSubExpr(); 9434 } 9435 9436 if (IsAddressOf) { 9437 unsigned DiagID = IsCompare 9438 ? diag::warn_address_of_reference_null_compare 9439 : diag::warn_address_of_reference_bool_conversion; 9440 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 9441 << IsEqual; 9442 if (CheckForReference(*this, E, PD)) { 9443 return; 9444 } 9445 } 9446 9447 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 9448 bool IsParam = isa<NonNullAttr>(NonnullAttr); 9449 std::string Str; 9450 llvm::raw_string_ostream S(Str); 9451 E->printPretty(S, nullptr, getPrintingPolicy()); 9452 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 9453 : diag::warn_cast_nonnull_to_bool; 9454 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 9455 << E->getSourceRange() << Range << IsEqual; 9456 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 9457 }; 9458 9459 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 9460 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 9461 if (auto *Callee = Call->getDirectCallee()) { 9462 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 9463 ComplainAboutNonnullParamOrCall(A); 9464 return; 9465 } 9466 } 9467 } 9468 9469 // Expect to find a single Decl. Skip anything more complicated. 9470 ValueDecl *D = nullptr; 9471 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 9472 D = R->getDecl(); 9473 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 9474 D = M->getMemberDecl(); 9475 } 9476 9477 // Weak Decls can be null. 9478 if (!D || D->isWeak()) 9479 return; 9480 9481 // Check for parameter decl with nonnull attribute 9482 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 9483 if (getCurFunction() && 9484 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 9485 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 9486 ComplainAboutNonnullParamOrCall(A); 9487 return; 9488 } 9489 9490 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 9491 auto ParamIter = llvm::find(FD->parameters(), PV); 9492 assert(ParamIter != FD->param_end()); 9493 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 9494 9495 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 9496 if (!NonNull->args_size()) { 9497 ComplainAboutNonnullParamOrCall(NonNull); 9498 return; 9499 } 9500 9501 for (unsigned ArgNo : NonNull->args()) { 9502 if (ArgNo == ParamNo) { 9503 ComplainAboutNonnullParamOrCall(NonNull); 9504 return; 9505 } 9506 } 9507 } 9508 } 9509 } 9510 } 9511 9512 QualType T = D->getType(); 9513 const bool IsArray = T->isArrayType(); 9514 const bool IsFunction = T->isFunctionType(); 9515 9516 // Address of function is used to silence the function warning. 9517 if (IsAddressOf && IsFunction) { 9518 return; 9519 } 9520 9521 // Found nothing. 9522 if (!IsAddressOf && !IsFunction && !IsArray) 9523 return; 9524 9525 // Pretty print the expression for the diagnostic. 9526 std::string Str; 9527 llvm::raw_string_ostream S(Str); 9528 E->printPretty(S, nullptr, getPrintingPolicy()); 9529 9530 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 9531 : diag::warn_impcast_pointer_to_bool; 9532 enum { 9533 AddressOf, 9534 FunctionPointer, 9535 ArrayPointer 9536 } DiagType; 9537 if (IsAddressOf) 9538 DiagType = AddressOf; 9539 else if (IsFunction) 9540 DiagType = FunctionPointer; 9541 else if (IsArray) 9542 DiagType = ArrayPointer; 9543 else 9544 llvm_unreachable("Could not determine diagnostic."); 9545 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 9546 << Range << IsEqual; 9547 9548 if (!IsFunction) 9549 return; 9550 9551 // Suggest '&' to silence the function warning. 9552 Diag(E->getExprLoc(), diag::note_function_warning_silence) 9553 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 9554 9555 // Check to see if '()' fixit should be emitted. 9556 QualType ReturnType; 9557 UnresolvedSet<4> NonTemplateOverloads; 9558 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 9559 if (ReturnType.isNull()) 9560 return; 9561 9562 if (IsCompare) { 9563 // There are two cases here. If there is null constant, the only suggest 9564 // for a pointer return type. If the null is 0, then suggest if the return 9565 // type is a pointer or an integer type. 9566 if (!ReturnType->isPointerType()) { 9567 if (NullKind == Expr::NPCK_ZeroExpression || 9568 NullKind == Expr::NPCK_ZeroLiteral) { 9569 if (!ReturnType->isIntegerType()) 9570 return; 9571 } else { 9572 return; 9573 } 9574 } 9575 } else { // !IsCompare 9576 // For function to bool, only suggest if the function pointer has bool 9577 // return type. 9578 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 9579 return; 9580 } 9581 Diag(E->getExprLoc(), diag::note_function_to_function_call) 9582 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 9583 } 9584 9585 /// Diagnoses "dangerous" implicit conversions within the given 9586 /// expression (which is a full expression). Implements -Wconversion 9587 /// and -Wsign-compare. 9588 /// 9589 /// \param CC the "context" location of the implicit conversion, i.e. 9590 /// the most location of the syntactic entity requiring the implicit 9591 /// conversion 9592 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 9593 // Don't diagnose in unevaluated contexts. 9594 if (isUnevaluatedContext()) 9595 return; 9596 9597 // Don't diagnose for value- or type-dependent expressions. 9598 if (E->isTypeDependent() || E->isValueDependent()) 9599 return; 9600 9601 // Check for array bounds violations in cases where the check isn't triggered 9602 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 9603 // ArraySubscriptExpr is on the RHS of a variable initialization. 9604 CheckArrayAccess(E); 9605 9606 // This is not the right CC for (e.g.) a variable initialization. 9607 AnalyzeImplicitConversions(*this, E, CC); 9608 } 9609 9610 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 9611 /// Input argument E is a logical expression. 9612 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 9613 ::CheckBoolLikeConversion(*this, E, CC); 9614 } 9615 9616 /// Diagnose when expression is an integer constant expression and its evaluation 9617 /// results in integer overflow 9618 void Sema::CheckForIntOverflow (Expr *E) { 9619 // Use a work list to deal with nested struct initializers. 9620 SmallVector<Expr *, 2> Exprs(1, E); 9621 9622 do { 9623 Expr *E = Exprs.pop_back_val(); 9624 9625 if (isa<BinaryOperator>(E->IgnoreParenCasts())) { 9626 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 9627 continue; 9628 } 9629 9630 if (auto InitList = dyn_cast<InitListExpr>(E)) 9631 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 9632 } while (!Exprs.empty()); 9633 } 9634 9635 namespace { 9636 /// \brief Visitor for expressions which looks for unsequenced operations on the 9637 /// same object. 9638 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 9639 typedef EvaluatedExprVisitor<SequenceChecker> Base; 9640 9641 /// \brief A tree of sequenced regions within an expression. Two regions are 9642 /// unsequenced if one is an ancestor or a descendent of the other. When we 9643 /// finish processing an expression with sequencing, such as a comma 9644 /// expression, we fold its tree nodes into its parent, since they are 9645 /// unsequenced with respect to nodes we will visit later. 9646 class SequenceTree { 9647 struct Value { 9648 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 9649 unsigned Parent : 31; 9650 unsigned Merged : 1; 9651 }; 9652 SmallVector<Value, 8> Values; 9653 9654 public: 9655 /// \brief A region within an expression which may be sequenced with respect 9656 /// to some other region. 9657 class Seq { 9658 explicit Seq(unsigned N) : Index(N) {} 9659 unsigned Index; 9660 friend class SequenceTree; 9661 public: 9662 Seq() : Index(0) {} 9663 }; 9664 9665 SequenceTree() { Values.push_back(Value(0)); } 9666 Seq root() const { return Seq(0); } 9667 9668 /// \brief Create a new sequence of operations, which is an unsequenced 9669 /// subset of \p Parent. This sequence of operations is sequenced with 9670 /// respect to other children of \p Parent. 9671 Seq allocate(Seq Parent) { 9672 Values.push_back(Value(Parent.Index)); 9673 return Seq(Values.size() - 1); 9674 } 9675 9676 /// \brief Merge a sequence of operations into its parent. 9677 void merge(Seq S) { 9678 Values[S.Index].Merged = true; 9679 } 9680 9681 /// \brief Determine whether two operations are unsequenced. This operation 9682 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 9683 /// should have been merged into its parent as appropriate. 9684 bool isUnsequenced(Seq Cur, Seq Old) { 9685 unsigned C = representative(Cur.Index); 9686 unsigned Target = representative(Old.Index); 9687 while (C >= Target) { 9688 if (C == Target) 9689 return true; 9690 C = Values[C].Parent; 9691 } 9692 return false; 9693 } 9694 9695 private: 9696 /// \brief Pick a representative for a sequence. 9697 unsigned representative(unsigned K) { 9698 if (Values[K].Merged) 9699 // Perform path compression as we go. 9700 return Values[K].Parent = representative(Values[K].Parent); 9701 return K; 9702 } 9703 }; 9704 9705 /// An object for which we can track unsequenced uses. 9706 typedef NamedDecl *Object; 9707 9708 /// Different flavors of object usage which we track. We only track the 9709 /// least-sequenced usage of each kind. 9710 enum UsageKind { 9711 /// A read of an object. Multiple unsequenced reads are OK. 9712 UK_Use, 9713 /// A modification of an object which is sequenced before the value 9714 /// computation of the expression, such as ++n in C++. 9715 UK_ModAsValue, 9716 /// A modification of an object which is not sequenced before the value 9717 /// computation of the expression, such as n++. 9718 UK_ModAsSideEffect, 9719 9720 UK_Count = UK_ModAsSideEffect + 1 9721 }; 9722 9723 struct Usage { 9724 Usage() : Use(nullptr), Seq() {} 9725 Expr *Use; 9726 SequenceTree::Seq Seq; 9727 }; 9728 9729 struct UsageInfo { 9730 UsageInfo() : Diagnosed(false) {} 9731 Usage Uses[UK_Count]; 9732 /// Have we issued a diagnostic for this variable already? 9733 bool Diagnosed; 9734 }; 9735 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 9736 9737 Sema &SemaRef; 9738 /// Sequenced regions within the expression. 9739 SequenceTree Tree; 9740 /// Declaration modifications and references which we have seen. 9741 UsageInfoMap UsageMap; 9742 /// The region we are currently within. 9743 SequenceTree::Seq Region; 9744 /// Filled in with declarations which were modified as a side-effect 9745 /// (that is, post-increment operations). 9746 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 9747 /// Expressions to check later. We defer checking these to reduce 9748 /// stack usage. 9749 SmallVectorImpl<Expr *> &WorkList; 9750 9751 /// RAII object wrapping the visitation of a sequenced subexpression of an 9752 /// expression. At the end of this process, the side-effects of the evaluation 9753 /// become sequenced with respect to the value computation of the result, so 9754 /// we downgrade any UK_ModAsSideEffect within the evaluation to 9755 /// UK_ModAsValue. 9756 struct SequencedSubexpression { 9757 SequencedSubexpression(SequenceChecker &Self) 9758 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 9759 Self.ModAsSideEffect = &ModAsSideEffect; 9760 } 9761 ~SequencedSubexpression() { 9762 for (auto &M : llvm::reverse(ModAsSideEffect)) { 9763 UsageInfo &U = Self.UsageMap[M.first]; 9764 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 9765 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 9766 SideEffectUsage = M.second; 9767 } 9768 Self.ModAsSideEffect = OldModAsSideEffect; 9769 } 9770 9771 SequenceChecker &Self; 9772 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 9773 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 9774 }; 9775 9776 /// RAII object wrapping the visitation of a subexpression which we might 9777 /// choose to evaluate as a constant. If any subexpression is evaluated and 9778 /// found to be non-constant, this allows us to suppress the evaluation of 9779 /// the outer expression. 9780 class EvaluationTracker { 9781 public: 9782 EvaluationTracker(SequenceChecker &Self) 9783 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 9784 Self.EvalTracker = this; 9785 } 9786 ~EvaluationTracker() { 9787 Self.EvalTracker = Prev; 9788 if (Prev) 9789 Prev->EvalOK &= EvalOK; 9790 } 9791 9792 bool evaluate(const Expr *E, bool &Result) { 9793 if (!EvalOK || E->isValueDependent()) 9794 return false; 9795 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 9796 return EvalOK; 9797 } 9798 9799 private: 9800 SequenceChecker &Self; 9801 EvaluationTracker *Prev; 9802 bool EvalOK; 9803 } *EvalTracker; 9804 9805 /// \brief Find the object which is produced by the specified expression, 9806 /// if any. 9807 Object getObject(Expr *E, bool Mod) const { 9808 E = E->IgnoreParenCasts(); 9809 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 9810 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 9811 return getObject(UO->getSubExpr(), Mod); 9812 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9813 if (BO->getOpcode() == BO_Comma) 9814 return getObject(BO->getRHS(), Mod); 9815 if (Mod && BO->isAssignmentOp()) 9816 return getObject(BO->getLHS(), Mod); 9817 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9818 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 9819 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 9820 return ME->getMemberDecl(); 9821 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9822 // FIXME: If this is a reference, map through to its value. 9823 return DRE->getDecl(); 9824 return nullptr; 9825 } 9826 9827 /// \brief Note that an object was modified or used by an expression. 9828 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 9829 Usage &U = UI.Uses[UK]; 9830 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 9831 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 9832 ModAsSideEffect->push_back(std::make_pair(O, U)); 9833 U.Use = Ref; 9834 U.Seq = Region; 9835 } 9836 } 9837 /// \brief Check whether a modification or use conflicts with a prior usage. 9838 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 9839 bool IsModMod) { 9840 if (UI.Diagnosed) 9841 return; 9842 9843 const Usage &U = UI.Uses[OtherKind]; 9844 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 9845 return; 9846 9847 Expr *Mod = U.Use; 9848 Expr *ModOrUse = Ref; 9849 if (OtherKind == UK_Use) 9850 std::swap(Mod, ModOrUse); 9851 9852 SemaRef.Diag(Mod->getExprLoc(), 9853 IsModMod ? diag::warn_unsequenced_mod_mod 9854 : diag::warn_unsequenced_mod_use) 9855 << O << SourceRange(ModOrUse->getExprLoc()); 9856 UI.Diagnosed = true; 9857 } 9858 9859 void notePreUse(Object O, Expr *Use) { 9860 UsageInfo &U = UsageMap[O]; 9861 // Uses conflict with other modifications. 9862 checkUsage(O, U, Use, UK_ModAsValue, false); 9863 } 9864 void notePostUse(Object O, Expr *Use) { 9865 UsageInfo &U = UsageMap[O]; 9866 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 9867 addUsage(U, O, Use, UK_Use); 9868 } 9869 9870 void notePreMod(Object O, Expr *Mod) { 9871 UsageInfo &U = UsageMap[O]; 9872 // Modifications conflict with other modifications and with uses. 9873 checkUsage(O, U, Mod, UK_ModAsValue, true); 9874 checkUsage(O, U, Mod, UK_Use, false); 9875 } 9876 void notePostMod(Object O, Expr *Use, UsageKind UK) { 9877 UsageInfo &U = UsageMap[O]; 9878 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 9879 addUsage(U, O, Use, UK); 9880 } 9881 9882 public: 9883 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 9884 : Base(S.Context), SemaRef(S), Region(Tree.root()), 9885 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 9886 Visit(E); 9887 } 9888 9889 void VisitStmt(Stmt *S) { 9890 // Skip all statements which aren't expressions for now. 9891 } 9892 9893 void VisitExpr(Expr *E) { 9894 // By default, just recurse to evaluated subexpressions. 9895 Base::VisitStmt(E); 9896 } 9897 9898 void VisitCastExpr(CastExpr *E) { 9899 Object O = Object(); 9900 if (E->getCastKind() == CK_LValueToRValue) 9901 O = getObject(E->getSubExpr(), false); 9902 9903 if (O) 9904 notePreUse(O, E); 9905 VisitExpr(E); 9906 if (O) 9907 notePostUse(O, E); 9908 } 9909 9910 void VisitBinComma(BinaryOperator *BO) { 9911 // C++11 [expr.comma]p1: 9912 // Every value computation and side effect associated with the left 9913 // expression is sequenced before every value computation and side 9914 // effect associated with the right expression. 9915 SequenceTree::Seq LHS = Tree.allocate(Region); 9916 SequenceTree::Seq RHS = Tree.allocate(Region); 9917 SequenceTree::Seq OldRegion = Region; 9918 9919 { 9920 SequencedSubexpression SeqLHS(*this); 9921 Region = LHS; 9922 Visit(BO->getLHS()); 9923 } 9924 9925 Region = RHS; 9926 Visit(BO->getRHS()); 9927 9928 Region = OldRegion; 9929 9930 // Forget that LHS and RHS are sequenced. They are both unsequenced 9931 // with respect to other stuff. 9932 Tree.merge(LHS); 9933 Tree.merge(RHS); 9934 } 9935 9936 void VisitBinAssign(BinaryOperator *BO) { 9937 // The modification is sequenced after the value computation of the LHS 9938 // and RHS, so check it before inspecting the operands and update the 9939 // map afterwards. 9940 Object O = getObject(BO->getLHS(), true); 9941 if (!O) 9942 return VisitExpr(BO); 9943 9944 notePreMod(O, BO); 9945 9946 // C++11 [expr.ass]p7: 9947 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 9948 // only once. 9949 // 9950 // Therefore, for a compound assignment operator, O is considered used 9951 // everywhere except within the evaluation of E1 itself. 9952 if (isa<CompoundAssignOperator>(BO)) 9953 notePreUse(O, BO); 9954 9955 Visit(BO->getLHS()); 9956 9957 if (isa<CompoundAssignOperator>(BO)) 9958 notePostUse(O, BO); 9959 9960 Visit(BO->getRHS()); 9961 9962 // C++11 [expr.ass]p1: 9963 // the assignment is sequenced [...] before the value computation of the 9964 // assignment expression. 9965 // C11 6.5.16/3 has no such rule. 9966 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 9967 : UK_ModAsSideEffect); 9968 } 9969 9970 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 9971 VisitBinAssign(CAO); 9972 } 9973 9974 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 9975 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 9976 void VisitUnaryPreIncDec(UnaryOperator *UO) { 9977 Object O = getObject(UO->getSubExpr(), true); 9978 if (!O) 9979 return VisitExpr(UO); 9980 9981 notePreMod(O, UO); 9982 Visit(UO->getSubExpr()); 9983 // C++11 [expr.pre.incr]p1: 9984 // the expression ++x is equivalent to x+=1 9985 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 9986 : UK_ModAsSideEffect); 9987 } 9988 9989 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 9990 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 9991 void VisitUnaryPostIncDec(UnaryOperator *UO) { 9992 Object O = getObject(UO->getSubExpr(), true); 9993 if (!O) 9994 return VisitExpr(UO); 9995 9996 notePreMod(O, UO); 9997 Visit(UO->getSubExpr()); 9998 notePostMod(O, UO, UK_ModAsSideEffect); 9999 } 10000 10001 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 10002 void VisitBinLOr(BinaryOperator *BO) { 10003 // The side-effects of the LHS of an '&&' are sequenced before the 10004 // value computation of the RHS, and hence before the value computation 10005 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 10006 // as if they were unconditionally sequenced. 10007 EvaluationTracker Eval(*this); 10008 { 10009 SequencedSubexpression Sequenced(*this); 10010 Visit(BO->getLHS()); 10011 } 10012 10013 bool Result; 10014 if (Eval.evaluate(BO->getLHS(), Result)) { 10015 if (!Result) 10016 Visit(BO->getRHS()); 10017 } else { 10018 // Check for unsequenced operations in the RHS, treating it as an 10019 // entirely separate evaluation. 10020 // 10021 // FIXME: If there are operations in the RHS which are unsequenced 10022 // with respect to operations outside the RHS, and those operations 10023 // are unconditionally evaluated, diagnose them. 10024 WorkList.push_back(BO->getRHS()); 10025 } 10026 } 10027 void VisitBinLAnd(BinaryOperator *BO) { 10028 EvaluationTracker Eval(*this); 10029 { 10030 SequencedSubexpression Sequenced(*this); 10031 Visit(BO->getLHS()); 10032 } 10033 10034 bool Result; 10035 if (Eval.evaluate(BO->getLHS(), Result)) { 10036 if (Result) 10037 Visit(BO->getRHS()); 10038 } else { 10039 WorkList.push_back(BO->getRHS()); 10040 } 10041 } 10042 10043 // Only visit the condition, unless we can be sure which subexpression will 10044 // be chosen. 10045 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 10046 EvaluationTracker Eval(*this); 10047 { 10048 SequencedSubexpression Sequenced(*this); 10049 Visit(CO->getCond()); 10050 } 10051 10052 bool Result; 10053 if (Eval.evaluate(CO->getCond(), Result)) 10054 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 10055 else { 10056 WorkList.push_back(CO->getTrueExpr()); 10057 WorkList.push_back(CO->getFalseExpr()); 10058 } 10059 } 10060 10061 void VisitCallExpr(CallExpr *CE) { 10062 // C++11 [intro.execution]p15: 10063 // When calling a function [...], every value computation and side effect 10064 // associated with any argument expression, or with the postfix expression 10065 // designating the called function, is sequenced before execution of every 10066 // expression or statement in the body of the function [and thus before 10067 // the value computation of its result]. 10068 SequencedSubexpression Sequenced(*this); 10069 Base::VisitCallExpr(CE); 10070 10071 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 10072 } 10073 10074 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 10075 // This is a call, so all subexpressions are sequenced before the result. 10076 SequencedSubexpression Sequenced(*this); 10077 10078 if (!CCE->isListInitialization()) 10079 return VisitExpr(CCE); 10080 10081 // In C++11, list initializations are sequenced. 10082 SmallVector<SequenceTree::Seq, 32> Elts; 10083 SequenceTree::Seq Parent = Region; 10084 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 10085 E = CCE->arg_end(); 10086 I != E; ++I) { 10087 Region = Tree.allocate(Parent); 10088 Elts.push_back(Region); 10089 Visit(*I); 10090 } 10091 10092 // Forget that the initializers are sequenced. 10093 Region = Parent; 10094 for (unsigned I = 0; I < Elts.size(); ++I) 10095 Tree.merge(Elts[I]); 10096 } 10097 10098 void VisitInitListExpr(InitListExpr *ILE) { 10099 if (!SemaRef.getLangOpts().CPlusPlus11) 10100 return VisitExpr(ILE); 10101 10102 // In C++11, list initializations are sequenced. 10103 SmallVector<SequenceTree::Seq, 32> Elts; 10104 SequenceTree::Seq Parent = Region; 10105 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 10106 Expr *E = ILE->getInit(I); 10107 if (!E) continue; 10108 Region = Tree.allocate(Parent); 10109 Elts.push_back(Region); 10110 Visit(E); 10111 } 10112 10113 // Forget that the initializers are sequenced. 10114 Region = Parent; 10115 for (unsigned I = 0; I < Elts.size(); ++I) 10116 Tree.merge(Elts[I]); 10117 } 10118 }; 10119 } // end anonymous namespace 10120 10121 void Sema::CheckUnsequencedOperations(Expr *E) { 10122 SmallVector<Expr *, 8> WorkList; 10123 WorkList.push_back(E); 10124 while (!WorkList.empty()) { 10125 Expr *Item = WorkList.pop_back_val(); 10126 SequenceChecker(*this, Item, WorkList); 10127 } 10128 } 10129 10130 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 10131 bool IsConstexpr) { 10132 CheckImplicitConversions(E, CheckLoc); 10133 if (!E->isInstantiationDependent()) 10134 CheckUnsequencedOperations(E); 10135 if (!IsConstexpr && !E->isValueDependent()) 10136 CheckForIntOverflow(E); 10137 DiagnoseMisalignedMembers(); 10138 } 10139 10140 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 10141 FieldDecl *BitField, 10142 Expr *Init) { 10143 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 10144 } 10145 10146 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 10147 SourceLocation Loc) { 10148 if (!PType->isVariablyModifiedType()) 10149 return; 10150 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 10151 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 10152 return; 10153 } 10154 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 10155 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 10156 return; 10157 } 10158 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 10159 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 10160 return; 10161 } 10162 10163 const ArrayType *AT = S.Context.getAsArrayType(PType); 10164 if (!AT) 10165 return; 10166 10167 if (AT->getSizeModifier() != ArrayType::Star) { 10168 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 10169 return; 10170 } 10171 10172 S.Diag(Loc, diag::err_array_star_in_function_definition); 10173 } 10174 10175 /// CheckParmsForFunctionDef - Check that the parameters of the given 10176 /// function are appropriate for the definition of a function. This 10177 /// takes care of any checks that cannot be performed on the 10178 /// declaration itself, e.g., that the types of each of the function 10179 /// parameters are complete. 10180 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 10181 bool CheckParameterNames) { 10182 bool HasInvalidParm = false; 10183 for (ParmVarDecl *Param : Parameters) { 10184 // C99 6.7.5.3p4: the parameters in a parameter type list in a 10185 // function declarator that is part of a function definition of 10186 // that function shall not have incomplete type. 10187 // 10188 // This is also C++ [dcl.fct]p6. 10189 if (!Param->isInvalidDecl() && 10190 RequireCompleteType(Param->getLocation(), Param->getType(), 10191 diag::err_typecheck_decl_incomplete_type)) { 10192 Param->setInvalidDecl(); 10193 HasInvalidParm = true; 10194 } 10195 10196 // C99 6.9.1p5: If the declarator includes a parameter type list, the 10197 // declaration of each parameter shall include an identifier. 10198 if (CheckParameterNames && 10199 Param->getIdentifier() == nullptr && 10200 !Param->isImplicit() && 10201 !getLangOpts().CPlusPlus) 10202 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10203 10204 // C99 6.7.5.3p12: 10205 // If the function declarator is not part of a definition of that 10206 // function, parameters may have incomplete type and may use the [*] 10207 // notation in their sequences of declarator specifiers to specify 10208 // variable length array types. 10209 QualType PType = Param->getOriginalType(); 10210 // FIXME: This diagnostic should point the '[*]' if source-location 10211 // information is added for it. 10212 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 10213 10214 // MSVC destroys objects passed by value in the callee. Therefore a 10215 // function definition which takes such a parameter must be able to call the 10216 // object's destructor. However, we don't perform any direct access check 10217 // on the dtor. 10218 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 10219 .getCXXABI() 10220 .areArgsDestroyedLeftToRightInCallee()) { 10221 if (!Param->isInvalidDecl()) { 10222 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 10223 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 10224 if (!ClassDecl->isInvalidDecl() && 10225 !ClassDecl->hasIrrelevantDestructor() && 10226 !ClassDecl->isDependentContext()) { 10227 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10228 MarkFunctionReferenced(Param->getLocation(), Destructor); 10229 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 10230 } 10231 } 10232 } 10233 } 10234 10235 // Parameters with the pass_object_size attribute only need to be marked 10236 // constant at function definitions. Because we lack information about 10237 // whether we're on a declaration or definition when we're instantiating the 10238 // attribute, we need to check for constness here. 10239 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 10240 if (!Param->getType().isConstQualified()) 10241 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 10242 << Attr->getSpelling() << 1; 10243 } 10244 10245 return HasInvalidParm; 10246 } 10247 10248 /// CheckCastAlign - Implements -Wcast-align, which warns when a 10249 /// pointer cast increases the alignment requirements. 10250 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 10251 // This is actually a lot of work to potentially be doing on every 10252 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 10253 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 10254 return; 10255 10256 // Ignore dependent types. 10257 if (T->isDependentType() || Op->getType()->isDependentType()) 10258 return; 10259 10260 // Require that the destination be a pointer type. 10261 const PointerType *DestPtr = T->getAs<PointerType>(); 10262 if (!DestPtr) return; 10263 10264 // If the destination has alignment 1, we're done. 10265 QualType DestPointee = DestPtr->getPointeeType(); 10266 if (DestPointee->isIncompleteType()) return; 10267 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 10268 if (DestAlign.isOne()) return; 10269 10270 // Require that the source be a pointer type. 10271 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 10272 if (!SrcPtr) return; 10273 QualType SrcPointee = SrcPtr->getPointeeType(); 10274 10275 // Whitelist casts from cv void*. We already implicitly 10276 // whitelisted casts to cv void*, since they have alignment 1. 10277 // Also whitelist casts involving incomplete types, which implicitly 10278 // includes 'void'. 10279 if (SrcPointee->isIncompleteType()) return; 10280 10281 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 10282 if (SrcAlign >= DestAlign) return; 10283 10284 Diag(TRange.getBegin(), diag::warn_cast_align) 10285 << Op->getType() << T 10286 << static_cast<unsigned>(SrcAlign.getQuantity()) 10287 << static_cast<unsigned>(DestAlign.getQuantity()) 10288 << TRange << Op->getSourceRange(); 10289 } 10290 10291 /// \brief Check whether this array fits the idiom of a size-one tail padded 10292 /// array member of a struct. 10293 /// 10294 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 10295 /// commonly used to emulate flexible arrays in C89 code. 10296 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 10297 const NamedDecl *ND) { 10298 if (Size != 1 || !ND) return false; 10299 10300 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 10301 if (!FD) return false; 10302 10303 // Don't consider sizes resulting from macro expansions or template argument 10304 // substitution to form C89 tail-padded arrays. 10305 10306 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 10307 while (TInfo) { 10308 TypeLoc TL = TInfo->getTypeLoc(); 10309 // Look through typedefs. 10310 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 10311 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 10312 TInfo = TDL->getTypeSourceInfo(); 10313 continue; 10314 } 10315 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 10316 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 10317 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 10318 return false; 10319 } 10320 break; 10321 } 10322 10323 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 10324 if (!RD) return false; 10325 if (RD->isUnion()) return false; 10326 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10327 if (!CRD->isStandardLayout()) return false; 10328 } 10329 10330 // See if this is the last field decl in the record. 10331 const Decl *D = FD; 10332 while ((D = D->getNextDeclInContext())) 10333 if (isa<FieldDecl>(D)) 10334 return false; 10335 return true; 10336 } 10337 10338 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 10339 const ArraySubscriptExpr *ASE, 10340 bool AllowOnePastEnd, bool IndexNegated) { 10341 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 10342 if (IndexExpr->isValueDependent()) 10343 return; 10344 10345 const Type *EffectiveType = 10346 BaseExpr->getType()->getPointeeOrArrayElementType(); 10347 BaseExpr = BaseExpr->IgnoreParenCasts(); 10348 const ConstantArrayType *ArrayTy = 10349 Context.getAsConstantArrayType(BaseExpr->getType()); 10350 if (!ArrayTy) 10351 return; 10352 10353 llvm::APSInt index; 10354 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 10355 return; 10356 if (IndexNegated) 10357 index = -index; 10358 10359 const NamedDecl *ND = nullptr; 10360 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10361 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10362 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10363 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10364 10365 if (index.isUnsigned() || !index.isNegative()) { 10366 llvm::APInt size = ArrayTy->getSize(); 10367 if (!size.isStrictlyPositive()) 10368 return; 10369 10370 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 10371 if (BaseType != EffectiveType) { 10372 // Make sure we're comparing apples to apples when comparing index to size 10373 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 10374 uint64_t array_typesize = Context.getTypeSize(BaseType); 10375 // Handle ptrarith_typesize being zero, such as when casting to void* 10376 if (!ptrarith_typesize) ptrarith_typesize = 1; 10377 if (ptrarith_typesize != array_typesize) { 10378 // There's a cast to a different size type involved 10379 uint64_t ratio = array_typesize / ptrarith_typesize; 10380 // TODO: Be smarter about handling cases where array_typesize is not a 10381 // multiple of ptrarith_typesize 10382 if (ptrarith_typesize * ratio == array_typesize) 10383 size *= llvm::APInt(size.getBitWidth(), ratio); 10384 } 10385 } 10386 10387 if (size.getBitWidth() > index.getBitWidth()) 10388 index = index.zext(size.getBitWidth()); 10389 else if (size.getBitWidth() < index.getBitWidth()) 10390 size = size.zext(index.getBitWidth()); 10391 10392 // For array subscripting the index must be less than size, but for pointer 10393 // arithmetic also allow the index (offset) to be equal to size since 10394 // computing the next address after the end of the array is legal and 10395 // commonly done e.g. in C++ iterators and range-based for loops. 10396 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 10397 return; 10398 10399 // Also don't warn for arrays of size 1 which are members of some 10400 // structure. These are often used to approximate flexible arrays in C89 10401 // code. 10402 if (IsTailPaddedMemberArray(*this, size, ND)) 10403 return; 10404 10405 // Suppress the warning if the subscript expression (as identified by the 10406 // ']' location) and the index expression are both from macro expansions 10407 // within a system header. 10408 if (ASE) { 10409 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 10410 ASE->getRBracketLoc()); 10411 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 10412 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 10413 IndexExpr->getLocStart()); 10414 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 10415 return; 10416 } 10417 } 10418 10419 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 10420 if (ASE) 10421 DiagID = diag::warn_array_index_exceeds_bounds; 10422 10423 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10424 PDiag(DiagID) << index.toString(10, true) 10425 << size.toString(10, true) 10426 << (unsigned)size.getLimitedValue(~0U) 10427 << IndexExpr->getSourceRange()); 10428 } else { 10429 unsigned DiagID = diag::warn_array_index_precedes_bounds; 10430 if (!ASE) { 10431 DiagID = diag::warn_ptr_arith_precedes_bounds; 10432 if (index.isNegative()) index = -index; 10433 } 10434 10435 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 10436 PDiag(DiagID) << index.toString(10, true) 10437 << IndexExpr->getSourceRange()); 10438 } 10439 10440 if (!ND) { 10441 // Try harder to find a NamedDecl to point at in the note. 10442 while (const ArraySubscriptExpr *ASE = 10443 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 10444 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 10445 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 10446 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 10447 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 10448 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 10449 } 10450 10451 if (ND) 10452 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 10453 PDiag(diag::note_array_index_out_of_bounds) 10454 << ND->getDeclName()); 10455 } 10456 10457 void Sema::CheckArrayAccess(const Expr *expr) { 10458 int AllowOnePastEnd = 0; 10459 while (expr) { 10460 expr = expr->IgnoreParenImpCasts(); 10461 switch (expr->getStmtClass()) { 10462 case Stmt::ArraySubscriptExprClass: { 10463 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 10464 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 10465 AllowOnePastEnd > 0); 10466 return; 10467 } 10468 case Stmt::OMPArraySectionExprClass: { 10469 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 10470 if (ASE->getLowerBound()) 10471 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 10472 /*ASE=*/nullptr, AllowOnePastEnd > 0); 10473 return; 10474 } 10475 case Stmt::UnaryOperatorClass: { 10476 // Only unwrap the * and & unary operators 10477 const UnaryOperator *UO = cast<UnaryOperator>(expr); 10478 expr = UO->getSubExpr(); 10479 switch (UO->getOpcode()) { 10480 case UO_AddrOf: 10481 AllowOnePastEnd++; 10482 break; 10483 case UO_Deref: 10484 AllowOnePastEnd--; 10485 break; 10486 default: 10487 return; 10488 } 10489 break; 10490 } 10491 case Stmt::ConditionalOperatorClass: { 10492 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 10493 if (const Expr *lhs = cond->getLHS()) 10494 CheckArrayAccess(lhs); 10495 if (const Expr *rhs = cond->getRHS()) 10496 CheckArrayAccess(rhs); 10497 return; 10498 } 10499 default: 10500 return; 10501 } 10502 } 10503 } 10504 10505 //===--- CHECK: Objective-C retain cycles ----------------------------------// 10506 10507 namespace { 10508 struct RetainCycleOwner { 10509 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 10510 VarDecl *Variable; 10511 SourceRange Range; 10512 SourceLocation Loc; 10513 bool Indirect; 10514 10515 void setLocsFrom(Expr *e) { 10516 Loc = e->getExprLoc(); 10517 Range = e->getSourceRange(); 10518 } 10519 }; 10520 } // end anonymous namespace 10521 10522 /// Consider whether capturing the given variable can possibly lead to 10523 /// a retain cycle. 10524 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 10525 // In ARC, it's captured strongly iff the variable has __strong 10526 // lifetime. In MRR, it's captured strongly if the variable is 10527 // __block and has an appropriate type. 10528 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 10529 return false; 10530 10531 owner.Variable = var; 10532 if (ref) 10533 owner.setLocsFrom(ref); 10534 return true; 10535 } 10536 10537 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 10538 while (true) { 10539 e = e->IgnoreParens(); 10540 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 10541 switch (cast->getCastKind()) { 10542 case CK_BitCast: 10543 case CK_LValueBitCast: 10544 case CK_LValueToRValue: 10545 case CK_ARCReclaimReturnedObject: 10546 e = cast->getSubExpr(); 10547 continue; 10548 10549 default: 10550 return false; 10551 } 10552 } 10553 10554 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 10555 ObjCIvarDecl *ivar = ref->getDecl(); 10556 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 10557 return false; 10558 10559 // Try to find a retain cycle in the base. 10560 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 10561 return false; 10562 10563 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 10564 owner.Indirect = true; 10565 return true; 10566 } 10567 10568 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 10569 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 10570 if (!var) return false; 10571 return considerVariable(var, ref, owner); 10572 } 10573 10574 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 10575 if (member->isArrow()) return false; 10576 10577 // Don't count this as an indirect ownership. 10578 e = member->getBase(); 10579 continue; 10580 } 10581 10582 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 10583 // Only pay attention to pseudo-objects on property references. 10584 ObjCPropertyRefExpr *pre 10585 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 10586 ->IgnoreParens()); 10587 if (!pre) return false; 10588 if (pre->isImplicitProperty()) return false; 10589 ObjCPropertyDecl *property = pre->getExplicitProperty(); 10590 if (!property->isRetaining() && 10591 !(property->getPropertyIvarDecl() && 10592 property->getPropertyIvarDecl()->getType() 10593 .getObjCLifetime() == Qualifiers::OCL_Strong)) 10594 return false; 10595 10596 owner.Indirect = true; 10597 if (pre->isSuperReceiver()) { 10598 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 10599 if (!owner.Variable) 10600 return false; 10601 owner.Loc = pre->getLocation(); 10602 owner.Range = pre->getSourceRange(); 10603 return true; 10604 } 10605 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 10606 ->getSourceExpr()); 10607 continue; 10608 } 10609 10610 // Array ivars? 10611 10612 return false; 10613 } 10614 } 10615 10616 namespace { 10617 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 10618 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 10619 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 10620 Context(Context), Variable(variable), Capturer(nullptr), 10621 VarWillBeReased(false) {} 10622 ASTContext &Context; 10623 VarDecl *Variable; 10624 Expr *Capturer; 10625 bool VarWillBeReased; 10626 10627 void VisitDeclRefExpr(DeclRefExpr *ref) { 10628 if (ref->getDecl() == Variable && !Capturer) 10629 Capturer = ref; 10630 } 10631 10632 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 10633 if (Capturer) return; 10634 Visit(ref->getBase()); 10635 if (Capturer && ref->isFreeIvar()) 10636 Capturer = ref; 10637 } 10638 10639 void VisitBlockExpr(BlockExpr *block) { 10640 // Look inside nested blocks 10641 if (block->getBlockDecl()->capturesVariable(Variable)) 10642 Visit(block->getBlockDecl()->getBody()); 10643 } 10644 10645 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 10646 if (Capturer) return; 10647 if (OVE->getSourceExpr()) 10648 Visit(OVE->getSourceExpr()); 10649 } 10650 void VisitBinaryOperator(BinaryOperator *BinOp) { 10651 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 10652 return; 10653 Expr *LHS = BinOp->getLHS(); 10654 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 10655 if (DRE->getDecl() != Variable) 10656 return; 10657 if (Expr *RHS = BinOp->getRHS()) { 10658 RHS = RHS->IgnoreParenCasts(); 10659 llvm::APSInt Value; 10660 VarWillBeReased = 10661 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 10662 } 10663 } 10664 } 10665 }; 10666 } // end anonymous namespace 10667 10668 /// Check whether the given argument is a block which captures a 10669 /// variable. 10670 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 10671 assert(owner.Variable && owner.Loc.isValid()); 10672 10673 e = e->IgnoreParenCasts(); 10674 10675 // Look through [^{...} copy] and Block_copy(^{...}). 10676 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 10677 Selector Cmd = ME->getSelector(); 10678 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 10679 e = ME->getInstanceReceiver(); 10680 if (!e) 10681 return nullptr; 10682 e = e->IgnoreParenCasts(); 10683 } 10684 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 10685 if (CE->getNumArgs() == 1) { 10686 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 10687 if (Fn) { 10688 const IdentifierInfo *FnI = Fn->getIdentifier(); 10689 if (FnI && FnI->isStr("_Block_copy")) { 10690 e = CE->getArg(0)->IgnoreParenCasts(); 10691 } 10692 } 10693 } 10694 } 10695 10696 BlockExpr *block = dyn_cast<BlockExpr>(e); 10697 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 10698 return nullptr; 10699 10700 FindCaptureVisitor visitor(S.Context, owner.Variable); 10701 visitor.Visit(block->getBlockDecl()->getBody()); 10702 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 10703 } 10704 10705 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 10706 RetainCycleOwner &owner) { 10707 assert(capturer); 10708 assert(owner.Variable && owner.Loc.isValid()); 10709 10710 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 10711 << owner.Variable << capturer->getSourceRange(); 10712 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 10713 << owner.Indirect << owner.Range; 10714 } 10715 10716 /// Check for a keyword selector that starts with the word 'add' or 10717 /// 'set'. 10718 static bool isSetterLikeSelector(Selector sel) { 10719 if (sel.isUnarySelector()) return false; 10720 10721 StringRef str = sel.getNameForSlot(0); 10722 while (!str.empty() && str.front() == '_') str = str.substr(1); 10723 if (str.startswith("set")) 10724 str = str.substr(3); 10725 else if (str.startswith("add")) { 10726 // Specially whitelist 'addOperationWithBlock:'. 10727 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 10728 return false; 10729 str = str.substr(3); 10730 } 10731 else 10732 return false; 10733 10734 if (str.empty()) return true; 10735 return !isLowercase(str.front()); 10736 } 10737 10738 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 10739 ObjCMessageExpr *Message) { 10740 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 10741 Message->getReceiverInterface(), 10742 NSAPI::ClassId_NSMutableArray); 10743 if (!IsMutableArray) { 10744 return None; 10745 } 10746 10747 Selector Sel = Message->getSelector(); 10748 10749 Optional<NSAPI::NSArrayMethodKind> MKOpt = 10750 S.NSAPIObj->getNSArrayMethodKind(Sel); 10751 if (!MKOpt) { 10752 return None; 10753 } 10754 10755 NSAPI::NSArrayMethodKind MK = *MKOpt; 10756 10757 switch (MK) { 10758 case NSAPI::NSMutableArr_addObject: 10759 case NSAPI::NSMutableArr_insertObjectAtIndex: 10760 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 10761 return 0; 10762 case NSAPI::NSMutableArr_replaceObjectAtIndex: 10763 return 1; 10764 10765 default: 10766 return None; 10767 } 10768 10769 return None; 10770 } 10771 10772 static 10773 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 10774 ObjCMessageExpr *Message) { 10775 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 10776 Message->getReceiverInterface(), 10777 NSAPI::ClassId_NSMutableDictionary); 10778 if (!IsMutableDictionary) { 10779 return None; 10780 } 10781 10782 Selector Sel = Message->getSelector(); 10783 10784 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 10785 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 10786 if (!MKOpt) { 10787 return None; 10788 } 10789 10790 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 10791 10792 switch (MK) { 10793 case NSAPI::NSMutableDict_setObjectForKey: 10794 case NSAPI::NSMutableDict_setValueForKey: 10795 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 10796 return 0; 10797 10798 default: 10799 return None; 10800 } 10801 10802 return None; 10803 } 10804 10805 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 10806 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 10807 Message->getReceiverInterface(), 10808 NSAPI::ClassId_NSMutableSet); 10809 10810 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 10811 Message->getReceiverInterface(), 10812 NSAPI::ClassId_NSMutableOrderedSet); 10813 if (!IsMutableSet && !IsMutableOrderedSet) { 10814 return None; 10815 } 10816 10817 Selector Sel = Message->getSelector(); 10818 10819 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 10820 if (!MKOpt) { 10821 return None; 10822 } 10823 10824 NSAPI::NSSetMethodKind MK = *MKOpt; 10825 10826 switch (MK) { 10827 case NSAPI::NSMutableSet_addObject: 10828 case NSAPI::NSOrderedSet_setObjectAtIndex: 10829 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 10830 case NSAPI::NSOrderedSet_insertObjectAtIndex: 10831 return 0; 10832 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 10833 return 1; 10834 } 10835 10836 return None; 10837 } 10838 10839 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 10840 if (!Message->isInstanceMessage()) { 10841 return; 10842 } 10843 10844 Optional<int> ArgOpt; 10845 10846 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 10847 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 10848 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 10849 return; 10850 } 10851 10852 int ArgIndex = *ArgOpt; 10853 10854 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 10855 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 10856 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 10857 } 10858 10859 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 10860 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 10861 if (ArgRE->isObjCSelfExpr()) { 10862 Diag(Message->getSourceRange().getBegin(), 10863 diag::warn_objc_circular_container) 10864 << ArgRE->getDecl()->getName() << StringRef("super"); 10865 } 10866 } 10867 } else { 10868 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 10869 10870 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 10871 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 10872 } 10873 10874 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 10875 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 10876 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 10877 ValueDecl *Decl = ReceiverRE->getDecl(); 10878 Diag(Message->getSourceRange().getBegin(), 10879 diag::warn_objc_circular_container) 10880 << Decl->getName() << Decl->getName(); 10881 if (!ArgRE->isObjCSelfExpr()) { 10882 Diag(Decl->getLocation(), 10883 diag::note_objc_circular_container_declared_here) 10884 << Decl->getName(); 10885 } 10886 } 10887 } 10888 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 10889 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 10890 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 10891 ObjCIvarDecl *Decl = IvarRE->getDecl(); 10892 Diag(Message->getSourceRange().getBegin(), 10893 diag::warn_objc_circular_container) 10894 << Decl->getName() << Decl->getName(); 10895 Diag(Decl->getLocation(), 10896 diag::note_objc_circular_container_declared_here) 10897 << Decl->getName(); 10898 } 10899 } 10900 } 10901 } 10902 } 10903 10904 /// Check a message send to see if it's likely to cause a retain cycle. 10905 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 10906 // Only check instance methods whose selector looks like a setter. 10907 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 10908 return; 10909 10910 // Try to find a variable that the receiver is strongly owned by. 10911 RetainCycleOwner owner; 10912 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 10913 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 10914 return; 10915 } else { 10916 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 10917 owner.Variable = getCurMethodDecl()->getSelfDecl(); 10918 owner.Loc = msg->getSuperLoc(); 10919 owner.Range = msg->getSuperLoc(); 10920 } 10921 10922 // Check whether the receiver is captured by any of the arguments. 10923 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 10924 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 10925 return diagnoseRetainCycle(*this, capturer, owner); 10926 } 10927 10928 /// Check a property assign to see if it's likely to cause a retain cycle. 10929 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 10930 RetainCycleOwner owner; 10931 if (!findRetainCycleOwner(*this, receiver, owner)) 10932 return; 10933 10934 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 10935 diagnoseRetainCycle(*this, capturer, owner); 10936 } 10937 10938 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 10939 RetainCycleOwner Owner; 10940 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 10941 return; 10942 10943 // Because we don't have an expression for the variable, we have to set the 10944 // location explicitly here. 10945 Owner.Loc = Var->getLocation(); 10946 Owner.Range = Var->getSourceRange(); 10947 10948 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 10949 diagnoseRetainCycle(*this, Capturer, Owner); 10950 } 10951 10952 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 10953 Expr *RHS, bool isProperty) { 10954 // Check if RHS is an Objective-C object literal, which also can get 10955 // immediately zapped in a weak reference. Note that we explicitly 10956 // allow ObjCStringLiterals, since those are designed to never really die. 10957 RHS = RHS->IgnoreParenImpCasts(); 10958 10959 // This enum needs to match with the 'select' in 10960 // warn_objc_arc_literal_assign (off-by-1). 10961 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 10962 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 10963 return false; 10964 10965 S.Diag(Loc, diag::warn_arc_literal_assign) 10966 << (unsigned) Kind 10967 << (isProperty ? 0 : 1) 10968 << RHS->getSourceRange(); 10969 10970 return true; 10971 } 10972 10973 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 10974 Qualifiers::ObjCLifetime LT, 10975 Expr *RHS, bool isProperty) { 10976 // Strip off any implicit cast added to get to the one ARC-specific. 10977 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 10978 if (cast->getCastKind() == CK_ARCConsumeObject) { 10979 S.Diag(Loc, diag::warn_arc_retained_assign) 10980 << (LT == Qualifiers::OCL_ExplicitNone) 10981 << (isProperty ? 0 : 1) 10982 << RHS->getSourceRange(); 10983 return true; 10984 } 10985 RHS = cast->getSubExpr(); 10986 } 10987 10988 if (LT == Qualifiers::OCL_Weak && 10989 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 10990 return true; 10991 10992 return false; 10993 } 10994 10995 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 10996 QualType LHS, Expr *RHS) { 10997 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 10998 10999 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 11000 return false; 11001 11002 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 11003 return true; 11004 11005 return false; 11006 } 11007 11008 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 11009 Expr *LHS, Expr *RHS) { 11010 QualType LHSType; 11011 // PropertyRef on LHS type need be directly obtained from 11012 // its declaration as it has a PseudoType. 11013 ObjCPropertyRefExpr *PRE 11014 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 11015 if (PRE && !PRE->isImplicitProperty()) { 11016 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11017 if (PD) 11018 LHSType = PD->getType(); 11019 } 11020 11021 if (LHSType.isNull()) 11022 LHSType = LHS->getType(); 11023 11024 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 11025 11026 if (LT == Qualifiers::OCL_Weak) { 11027 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 11028 getCurFunction()->markSafeWeakUse(LHS); 11029 } 11030 11031 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 11032 return; 11033 11034 // FIXME. Check for other life times. 11035 if (LT != Qualifiers::OCL_None) 11036 return; 11037 11038 if (PRE) { 11039 if (PRE->isImplicitProperty()) 11040 return; 11041 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 11042 if (!PD) 11043 return; 11044 11045 unsigned Attributes = PD->getPropertyAttributes(); 11046 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 11047 // when 'assign' attribute was not explicitly specified 11048 // by user, ignore it and rely on property type itself 11049 // for lifetime info. 11050 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 11051 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 11052 LHSType->isObjCRetainableType()) 11053 return; 11054 11055 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 11056 if (cast->getCastKind() == CK_ARCConsumeObject) { 11057 Diag(Loc, diag::warn_arc_retained_property_assign) 11058 << RHS->getSourceRange(); 11059 return; 11060 } 11061 RHS = cast->getSubExpr(); 11062 } 11063 } 11064 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 11065 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 11066 return; 11067 } 11068 } 11069 } 11070 11071 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 11072 11073 namespace { 11074 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 11075 SourceLocation StmtLoc, 11076 const NullStmt *Body) { 11077 // Do not warn if the body is a macro that expands to nothing, e.g: 11078 // 11079 // #define CALL(x) 11080 // if (condition) 11081 // CALL(0); 11082 // 11083 if (Body->hasLeadingEmptyMacro()) 11084 return false; 11085 11086 // Get line numbers of statement and body. 11087 bool StmtLineInvalid; 11088 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 11089 &StmtLineInvalid); 11090 if (StmtLineInvalid) 11091 return false; 11092 11093 bool BodyLineInvalid; 11094 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 11095 &BodyLineInvalid); 11096 if (BodyLineInvalid) 11097 return false; 11098 11099 // Warn if null statement and body are on the same line. 11100 if (StmtLine != BodyLine) 11101 return false; 11102 11103 return true; 11104 } 11105 } // end anonymous namespace 11106 11107 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 11108 const Stmt *Body, 11109 unsigned DiagID) { 11110 // Since this is a syntactic check, don't emit diagnostic for template 11111 // instantiations, this just adds noise. 11112 if (CurrentInstantiationScope) 11113 return; 11114 11115 // The body should be a null statement. 11116 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11117 if (!NBody) 11118 return; 11119 11120 // Do the usual checks. 11121 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11122 return; 11123 11124 Diag(NBody->getSemiLoc(), DiagID); 11125 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11126 } 11127 11128 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 11129 const Stmt *PossibleBody) { 11130 assert(!CurrentInstantiationScope); // Ensured by caller 11131 11132 SourceLocation StmtLoc; 11133 const Stmt *Body; 11134 unsigned DiagID; 11135 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 11136 StmtLoc = FS->getRParenLoc(); 11137 Body = FS->getBody(); 11138 DiagID = diag::warn_empty_for_body; 11139 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 11140 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 11141 Body = WS->getBody(); 11142 DiagID = diag::warn_empty_while_body; 11143 } else 11144 return; // Neither `for' nor `while'. 11145 11146 // The body should be a null statement. 11147 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 11148 if (!NBody) 11149 return; 11150 11151 // Skip expensive checks if diagnostic is disabled. 11152 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 11153 return; 11154 11155 // Do the usual checks. 11156 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 11157 return; 11158 11159 // `for(...);' and `while(...);' are popular idioms, so in order to keep 11160 // noise level low, emit diagnostics only if for/while is followed by a 11161 // CompoundStmt, e.g.: 11162 // for (int i = 0; i < n; i++); 11163 // { 11164 // a(i); 11165 // } 11166 // or if for/while is followed by a statement with more indentation 11167 // than for/while itself: 11168 // for (int i = 0; i < n; i++); 11169 // a(i); 11170 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 11171 if (!ProbableTypo) { 11172 bool BodyColInvalid; 11173 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 11174 PossibleBody->getLocStart(), 11175 &BodyColInvalid); 11176 if (BodyColInvalid) 11177 return; 11178 11179 bool StmtColInvalid; 11180 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 11181 S->getLocStart(), 11182 &StmtColInvalid); 11183 if (StmtColInvalid) 11184 return; 11185 11186 if (BodyCol > StmtCol) 11187 ProbableTypo = true; 11188 } 11189 11190 if (ProbableTypo) { 11191 Diag(NBody->getSemiLoc(), DiagID); 11192 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 11193 } 11194 } 11195 11196 //===--- CHECK: Warn on self move with std::move. -------------------------===// 11197 11198 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 11199 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 11200 SourceLocation OpLoc) { 11201 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 11202 return; 11203 11204 if (!ActiveTemplateInstantiations.empty()) 11205 return; 11206 11207 // Strip parens and casts away. 11208 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11209 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11210 11211 // Check for a call expression 11212 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 11213 if (!CE || CE->getNumArgs() != 1) 11214 return; 11215 11216 // Check for a call to std::move 11217 const FunctionDecl *FD = CE->getDirectCallee(); 11218 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() || 11219 !FD->getIdentifier()->isStr("move")) 11220 return; 11221 11222 // Get argument from std::move 11223 RHSExpr = CE->getArg(0); 11224 11225 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11226 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11227 11228 // Two DeclRefExpr's, check that the decls are the same. 11229 if (LHSDeclRef && RHSDeclRef) { 11230 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11231 return; 11232 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11233 RHSDeclRef->getDecl()->getCanonicalDecl()) 11234 return; 11235 11236 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11237 << LHSExpr->getSourceRange() 11238 << RHSExpr->getSourceRange(); 11239 return; 11240 } 11241 11242 // Member variables require a different approach to check for self moves. 11243 // MemberExpr's are the same if every nested MemberExpr refers to the same 11244 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 11245 // the base Expr's are CXXThisExpr's. 11246 const Expr *LHSBase = LHSExpr; 11247 const Expr *RHSBase = RHSExpr; 11248 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 11249 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 11250 if (!LHSME || !RHSME) 11251 return; 11252 11253 while (LHSME && RHSME) { 11254 if (LHSME->getMemberDecl()->getCanonicalDecl() != 11255 RHSME->getMemberDecl()->getCanonicalDecl()) 11256 return; 11257 11258 LHSBase = LHSME->getBase(); 11259 RHSBase = RHSME->getBase(); 11260 LHSME = dyn_cast<MemberExpr>(LHSBase); 11261 RHSME = dyn_cast<MemberExpr>(RHSBase); 11262 } 11263 11264 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 11265 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 11266 if (LHSDeclRef && RHSDeclRef) { 11267 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 11268 return; 11269 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 11270 RHSDeclRef->getDecl()->getCanonicalDecl()) 11271 return; 11272 11273 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11274 << LHSExpr->getSourceRange() 11275 << RHSExpr->getSourceRange(); 11276 return; 11277 } 11278 11279 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 11280 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 11281 << LHSExpr->getSourceRange() 11282 << RHSExpr->getSourceRange(); 11283 } 11284 11285 //===--- Layout compatibility ----------------------------------------------// 11286 11287 namespace { 11288 11289 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 11290 11291 /// \brief Check if two enumeration types are layout-compatible. 11292 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 11293 // C++11 [dcl.enum] p8: 11294 // Two enumeration types are layout-compatible if they have the same 11295 // underlying type. 11296 return ED1->isComplete() && ED2->isComplete() && 11297 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 11298 } 11299 11300 /// \brief Check if two fields are layout-compatible. 11301 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 11302 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 11303 return false; 11304 11305 if (Field1->isBitField() != Field2->isBitField()) 11306 return false; 11307 11308 if (Field1->isBitField()) { 11309 // Make sure that the bit-fields are the same length. 11310 unsigned Bits1 = Field1->getBitWidthValue(C); 11311 unsigned Bits2 = Field2->getBitWidthValue(C); 11312 11313 if (Bits1 != Bits2) 11314 return false; 11315 } 11316 11317 return true; 11318 } 11319 11320 /// \brief Check if two standard-layout structs are layout-compatible. 11321 /// (C++11 [class.mem] p17) 11322 bool isLayoutCompatibleStruct(ASTContext &C, 11323 RecordDecl *RD1, 11324 RecordDecl *RD2) { 11325 // If both records are C++ classes, check that base classes match. 11326 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 11327 // If one of records is a CXXRecordDecl we are in C++ mode, 11328 // thus the other one is a CXXRecordDecl, too. 11329 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 11330 // Check number of base classes. 11331 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 11332 return false; 11333 11334 // Check the base classes. 11335 for (CXXRecordDecl::base_class_const_iterator 11336 Base1 = D1CXX->bases_begin(), 11337 BaseEnd1 = D1CXX->bases_end(), 11338 Base2 = D2CXX->bases_begin(); 11339 Base1 != BaseEnd1; 11340 ++Base1, ++Base2) { 11341 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 11342 return false; 11343 } 11344 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 11345 // If only RD2 is a C++ class, it should have zero base classes. 11346 if (D2CXX->getNumBases() > 0) 11347 return false; 11348 } 11349 11350 // Check the fields. 11351 RecordDecl::field_iterator Field2 = RD2->field_begin(), 11352 Field2End = RD2->field_end(), 11353 Field1 = RD1->field_begin(), 11354 Field1End = RD1->field_end(); 11355 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 11356 if (!isLayoutCompatible(C, *Field1, *Field2)) 11357 return false; 11358 } 11359 if (Field1 != Field1End || Field2 != Field2End) 11360 return false; 11361 11362 return true; 11363 } 11364 11365 /// \brief Check if two standard-layout unions are layout-compatible. 11366 /// (C++11 [class.mem] p18) 11367 bool isLayoutCompatibleUnion(ASTContext &C, 11368 RecordDecl *RD1, 11369 RecordDecl *RD2) { 11370 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 11371 for (auto *Field2 : RD2->fields()) 11372 UnmatchedFields.insert(Field2); 11373 11374 for (auto *Field1 : RD1->fields()) { 11375 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 11376 I = UnmatchedFields.begin(), 11377 E = UnmatchedFields.end(); 11378 11379 for ( ; I != E; ++I) { 11380 if (isLayoutCompatible(C, Field1, *I)) { 11381 bool Result = UnmatchedFields.erase(*I); 11382 (void) Result; 11383 assert(Result); 11384 break; 11385 } 11386 } 11387 if (I == E) 11388 return false; 11389 } 11390 11391 return UnmatchedFields.empty(); 11392 } 11393 11394 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 11395 if (RD1->isUnion() != RD2->isUnion()) 11396 return false; 11397 11398 if (RD1->isUnion()) 11399 return isLayoutCompatibleUnion(C, RD1, RD2); 11400 else 11401 return isLayoutCompatibleStruct(C, RD1, RD2); 11402 } 11403 11404 /// \brief Check if two types are layout-compatible in C++11 sense. 11405 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 11406 if (T1.isNull() || T2.isNull()) 11407 return false; 11408 11409 // C++11 [basic.types] p11: 11410 // If two types T1 and T2 are the same type, then T1 and T2 are 11411 // layout-compatible types. 11412 if (C.hasSameType(T1, T2)) 11413 return true; 11414 11415 T1 = T1.getCanonicalType().getUnqualifiedType(); 11416 T2 = T2.getCanonicalType().getUnqualifiedType(); 11417 11418 const Type::TypeClass TC1 = T1->getTypeClass(); 11419 const Type::TypeClass TC2 = T2->getTypeClass(); 11420 11421 if (TC1 != TC2) 11422 return false; 11423 11424 if (TC1 == Type::Enum) { 11425 return isLayoutCompatible(C, 11426 cast<EnumType>(T1)->getDecl(), 11427 cast<EnumType>(T2)->getDecl()); 11428 } else if (TC1 == Type::Record) { 11429 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 11430 return false; 11431 11432 return isLayoutCompatible(C, 11433 cast<RecordType>(T1)->getDecl(), 11434 cast<RecordType>(T2)->getDecl()); 11435 } 11436 11437 return false; 11438 } 11439 } // end anonymous namespace 11440 11441 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 11442 11443 namespace { 11444 /// \brief Given a type tag expression find the type tag itself. 11445 /// 11446 /// \param TypeExpr Type tag expression, as it appears in user's code. 11447 /// 11448 /// \param VD Declaration of an identifier that appears in a type tag. 11449 /// 11450 /// \param MagicValue Type tag magic value. 11451 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 11452 const ValueDecl **VD, uint64_t *MagicValue) { 11453 while(true) { 11454 if (!TypeExpr) 11455 return false; 11456 11457 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 11458 11459 switch (TypeExpr->getStmtClass()) { 11460 case Stmt::UnaryOperatorClass: { 11461 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 11462 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 11463 TypeExpr = UO->getSubExpr(); 11464 continue; 11465 } 11466 return false; 11467 } 11468 11469 case Stmt::DeclRefExprClass: { 11470 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 11471 *VD = DRE->getDecl(); 11472 return true; 11473 } 11474 11475 case Stmt::IntegerLiteralClass: { 11476 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 11477 llvm::APInt MagicValueAPInt = IL->getValue(); 11478 if (MagicValueAPInt.getActiveBits() <= 64) { 11479 *MagicValue = MagicValueAPInt.getZExtValue(); 11480 return true; 11481 } else 11482 return false; 11483 } 11484 11485 case Stmt::BinaryConditionalOperatorClass: 11486 case Stmt::ConditionalOperatorClass: { 11487 const AbstractConditionalOperator *ACO = 11488 cast<AbstractConditionalOperator>(TypeExpr); 11489 bool Result; 11490 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 11491 if (Result) 11492 TypeExpr = ACO->getTrueExpr(); 11493 else 11494 TypeExpr = ACO->getFalseExpr(); 11495 continue; 11496 } 11497 return false; 11498 } 11499 11500 case Stmt::BinaryOperatorClass: { 11501 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 11502 if (BO->getOpcode() == BO_Comma) { 11503 TypeExpr = BO->getRHS(); 11504 continue; 11505 } 11506 return false; 11507 } 11508 11509 default: 11510 return false; 11511 } 11512 } 11513 } 11514 11515 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 11516 /// 11517 /// \param TypeExpr Expression that specifies a type tag. 11518 /// 11519 /// \param MagicValues Registered magic values. 11520 /// 11521 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 11522 /// kind. 11523 /// 11524 /// \param TypeInfo Information about the corresponding C type. 11525 /// 11526 /// \returns true if the corresponding C type was found. 11527 bool GetMatchingCType( 11528 const IdentifierInfo *ArgumentKind, 11529 const Expr *TypeExpr, const ASTContext &Ctx, 11530 const llvm::DenseMap<Sema::TypeTagMagicValue, 11531 Sema::TypeTagData> *MagicValues, 11532 bool &FoundWrongKind, 11533 Sema::TypeTagData &TypeInfo) { 11534 FoundWrongKind = false; 11535 11536 // Variable declaration that has type_tag_for_datatype attribute. 11537 const ValueDecl *VD = nullptr; 11538 11539 uint64_t MagicValue; 11540 11541 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 11542 return false; 11543 11544 if (VD) { 11545 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 11546 if (I->getArgumentKind() != ArgumentKind) { 11547 FoundWrongKind = true; 11548 return false; 11549 } 11550 TypeInfo.Type = I->getMatchingCType(); 11551 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 11552 TypeInfo.MustBeNull = I->getMustBeNull(); 11553 return true; 11554 } 11555 return false; 11556 } 11557 11558 if (!MagicValues) 11559 return false; 11560 11561 llvm::DenseMap<Sema::TypeTagMagicValue, 11562 Sema::TypeTagData>::const_iterator I = 11563 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 11564 if (I == MagicValues->end()) 11565 return false; 11566 11567 TypeInfo = I->second; 11568 return true; 11569 } 11570 } // end anonymous namespace 11571 11572 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 11573 uint64_t MagicValue, QualType Type, 11574 bool LayoutCompatible, 11575 bool MustBeNull) { 11576 if (!TypeTagForDatatypeMagicValues) 11577 TypeTagForDatatypeMagicValues.reset( 11578 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 11579 11580 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 11581 (*TypeTagForDatatypeMagicValues)[Magic] = 11582 TypeTagData(Type, LayoutCompatible, MustBeNull); 11583 } 11584 11585 namespace { 11586 bool IsSameCharType(QualType T1, QualType T2) { 11587 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 11588 if (!BT1) 11589 return false; 11590 11591 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 11592 if (!BT2) 11593 return false; 11594 11595 BuiltinType::Kind T1Kind = BT1->getKind(); 11596 BuiltinType::Kind T2Kind = BT2->getKind(); 11597 11598 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 11599 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 11600 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 11601 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 11602 } 11603 } // end anonymous namespace 11604 11605 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 11606 const Expr * const *ExprArgs) { 11607 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 11608 bool IsPointerAttr = Attr->getIsPointer(); 11609 11610 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 11611 bool FoundWrongKind; 11612 TypeTagData TypeInfo; 11613 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 11614 TypeTagForDatatypeMagicValues.get(), 11615 FoundWrongKind, TypeInfo)) { 11616 if (FoundWrongKind) 11617 Diag(TypeTagExpr->getExprLoc(), 11618 diag::warn_type_tag_for_datatype_wrong_kind) 11619 << TypeTagExpr->getSourceRange(); 11620 return; 11621 } 11622 11623 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 11624 if (IsPointerAttr) { 11625 // Skip implicit cast of pointer to `void *' (as a function argument). 11626 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 11627 if (ICE->getType()->isVoidPointerType() && 11628 ICE->getCastKind() == CK_BitCast) 11629 ArgumentExpr = ICE->getSubExpr(); 11630 } 11631 QualType ArgumentType = ArgumentExpr->getType(); 11632 11633 // Passing a `void*' pointer shouldn't trigger a warning. 11634 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 11635 return; 11636 11637 if (TypeInfo.MustBeNull) { 11638 // Type tag with matching void type requires a null pointer. 11639 if (!ArgumentExpr->isNullPointerConstant(Context, 11640 Expr::NPC_ValueDependentIsNotNull)) { 11641 Diag(ArgumentExpr->getExprLoc(), 11642 diag::warn_type_safety_null_pointer_required) 11643 << ArgumentKind->getName() 11644 << ArgumentExpr->getSourceRange() 11645 << TypeTagExpr->getSourceRange(); 11646 } 11647 return; 11648 } 11649 11650 QualType RequiredType = TypeInfo.Type; 11651 if (IsPointerAttr) 11652 RequiredType = Context.getPointerType(RequiredType); 11653 11654 bool mismatch = false; 11655 if (!TypeInfo.LayoutCompatible) { 11656 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 11657 11658 // C++11 [basic.fundamental] p1: 11659 // Plain char, signed char, and unsigned char are three distinct types. 11660 // 11661 // But we treat plain `char' as equivalent to `signed char' or `unsigned 11662 // char' depending on the current char signedness mode. 11663 if (mismatch) 11664 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 11665 RequiredType->getPointeeType())) || 11666 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 11667 mismatch = false; 11668 } else 11669 if (IsPointerAttr) 11670 mismatch = !isLayoutCompatible(Context, 11671 ArgumentType->getPointeeType(), 11672 RequiredType->getPointeeType()); 11673 else 11674 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 11675 11676 if (mismatch) 11677 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 11678 << ArgumentType << ArgumentKind 11679 << TypeInfo.LayoutCompatible << RequiredType 11680 << ArgumentExpr->getSourceRange() 11681 << TypeTagExpr->getSourceRange(); 11682 } 11683 11684 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 11685 CharUnits Alignment) { 11686 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 11687 } 11688 11689 void Sema::DiagnoseMisalignedMembers() { 11690 for (MisalignedMember &m : MisalignedMembers) { 11691 const NamedDecl *ND = m.RD; 11692 if (ND->getName().empty()) { 11693 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 11694 ND = TD; 11695 } 11696 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 11697 << m.MD << ND << m.E->getSourceRange(); 11698 } 11699 MisalignedMembers.clear(); 11700 } 11701 11702 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 11703 E = E->IgnoreParens(); 11704 if (!T->isPointerType() && !T->isIntegerType()) 11705 return; 11706 if (isa<UnaryOperator>(E) && 11707 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 11708 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 11709 if (isa<MemberExpr>(Op)) { 11710 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 11711 MisalignedMember(Op)); 11712 if (MA != MisalignedMembers.end() && 11713 (T->isIntegerType() || 11714 (T->isPointerType() && 11715 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment))) 11716 MisalignedMembers.erase(MA); 11717 } 11718 } 11719 } 11720 11721 void Sema::RefersToMemberWithReducedAlignment( 11722 Expr *E, 11723 std::function<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action) { 11724 const auto *ME = dyn_cast<MemberExpr>(E); 11725 if (!ME) 11726 return; 11727 11728 // For a chain of MemberExpr like "a.b.c.d" this list 11729 // will keep FieldDecl's like [d, c, b]. 11730 SmallVector<FieldDecl *, 4> ReverseMemberChain; 11731 const MemberExpr *TopME = nullptr; 11732 bool AnyIsPacked = false; 11733 do { 11734 QualType BaseType = ME->getBase()->getType(); 11735 if (ME->isArrow()) 11736 BaseType = BaseType->getPointeeType(); 11737 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 11738 11739 ValueDecl *MD = ME->getMemberDecl(); 11740 auto *FD = dyn_cast<FieldDecl>(MD); 11741 // We do not care about non-data members. 11742 if (!FD || FD->isInvalidDecl()) 11743 return; 11744 11745 AnyIsPacked = 11746 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 11747 ReverseMemberChain.push_back(FD); 11748 11749 TopME = ME; 11750 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 11751 } while (ME); 11752 assert(TopME && "We did not compute a topmost MemberExpr!"); 11753 11754 // Not the scope of this diagnostic. 11755 if (!AnyIsPacked) 11756 return; 11757 11758 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 11759 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 11760 // TODO: The innermost base of the member expression may be too complicated. 11761 // For now, just disregard these cases. This is left for future 11762 // improvement. 11763 if (!DRE && !isa<CXXThisExpr>(TopBase)) 11764 return; 11765 11766 // Alignment expected by the whole expression. 11767 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 11768 11769 // No need to do anything else with this case. 11770 if (ExpectedAlignment.isOne()) 11771 return; 11772 11773 // Synthesize offset of the whole access. 11774 CharUnits Offset; 11775 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 11776 I++) { 11777 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 11778 } 11779 11780 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 11781 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 11782 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 11783 11784 // The base expression of the innermost MemberExpr may give 11785 // stronger guarantees than the class containing the member. 11786 if (DRE && !TopME->isArrow()) { 11787 const ValueDecl *VD = DRE->getDecl(); 11788 if (!VD->getType()->isReferenceType()) 11789 CompleteObjectAlignment = 11790 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 11791 } 11792 11793 // Check if the synthesized offset fulfills the alignment. 11794 if (Offset % ExpectedAlignment != 0 || 11795 // It may fulfill the offset it but the effective alignment may still be 11796 // lower than the expected expression alignment. 11797 CompleteObjectAlignment < ExpectedAlignment) { 11798 // If this happens, we want to determine a sensible culprit of this. 11799 // Intuitively, watching the chain of member expressions from right to 11800 // left, we start with the required alignment (as required by the field 11801 // type) but some packed attribute in that chain has reduced the alignment. 11802 // It may happen that another packed structure increases it again. But if 11803 // we are here such increase has not been enough. So pointing the first 11804 // FieldDecl that either is packed or else its RecordDecl is, 11805 // seems reasonable. 11806 FieldDecl *FD = nullptr; 11807 CharUnits Alignment; 11808 for (FieldDecl *FDI : ReverseMemberChain) { 11809 if (FDI->hasAttr<PackedAttr>() || 11810 FDI->getParent()->hasAttr<PackedAttr>()) { 11811 FD = FDI; 11812 Alignment = std::min( 11813 Context.getTypeAlignInChars(FD->getType()), 11814 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 11815 break; 11816 } 11817 } 11818 assert(FD && "We did not find a packed FieldDecl!"); 11819 Action(E, FD->getParent(), FD, Alignment); 11820 } 11821 } 11822 11823 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 11824 using namespace std::placeholders; 11825 RefersToMemberWithReducedAlignment( 11826 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 11827 _2, _3, _4)); 11828 } 11829 11830