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