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