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