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