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