SemaChecking.cpp revision 5f8d604246976a93a73549b07bbc8ee0b2061b50
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/Initialization.h" 16#include "clang/Sema/Sema.h" 17#include "clang/Sema/SemaInternal.h" 18#include "clang/Sema/ScopeInfo.h" 19#include "clang/Analysis/Analyses/FormatString.h" 20#include "clang/AST/ASTContext.h" 21#include "clang/AST/CharUnits.h" 22#include "clang/AST/DeclCXX.h" 23#include "clang/AST/DeclObjC.h" 24#include "clang/AST/ExprCXX.h" 25#include "clang/AST/ExprObjC.h" 26#include "clang/AST/EvaluatedExprVisitor.h" 27#include "clang/AST/DeclObjC.h" 28#include "clang/AST/StmtCXX.h" 29#include "clang/AST/StmtObjC.h" 30#include "clang/Lex/Preprocessor.h" 31#include "llvm/ADT/BitVector.h" 32#include "llvm/ADT/STLExtras.h" 33#include "llvm/Support/raw_ostream.h" 34#include "clang/Basic/TargetBuiltins.h" 35#include "clang/Basic/TargetInfo.h" 36#include "clang/Basic/ConvertUTF.h" 37#include <limits> 38using namespace clang; 39using namespace sema; 40 41SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 42 unsigned ByteNo) const { 43 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(), 44 PP.getLangOptions(), PP.getTargetInfo()); 45} 46 47 48/// CheckablePrintfAttr - does a function call have a "printf" attribute 49/// and arguments that merit checking? 50bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) { 51 if (Format->getType() == "printf") return true; 52 if (Format->getType() == "printf0") { 53 // printf0 allows null "format" string; if so don't check format/args 54 unsigned format_idx = Format->getFormatIdx() - 1; 55 // Does the index refer to the implicit object argument? 56 if (isa<CXXMemberCallExpr>(TheCall)) { 57 if (format_idx == 0) 58 return false; 59 --format_idx; 60 } 61 if (format_idx < TheCall->getNumArgs()) { 62 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts(); 63 if (!Format->isNullPointerConstant(Context, 64 Expr::NPC_ValueDependentIsNull)) 65 return true; 66 } 67 } 68 return false; 69} 70 71/// Checks that a call expression's argument count is the desired number. 72/// This is useful when doing custom type-checking. Returns true on error. 73static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 74 unsigned argCount = call->getNumArgs(); 75 if (argCount == desiredArgCount) return false; 76 77 if (argCount < desiredArgCount) 78 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 79 << 0 /*function call*/ << desiredArgCount << argCount 80 << call->getSourceRange(); 81 82 // Highlight all the excess arguments. 83 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 84 call->getArg(argCount - 1)->getLocEnd()); 85 86 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 87 << 0 /*function call*/ << desiredArgCount << argCount 88 << call->getArg(1)->getSourceRange(); 89} 90 91ExprResult 92Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 93 ExprResult TheCallResult(Owned(TheCall)); 94 95 // Find out if any arguments are required to be integer constant expressions. 96 unsigned ICEArguments = 0; 97 ASTContext::GetBuiltinTypeError Error; 98 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 99 if (Error != ASTContext::GE_None) 100 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 101 102 // If any arguments are required to be ICE's, check and diagnose. 103 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 104 // Skip arguments not required to be ICE's. 105 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 106 107 llvm::APSInt Result; 108 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 109 return true; 110 ICEArguments &= ~(1 << ArgNo); 111 } 112 113 switch (BuiltinID) { 114 case Builtin::BI__builtin___CFStringMakeConstantString: 115 assert(TheCall->getNumArgs() == 1 && 116 "Wrong # arguments to builtin CFStringMakeConstantString"); 117 if (CheckObjCString(TheCall->getArg(0))) 118 return ExprError(); 119 break; 120 case Builtin::BI__builtin_stdarg_start: 121 case Builtin::BI__builtin_va_start: 122 if (SemaBuiltinVAStart(TheCall)) 123 return ExprError(); 124 break; 125 case Builtin::BI__builtin_isgreater: 126 case Builtin::BI__builtin_isgreaterequal: 127 case Builtin::BI__builtin_isless: 128 case Builtin::BI__builtin_islessequal: 129 case Builtin::BI__builtin_islessgreater: 130 case Builtin::BI__builtin_isunordered: 131 if (SemaBuiltinUnorderedCompare(TheCall)) 132 return ExprError(); 133 break; 134 case Builtin::BI__builtin_fpclassify: 135 if (SemaBuiltinFPClassification(TheCall, 6)) 136 return ExprError(); 137 break; 138 case Builtin::BI__builtin_isfinite: 139 case Builtin::BI__builtin_isinf: 140 case Builtin::BI__builtin_isinf_sign: 141 case Builtin::BI__builtin_isnan: 142 case Builtin::BI__builtin_isnormal: 143 if (SemaBuiltinFPClassification(TheCall, 1)) 144 return ExprError(); 145 break; 146 case Builtin::BI__builtin_shufflevector: 147 return SemaBuiltinShuffleVector(TheCall); 148 // TheCall will be freed by the smart pointer here, but that's fine, since 149 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 150 case Builtin::BI__builtin_prefetch: 151 if (SemaBuiltinPrefetch(TheCall)) 152 return ExprError(); 153 break; 154 case Builtin::BI__builtin_object_size: 155 if (SemaBuiltinObjectSize(TheCall)) 156 return ExprError(); 157 break; 158 case Builtin::BI__builtin_longjmp: 159 if (SemaBuiltinLongjmp(TheCall)) 160 return ExprError(); 161 break; 162 163 case Builtin::BI__builtin_classify_type: 164 if (checkArgCount(*this, TheCall, 1)) return true; 165 TheCall->setType(Context.IntTy); 166 break; 167 case Builtin::BI__builtin_constant_p: 168 if (checkArgCount(*this, TheCall, 1)) return true; 169 TheCall->setType(Context.IntTy); 170 break; 171 case Builtin::BI__sync_fetch_and_add: 172 case Builtin::BI__sync_fetch_and_sub: 173 case Builtin::BI__sync_fetch_and_or: 174 case Builtin::BI__sync_fetch_and_and: 175 case Builtin::BI__sync_fetch_and_xor: 176 case Builtin::BI__sync_add_and_fetch: 177 case Builtin::BI__sync_sub_and_fetch: 178 case Builtin::BI__sync_and_and_fetch: 179 case Builtin::BI__sync_or_and_fetch: 180 case Builtin::BI__sync_xor_and_fetch: 181 case Builtin::BI__sync_val_compare_and_swap: 182 case Builtin::BI__sync_bool_compare_and_swap: 183 case Builtin::BI__sync_lock_test_and_set: 184 case Builtin::BI__sync_lock_release: 185 case Builtin::BI__sync_swap: 186 return SemaBuiltinAtomicOverloaded(move(TheCallResult)); 187 } 188 189 // Since the target specific builtins for each arch overlap, only check those 190 // of the arch we are compiling for. 191 if (BuiltinID >= Builtin::FirstTSBuiltin) { 192 switch (Context.Target.getTriple().getArch()) { 193 case llvm::Triple::arm: 194 case llvm::Triple::thumb: 195 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 196 return ExprError(); 197 break; 198 default: 199 break; 200 } 201 } 202 203 return move(TheCallResult); 204} 205 206// Get the valid immediate range for the specified NEON type code. 207static unsigned RFT(unsigned t, bool shift = false) { 208 bool quad = t & 0x10; 209 210 switch (t & 0x7) { 211 case 0: // i8 212 return shift ? 7 : (8 << (int)quad) - 1; 213 case 1: // i16 214 return shift ? 15 : (4 << (int)quad) - 1; 215 case 2: // i32 216 return shift ? 31 : (2 << (int)quad) - 1; 217 case 3: // i64 218 return shift ? 63 : (1 << (int)quad) - 1; 219 case 4: // f32 220 assert(!shift && "cannot shift float types!"); 221 return (2 << (int)quad) - 1; 222 case 5: // poly8 223 return shift ? 7 : (8 << (int)quad) - 1; 224 case 6: // poly16 225 return shift ? 15 : (4 << (int)quad) - 1; 226 case 7: // float16 227 assert(!shift && "cannot shift float types!"); 228 return (4 << (int)quad) - 1; 229 } 230 return 0; 231} 232 233bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 234 llvm::APSInt Result; 235 236 unsigned mask = 0; 237 unsigned TV = 0; 238 switch (BuiltinID) { 239#define GET_NEON_OVERLOAD_CHECK 240#include "clang/Basic/arm_neon.inc" 241#undef GET_NEON_OVERLOAD_CHECK 242 } 243 244 // For NEON intrinsics which are overloaded on vector element type, validate 245 // the immediate which specifies which variant to emit. 246 if (mask) { 247 unsigned ArgNo = TheCall->getNumArgs()-1; 248 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 249 return true; 250 251 TV = Result.getLimitedValue(32); 252 if ((TV > 31) || (mask & (1 << TV)) == 0) 253 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 254 << TheCall->getArg(ArgNo)->getSourceRange(); 255 } 256 257 // For NEON intrinsics which take an immediate value as part of the 258 // instruction, range check them here. 259 unsigned i = 0, l = 0, u = 0; 260 switch (BuiltinID) { 261 default: return false; 262 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 263 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 264 case ARM::BI__builtin_arm_vcvtr_f: 265 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 266#define GET_NEON_IMMEDIATE_CHECK 267#include "clang/Basic/arm_neon.inc" 268#undef GET_NEON_IMMEDIATE_CHECK 269 }; 270 271 // Check that the immediate argument is actually a constant. 272 if (SemaBuiltinConstantArg(TheCall, i, Result)) 273 return true; 274 275 // Range check against the upper/lower values for this isntruction. 276 unsigned Val = Result.getZExtValue(); 277 if (Val < l || Val > (u + l)) 278 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 279 << l << u+l << TheCall->getArg(i)->getSourceRange(); 280 281 // FIXME: VFP Intrinsics should error if VFP not present. 282 return false; 283} 284 285/// CheckFunctionCall - Check a direct function call for various correctness 286/// and safety properties not strictly enforced by the C type system. 287bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) { 288 // Get the IdentifierInfo* for the called function. 289 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 290 291 // None of the checks below are needed for functions that don't have 292 // simple names (e.g., C++ conversion functions). 293 if (!FnInfo) 294 return false; 295 296 // FIXME: This mechanism should be abstracted to be less fragile and 297 // more efficient. For example, just map function ids to custom 298 // handlers. 299 300 // Printf and scanf checking. 301 for (specific_attr_iterator<FormatAttr> 302 i = FDecl->specific_attr_begin<FormatAttr>(), 303 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) { 304 305 const FormatAttr *Format = *i; 306 const bool b = Format->getType() == "scanf"; 307 if (b || CheckablePrintfAttr(Format, TheCall)) { 308 bool HasVAListArg = Format->getFirstArg() == 0; 309 CheckPrintfScanfArguments(TheCall, HasVAListArg, 310 Format->getFormatIdx() - 1, 311 HasVAListArg ? 0 : Format->getFirstArg() - 1, 312 !b); 313 } 314 } 315 316 for (specific_attr_iterator<NonNullAttr> 317 i = FDecl->specific_attr_begin<NonNullAttr>(), 318 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) { 319 CheckNonNullArguments(*i, TheCall->getArgs(), 320 TheCall->getCallee()->getLocStart()); 321 } 322 323 // Builtin handling 324 int CMF = -1; 325 switch (FDecl->getBuiltinID()) { 326 case Builtin::BI__builtin_memset: 327 case Builtin::BI__builtin___memset_chk: 328 case Builtin::BImemset: 329 CMF = CMF_Memset; 330 break; 331 332 case Builtin::BI__builtin_memcpy: 333 case Builtin::BI__builtin___memcpy_chk: 334 case Builtin::BImemcpy: 335 CMF = CMF_Memcpy; 336 break; 337 338 case Builtin::BI__builtin_memmove: 339 case Builtin::BI__builtin___memmove_chk: 340 case Builtin::BImemmove: 341 CMF = CMF_Memmove; 342 break; 343 344 case Builtin::BIstrlcpy: 345 case Builtin::BIstrlcat: 346 CheckStrlcpycatArguments(TheCall, FnInfo); 347 break; 348 349 case Builtin::BI__builtin_memcmp: 350 CMF = CMF_Memcmp; 351 break; 352 353 default: 354 if (FDecl->getLinkage() == ExternalLinkage && 355 (!getLangOptions().CPlusPlus || FDecl->isExternC())) { 356 if (FnInfo->isStr("memset")) 357 CMF = CMF_Memset; 358 else if (FnInfo->isStr("memcpy")) 359 CMF = CMF_Memcpy; 360 else if (FnInfo->isStr("memmove")) 361 CMF = CMF_Memmove; 362 else if (FnInfo->isStr("memcmp")) 363 CMF = CMF_Memcmp; 364 } 365 break; 366 } 367 368 // Memset/memcpy/memmove handling 369 if (CMF != -1) 370 CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo); 371 372 return false; 373} 374 375bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) { 376 // Printf checking. 377 const FormatAttr *Format = NDecl->getAttr<FormatAttr>(); 378 if (!Format) 379 return false; 380 381 const VarDecl *V = dyn_cast<VarDecl>(NDecl); 382 if (!V) 383 return false; 384 385 QualType Ty = V->getType(); 386 if (!Ty->isBlockPointerType()) 387 return false; 388 389 const bool b = Format->getType() == "scanf"; 390 if (!b && !CheckablePrintfAttr(Format, TheCall)) 391 return false; 392 393 bool HasVAListArg = Format->getFirstArg() == 0; 394 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1, 395 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b); 396 397 return false; 398} 399 400/// checkBuiltinArgument - Given a call to a builtin function, perform 401/// normal type-checking on the given argument, updating the call in 402/// place. This is useful when a builtin function requires custom 403/// type-checking for some of its arguments but not necessarily all of 404/// them. 405/// 406/// Returns true on error. 407static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 408 FunctionDecl *Fn = E->getDirectCallee(); 409 assert(Fn && "builtin call without direct callee!"); 410 411 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 412 InitializedEntity Entity = 413 InitializedEntity::InitializeParameter(S.Context, Param); 414 415 ExprResult Arg = E->getArg(0); 416 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 417 if (Arg.isInvalid()) 418 return true; 419 420 E->setArg(ArgIndex, Arg.take()); 421 return false; 422} 423 424/// SemaBuiltinAtomicOverloaded - We have a call to a function like 425/// __sync_fetch_and_add, which is an overloaded function based on the pointer 426/// type of its first argument. The main ActOnCallExpr routines have already 427/// promoted the types of arguments because all of these calls are prototyped as 428/// void(...). 429/// 430/// This function goes through and does final semantic checking for these 431/// builtins, 432ExprResult 433Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 434 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 435 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 436 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 437 438 // Ensure that we have at least one argument to do type inference from. 439 if (TheCall->getNumArgs() < 1) { 440 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 441 << 0 << 1 << TheCall->getNumArgs() 442 << TheCall->getCallee()->getSourceRange(); 443 return ExprError(); 444 } 445 446 // Inspect the first argument of the atomic builtin. This should always be 447 // a pointer type, whose element is an integral scalar or pointer type. 448 // Because it is a pointer type, we don't have to worry about any implicit 449 // casts here. 450 // FIXME: We don't allow floating point scalars as input. 451 Expr *FirstArg = TheCall->getArg(0); 452 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 453 if (!pointerType) { 454 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 455 << FirstArg->getType() << FirstArg->getSourceRange(); 456 return ExprError(); 457 } 458 459 QualType ValType = pointerType->getPointeeType(); 460 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 461 !ValType->isBlockPointerType()) { 462 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 463 << FirstArg->getType() << FirstArg->getSourceRange(); 464 return ExprError(); 465 } 466 467 switch (ValType.getObjCLifetime()) { 468 case Qualifiers::OCL_None: 469 case Qualifiers::OCL_ExplicitNone: 470 // okay 471 break; 472 473 case Qualifiers::OCL_Weak: 474 case Qualifiers::OCL_Strong: 475 case Qualifiers::OCL_Autoreleasing: 476 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 477 << ValType << FirstArg->getSourceRange(); 478 return ExprError(); 479 } 480 481 // The majority of builtins return a value, but a few have special return 482 // types, so allow them to override appropriately below. 483 QualType ResultType = ValType; 484 485 // We need to figure out which concrete builtin this maps onto. For example, 486 // __sync_fetch_and_add with a 2 byte object turns into 487 // __sync_fetch_and_add_2. 488#define BUILTIN_ROW(x) \ 489 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 490 Builtin::BI##x##_8, Builtin::BI##x##_16 } 491 492 static const unsigned BuiltinIndices[][5] = { 493 BUILTIN_ROW(__sync_fetch_and_add), 494 BUILTIN_ROW(__sync_fetch_and_sub), 495 BUILTIN_ROW(__sync_fetch_and_or), 496 BUILTIN_ROW(__sync_fetch_and_and), 497 BUILTIN_ROW(__sync_fetch_and_xor), 498 499 BUILTIN_ROW(__sync_add_and_fetch), 500 BUILTIN_ROW(__sync_sub_and_fetch), 501 BUILTIN_ROW(__sync_and_and_fetch), 502 BUILTIN_ROW(__sync_or_and_fetch), 503 BUILTIN_ROW(__sync_xor_and_fetch), 504 505 BUILTIN_ROW(__sync_val_compare_and_swap), 506 BUILTIN_ROW(__sync_bool_compare_and_swap), 507 BUILTIN_ROW(__sync_lock_test_and_set), 508 BUILTIN_ROW(__sync_lock_release), 509 BUILTIN_ROW(__sync_swap) 510 }; 511#undef BUILTIN_ROW 512 513 // Determine the index of the size. 514 unsigned SizeIndex; 515 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 516 case 1: SizeIndex = 0; break; 517 case 2: SizeIndex = 1; break; 518 case 4: SizeIndex = 2; break; 519 case 8: SizeIndex = 3; break; 520 case 16: SizeIndex = 4; break; 521 default: 522 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 523 << FirstArg->getType() << FirstArg->getSourceRange(); 524 return ExprError(); 525 } 526 527 // Each of these builtins has one pointer argument, followed by some number of 528 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 529 // that we ignore. Find out which row of BuiltinIndices to read from as well 530 // as the number of fixed args. 531 unsigned BuiltinID = FDecl->getBuiltinID(); 532 unsigned BuiltinIndex, NumFixed = 1; 533 switch (BuiltinID) { 534 default: assert(0 && "Unknown overloaded atomic builtin!"); 535 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break; 536 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break; 537 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break; 538 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break; 539 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break; 540 541 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break; 542 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break; 543 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break; 544 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break; 545 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break; 546 547 case Builtin::BI__sync_val_compare_and_swap: 548 BuiltinIndex = 10; 549 NumFixed = 2; 550 break; 551 case Builtin::BI__sync_bool_compare_and_swap: 552 BuiltinIndex = 11; 553 NumFixed = 2; 554 ResultType = Context.BoolTy; 555 break; 556 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break; 557 case Builtin::BI__sync_lock_release: 558 BuiltinIndex = 13; 559 NumFixed = 0; 560 ResultType = Context.VoidTy; 561 break; 562 case Builtin::BI__sync_swap: BuiltinIndex = 14; break; 563 } 564 565 // Now that we know how many fixed arguments we expect, first check that we 566 // have at least that many. 567 if (TheCall->getNumArgs() < 1+NumFixed) { 568 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 569 << 0 << 1+NumFixed << TheCall->getNumArgs() 570 << TheCall->getCallee()->getSourceRange(); 571 return ExprError(); 572 } 573 574 // Get the decl for the concrete builtin from this, we can tell what the 575 // concrete integer type we should convert to is. 576 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 577 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID); 578 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName); 579 FunctionDecl *NewBuiltinDecl = 580 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID, 581 TUScope, false, DRE->getLocStart())); 582 583 // The first argument --- the pointer --- has a fixed type; we 584 // deduce the types of the rest of the arguments accordingly. Walk 585 // the remaining arguments, converting them to the deduced value type. 586 for (unsigned i = 0; i != NumFixed; ++i) { 587 ExprResult Arg = TheCall->getArg(i+1); 588 589 // If the argument is an implicit cast, then there was a promotion due to 590 // "...", just remove it now. 591 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) { 592 Arg = ICE->getSubExpr(); 593 ICE->setSubExpr(0); 594 TheCall->setArg(i+1, Arg.get()); 595 } 596 597 // GCC does an implicit conversion to the pointer or integer ValType. This 598 // can fail in some cases (1i -> int**), check for this error case now. 599 CastKind Kind = CK_Invalid; 600 ExprValueKind VK = VK_RValue; 601 CXXCastPath BasePath; 602 Arg = CheckCastTypes(Arg.get()->getLocStart(), Arg.get()->getSourceRange(), 603 ValType, Arg.take(), Kind, VK, BasePath); 604 if (Arg.isInvalid()) 605 return ExprError(); 606 607 // Okay, we have something that *can* be converted to the right type. Check 608 // to see if there is a potentially weird extension going on here. This can 609 // happen when you do an atomic operation on something like an char* and 610 // pass in 42. The 42 gets converted to char. This is even more strange 611 // for things like 45.123 -> char, etc. 612 // FIXME: Do this check. 613 Arg = ImpCastExprToType(Arg.take(), ValType, Kind, VK, &BasePath); 614 TheCall->setArg(i+1, Arg.get()); 615 } 616 617 // Switch the DeclRefExpr to refer to the new decl. 618 DRE->setDecl(NewBuiltinDecl); 619 DRE->setType(NewBuiltinDecl->getType()); 620 621 // Set the callee in the CallExpr. 622 // FIXME: This leaks the original parens and implicit casts. 623 ExprResult PromotedCall = UsualUnaryConversions(DRE); 624 if (PromotedCall.isInvalid()) 625 return ExprError(); 626 TheCall->setCallee(PromotedCall.take()); 627 628 // Change the result type of the call to match the original value type. This 629 // is arbitrary, but the codegen for these builtins ins design to handle it 630 // gracefully. 631 TheCall->setType(ResultType); 632 633 return move(TheCallResult); 634} 635 636 637/// CheckObjCString - Checks that the argument to the builtin 638/// CFString constructor is correct 639/// Note: It might also make sense to do the UTF-16 conversion here (would 640/// simplify the backend). 641bool Sema::CheckObjCString(Expr *Arg) { 642 Arg = Arg->IgnoreParenCasts(); 643 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 644 645 if (!Literal || !Literal->isAscii()) { 646 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 647 << Arg->getSourceRange(); 648 return true; 649 } 650 651 if (Literal->containsNonAsciiOrNull()) { 652 StringRef String = Literal->getString(); 653 unsigned NumBytes = String.size(); 654 SmallVector<UTF16, 128> ToBuf(NumBytes); 655 const UTF8 *FromPtr = (UTF8 *)String.data(); 656 UTF16 *ToPtr = &ToBuf[0]; 657 658 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 659 &ToPtr, ToPtr + NumBytes, 660 strictConversion); 661 // Check for conversion failure. 662 if (Result != conversionOK) 663 Diag(Arg->getLocStart(), 664 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 665 } 666 return false; 667} 668 669/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 670/// Emit an error and return true on failure, return false on success. 671bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 672 Expr *Fn = TheCall->getCallee(); 673 if (TheCall->getNumArgs() > 2) { 674 Diag(TheCall->getArg(2)->getLocStart(), 675 diag::err_typecheck_call_too_many_args) 676 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 677 << Fn->getSourceRange() 678 << SourceRange(TheCall->getArg(2)->getLocStart(), 679 (*(TheCall->arg_end()-1))->getLocEnd()); 680 return true; 681 } 682 683 if (TheCall->getNumArgs() < 2) { 684 return Diag(TheCall->getLocEnd(), 685 diag::err_typecheck_call_too_few_args_at_least) 686 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 687 } 688 689 // Type-check the first argument normally. 690 if (checkBuiltinArgument(*this, TheCall, 0)) 691 return true; 692 693 // Determine whether the current function is variadic or not. 694 BlockScopeInfo *CurBlock = getCurBlock(); 695 bool isVariadic; 696 if (CurBlock) 697 isVariadic = CurBlock->TheDecl->isVariadic(); 698 else if (FunctionDecl *FD = getCurFunctionDecl()) 699 isVariadic = FD->isVariadic(); 700 else 701 isVariadic = getCurMethodDecl()->isVariadic(); 702 703 if (!isVariadic) { 704 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 705 return true; 706 } 707 708 // Verify that the second argument to the builtin is the last argument of the 709 // current function or method. 710 bool SecondArgIsLastNamedArgument = false; 711 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 712 713 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 714 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 715 // FIXME: This isn't correct for methods (results in bogus warning). 716 // Get the last formal in the current function. 717 const ParmVarDecl *LastArg; 718 if (CurBlock) 719 LastArg = *(CurBlock->TheDecl->param_end()-1); 720 else if (FunctionDecl *FD = getCurFunctionDecl()) 721 LastArg = *(FD->param_end()-1); 722 else 723 LastArg = *(getCurMethodDecl()->param_end()-1); 724 SecondArgIsLastNamedArgument = PV == LastArg; 725 } 726 } 727 728 if (!SecondArgIsLastNamedArgument) 729 Diag(TheCall->getArg(1)->getLocStart(), 730 diag::warn_second_parameter_of_va_start_not_last_named_argument); 731 return false; 732} 733 734/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 735/// friends. This is declared to take (...), so we have to check everything. 736bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 737 if (TheCall->getNumArgs() < 2) 738 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 739 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 740 if (TheCall->getNumArgs() > 2) 741 return Diag(TheCall->getArg(2)->getLocStart(), 742 diag::err_typecheck_call_too_many_args) 743 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 744 << SourceRange(TheCall->getArg(2)->getLocStart(), 745 (*(TheCall->arg_end()-1))->getLocEnd()); 746 747 ExprResult OrigArg0 = TheCall->getArg(0); 748 ExprResult OrigArg1 = TheCall->getArg(1); 749 750 // Do standard promotions between the two arguments, returning their common 751 // type. 752 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 753 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 754 return true; 755 756 // Make sure any conversions are pushed back into the call; this is 757 // type safe since unordered compare builtins are declared as "_Bool 758 // foo(...)". 759 TheCall->setArg(0, OrigArg0.get()); 760 TheCall->setArg(1, OrigArg1.get()); 761 762 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 763 return false; 764 765 // If the common type isn't a real floating type, then the arguments were 766 // invalid for this operation. 767 if (!Res->isRealFloatingType()) 768 return Diag(OrigArg0.get()->getLocStart(), 769 diag::err_typecheck_call_invalid_ordered_compare) 770 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 771 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 772 773 return false; 774} 775 776/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 777/// __builtin_isnan and friends. This is declared to take (...), so we have 778/// to check everything. We expect the last argument to be a floating point 779/// value. 780bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 781 if (TheCall->getNumArgs() < NumArgs) 782 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 783 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 784 if (TheCall->getNumArgs() > NumArgs) 785 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 786 diag::err_typecheck_call_too_many_args) 787 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 788 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 789 (*(TheCall->arg_end()-1))->getLocEnd()); 790 791 Expr *OrigArg = TheCall->getArg(NumArgs-1); 792 793 if (OrigArg->isTypeDependent()) 794 return false; 795 796 // This operation requires a non-_Complex floating-point number. 797 if (!OrigArg->getType()->isRealFloatingType()) 798 return Diag(OrigArg->getLocStart(), 799 diag::err_typecheck_call_invalid_unary_fp) 800 << OrigArg->getType() << OrigArg->getSourceRange(); 801 802 // If this is an implicit conversion from float -> double, remove it. 803 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 804 Expr *CastArg = Cast->getSubExpr(); 805 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 806 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 807 "promotion from float to double is the only expected cast here"); 808 Cast->setSubExpr(0); 809 TheCall->setArg(NumArgs-1, CastArg); 810 OrigArg = CastArg; 811 } 812 } 813 814 return false; 815} 816 817/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 818// This is declared to take (...), so we have to check everything. 819ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 820 if (TheCall->getNumArgs() < 2) 821 return ExprError(Diag(TheCall->getLocEnd(), 822 diag::err_typecheck_call_too_few_args_at_least) 823 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 824 << TheCall->getSourceRange()); 825 826 // Determine which of the following types of shufflevector we're checking: 827 // 1) unary, vector mask: (lhs, mask) 828 // 2) binary, vector mask: (lhs, rhs, mask) 829 // 3) binary, scalar mask: (lhs, rhs, index, ..., index) 830 QualType resType = TheCall->getArg(0)->getType(); 831 unsigned numElements = 0; 832 833 if (!TheCall->getArg(0)->isTypeDependent() && 834 !TheCall->getArg(1)->isTypeDependent()) { 835 QualType LHSType = TheCall->getArg(0)->getType(); 836 QualType RHSType = TheCall->getArg(1)->getType(); 837 838 if (!LHSType->isVectorType() || !RHSType->isVectorType()) { 839 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector) 840 << SourceRange(TheCall->getArg(0)->getLocStart(), 841 TheCall->getArg(1)->getLocEnd()); 842 return ExprError(); 843 } 844 845 numElements = LHSType->getAs<VectorType>()->getNumElements(); 846 unsigned numResElements = TheCall->getNumArgs() - 2; 847 848 // Check to see if we have a call with 2 vector arguments, the unary shuffle 849 // with mask. If so, verify that RHS is an integer vector type with the 850 // same number of elts as lhs. 851 if (TheCall->getNumArgs() == 2) { 852 if (!RHSType->hasIntegerRepresentation() || 853 RHSType->getAs<VectorType>()->getNumElements() != numElements) 854 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 855 << SourceRange(TheCall->getArg(1)->getLocStart(), 856 TheCall->getArg(1)->getLocEnd()); 857 numResElements = numElements; 858 } 859 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 860 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 861 << SourceRange(TheCall->getArg(0)->getLocStart(), 862 TheCall->getArg(1)->getLocEnd()); 863 return ExprError(); 864 } else if (numElements != numResElements) { 865 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 866 resType = Context.getVectorType(eltType, numResElements, 867 VectorType::GenericVector); 868 } 869 } 870 871 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 872 if (TheCall->getArg(i)->isTypeDependent() || 873 TheCall->getArg(i)->isValueDependent()) 874 continue; 875 876 llvm::APSInt Result(32); 877 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 878 return ExprError(Diag(TheCall->getLocStart(), 879 diag::err_shufflevector_nonconstant_argument) 880 << TheCall->getArg(i)->getSourceRange()); 881 882 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 883 return ExprError(Diag(TheCall->getLocStart(), 884 diag::err_shufflevector_argument_too_large) 885 << TheCall->getArg(i)->getSourceRange()); 886 } 887 888 SmallVector<Expr*, 32> exprs; 889 890 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 891 exprs.push_back(TheCall->getArg(i)); 892 TheCall->setArg(i, 0); 893 } 894 895 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(), 896 exprs.size(), resType, 897 TheCall->getCallee()->getLocStart(), 898 TheCall->getRParenLoc())); 899} 900 901/// SemaBuiltinPrefetch - Handle __builtin_prefetch. 902// This is declared to take (const void*, ...) and can take two 903// optional constant int args. 904bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 905 unsigned NumArgs = TheCall->getNumArgs(); 906 907 if (NumArgs > 3) 908 return Diag(TheCall->getLocEnd(), 909 diag::err_typecheck_call_too_many_args_at_most) 910 << 0 /*function call*/ << 3 << NumArgs 911 << TheCall->getSourceRange(); 912 913 // Argument 0 is checked for us and the remaining arguments must be 914 // constant integers. 915 for (unsigned i = 1; i != NumArgs; ++i) { 916 Expr *Arg = TheCall->getArg(i); 917 918 llvm::APSInt Result; 919 if (SemaBuiltinConstantArg(TheCall, i, Result)) 920 return true; 921 922 // FIXME: gcc issues a warning and rewrites these to 0. These 923 // seems especially odd for the third argument since the default 924 // is 3. 925 if (i == 1) { 926 if (Result.getLimitedValue() > 1) 927 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 928 << "0" << "1" << Arg->getSourceRange(); 929 } else { 930 if (Result.getLimitedValue() > 3) 931 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 932 << "0" << "3" << Arg->getSourceRange(); 933 } 934 } 935 936 return false; 937} 938 939/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 940/// TheCall is a constant expression. 941bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 942 llvm::APSInt &Result) { 943 Expr *Arg = TheCall->getArg(ArgNum); 944 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 945 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 946 947 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 948 949 if (!Arg->isIntegerConstantExpr(Result, Context)) 950 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 951 << FDecl->getDeclName() << Arg->getSourceRange(); 952 953 return false; 954} 955 956/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, 957/// int type). This simply type checks that type is one of the defined 958/// constants (0-3). 959// For compatibility check 0-3, llvm only handles 0 and 2. 960bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { 961 llvm::APSInt Result; 962 963 // Check constant-ness first. 964 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 965 return true; 966 967 Expr *Arg = TheCall->getArg(1); 968 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { 969 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 970 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 971 } 972 973 return false; 974} 975 976/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 977/// This checks that val is a constant 1. 978bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 979 Expr *Arg = TheCall->getArg(1); 980 llvm::APSInt Result; 981 982 // TODO: This is less than ideal. Overload this to take a value. 983 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 984 return true; 985 986 if (Result != 1) 987 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 988 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 989 990 return false; 991} 992 993// Handle i > 1 ? "x" : "y", recursively. 994bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall, 995 bool HasVAListArg, 996 unsigned format_idx, unsigned firstDataArg, 997 bool isPrintf) { 998 tryAgain: 999 if (E->isTypeDependent() || E->isValueDependent()) 1000 return false; 1001 1002 E = E->IgnoreParens(); 1003 1004 switch (E->getStmtClass()) { 1005 case Stmt::BinaryConditionalOperatorClass: 1006 case Stmt::ConditionalOperatorClass: { 1007 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E); 1008 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg, 1009 format_idx, firstDataArg, isPrintf) 1010 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg, 1011 format_idx, firstDataArg, isPrintf); 1012 } 1013 1014 case Stmt::IntegerLiteralClass: 1015 // Technically -Wformat-nonliteral does not warn about this case. 1016 // The behavior of printf and friends in this case is implementation 1017 // dependent. Ideally if the format string cannot be null then 1018 // it should have a 'nonnull' attribute in the function prototype. 1019 return true; 1020 1021 case Stmt::ImplicitCastExprClass: { 1022 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 1023 goto tryAgain; 1024 } 1025 1026 case Stmt::OpaqueValueExprClass: 1027 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 1028 E = src; 1029 goto tryAgain; 1030 } 1031 return false; 1032 1033 case Stmt::PredefinedExprClass: 1034 // While __func__, etc., are technically not string literals, they 1035 // cannot contain format specifiers and thus are not a security 1036 // liability. 1037 return true; 1038 1039 case Stmt::DeclRefExprClass: { 1040 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 1041 1042 // As an exception, do not flag errors for variables binding to 1043 // const string literals. 1044 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 1045 bool isConstant = false; 1046 QualType T = DR->getType(); 1047 1048 if (const ArrayType *AT = Context.getAsArrayType(T)) { 1049 isConstant = AT->getElementType().isConstant(Context); 1050 } else if (const PointerType *PT = T->getAs<PointerType>()) { 1051 isConstant = T.isConstant(Context) && 1052 PT->getPointeeType().isConstant(Context); 1053 } 1054 1055 if (isConstant) { 1056 if (const Expr *Init = VD->getAnyInitializer()) 1057 return SemaCheckStringLiteral(Init, TheCall, 1058 HasVAListArg, format_idx, firstDataArg, 1059 isPrintf); 1060 } 1061 1062 // For vprintf* functions (i.e., HasVAListArg==true), we add a 1063 // special check to see if the format string is a function parameter 1064 // of the function calling the printf function. If the function 1065 // has an attribute indicating it is a printf-like function, then we 1066 // should suppress warnings concerning non-literals being used in a call 1067 // to a vprintf function. For example: 1068 // 1069 // void 1070 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 1071 // va_list ap; 1072 // va_start(ap, fmt); 1073 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 1074 // ... 1075 // 1076 // 1077 // FIXME: We don't have full attribute support yet, so just check to see 1078 // if the argument is a DeclRefExpr that references a parameter. We'll 1079 // add proper support for checking the attribute later. 1080 if (HasVAListArg) 1081 if (isa<ParmVarDecl>(VD)) 1082 return true; 1083 } 1084 1085 return false; 1086 } 1087 1088 case Stmt::CallExprClass: { 1089 const CallExpr *CE = cast<CallExpr>(E); 1090 if (const ImplicitCastExpr *ICE 1091 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) { 1092 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) { 1093 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 1094 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) { 1095 unsigned ArgIndex = FA->getFormatIdx(); 1096 const Expr *Arg = CE->getArg(ArgIndex - 1); 1097 1098 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg, 1099 format_idx, firstDataArg, isPrintf); 1100 } 1101 } 1102 } 1103 } 1104 1105 return false; 1106 } 1107 case Stmt::ObjCStringLiteralClass: 1108 case Stmt::StringLiteralClass: { 1109 const StringLiteral *StrE = NULL; 1110 1111 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 1112 StrE = ObjCFExpr->getString(); 1113 else 1114 StrE = cast<StringLiteral>(E); 1115 1116 if (StrE) { 1117 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx, 1118 firstDataArg, isPrintf); 1119 return true; 1120 } 1121 1122 return false; 1123 } 1124 1125 default: 1126 return false; 1127 } 1128} 1129 1130void 1131Sema::CheckNonNullArguments(const NonNullAttr *NonNull, 1132 const Expr * const *ExprArgs, 1133 SourceLocation CallSiteLoc) { 1134 for (NonNullAttr::args_iterator i = NonNull->args_begin(), 1135 e = NonNull->args_end(); 1136 i != e; ++i) { 1137 const Expr *ArgExpr = ExprArgs[*i]; 1138 if (ArgExpr->isNullPointerConstant(Context, 1139 Expr::NPC_ValueDependentIsNotNull)) 1140 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 1141 } 1142} 1143 1144/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar 1145/// functions) for correct use of format strings. 1146void 1147Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg, 1148 unsigned format_idx, unsigned firstDataArg, 1149 bool isPrintf) { 1150 1151 const Expr *Fn = TheCall->getCallee(); 1152 1153 // The way the format attribute works in GCC, the implicit this argument 1154 // of member functions is counted. However, it doesn't appear in our own 1155 // lists, so decrement format_idx in that case. 1156 if (isa<CXXMemberCallExpr>(TheCall)) { 1157 const CXXMethodDecl *method_decl = 1158 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl()); 1159 if (method_decl && method_decl->isInstance()) { 1160 // Catch a format attribute mistakenly referring to the object argument. 1161 if (format_idx == 0) 1162 return; 1163 --format_idx; 1164 if(firstDataArg != 0) 1165 --firstDataArg; 1166 } 1167 } 1168 1169 // CHECK: printf/scanf-like function is called with no format string. 1170 if (format_idx >= TheCall->getNumArgs()) { 1171 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string) 1172 << Fn->getSourceRange(); 1173 return; 1174 } 1175 1176 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts(); 1177 1178 // CHECK: format string is not a string literal. 1179 // 1180 // Dynamically generated format strings are difficult to 1181 // automatically vet at compile time. Requiring that format strings 1182 // are string literals: (1) permits the checking of format strings by 1183 // the compiler and thereby (2) can practically remove the source of 1184 // many format string exploits. 1185 1186 // Format string can be either ObjC string (e.g. @"%d") or 1187 // C string (e.g. "%d") 1188 // ObjC string uses the same format specifiers as C string, so we can use 1189 // the same format string checking logic for both ObjC and C strings. 1190 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx, 1191 firstDataArg, isPrintf)) 1192 return; // Literal format string found, check done! 1193 1194 // If there are no arguments specified, warn with -Wformat-security, otherwise 1195 // warn only with -Wformat-nonliteral. 1196 if (TheCall->getNumArgs() == format_idx+1) 1197 Diag(TheCall->getArg(format_idx)->getLocStart(), 1198 diag::warn_format_nonliteral_noargs) 1199 << OrigFormatExpr->getSourceRange(); 1200 else 1201 Diag(TheCall->getArg(format_idx)->getLocStart(), 1202 diag::warn_format_nonliteral) 1203 << OrigFormatExpr->getSourceRange(); 1204} 1205 1206namespace { 1207class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 1208protected: 1209 Sema &S; 1210 const StringLiteral *FExpr; 1211 const Expr *OrigFormatExpr; 1212 const unsigned FirstDataArg; 1213 const unsigned NumDataArgs; 1214 const bool IsObjCLiteral; 1215 const char *Beg; // Start of format string. 1216 const bool HasVAListArg; 1217 const CallExpr *TheCall; 1218 unsigned FormatIdx; 1219 llvm::BitVector CoveredArgs; 1220 bool usesPositionalArgs; 1221 bool atFirstArg; 1222public: 1223 CheckFormatHandler(Sema &s, const StringLiteral *fexpr, 1224 const Expr *origFormatExpr, unsigned firstDataArg, 1225 unsigned numDataArgs, bool isObjCLiteral, 1226 const char *beg, bool hasVAListArg, 1227 const CallExpr *theCall, unsigned formatIdx) 1228 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 1229 FirstDataArg(firstDataArg), 1230 NumDataArgs(numDataArgs), 1231 IsObjCLiteral(isObjCLiteral), Beg(beg), 1232 HasVAListArg(hasVAListArg), 1233 TheCall(theCall), FormatIdx(formatIdx), 1234 usesPositionalArgs(false), atFirstArg(true) { 1235 CoveredArgs.resize(numDataArgs); 1236 CoveredArgs.reset(); 1237 } 1238 1239 void DoneProcessing(); 1240 1241 void HandleIncompleteSpecifier(const char *startSpecifier, 1242 unsigned specifierLen); 1243 1244 virtual void HandleInvalidPosition(const char *startSpecifier, 1245 unsigned specifierLen, 1246 analyze_format_string::PositionContext p); 1247 1248 virtual void HandleZeroPosition(const char *startPos, unsigned posLen); 1249 1250 void HandleNullChar(const char *nullCharacter); 1251 1252protected: 1253 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 1254 const char *startSpec, 1255 unsigned specifierLen, 1256 const char *csStart, unsigned csLen); 1257 1258 SourceRange getFormatStringRange(); 1259 CharSourceRange getSpecifierRange(const char *startSpecifier, 1260 unsigned specifierLen); 1261 SourceLocation getLocationOfByte(const char *x); 1262 1263 const Expr *getDataArg(unsigned i) const; 1264 1265 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 1266 const analyze_format_string::ConversionSpecifier &CS, 1267 const char *startSpecifier, unsigned specifierLen, 1268 unsigned argIndex); 1269}; 1270} 1271 1272SourceRange CheckFormatHandler::getFormatStringRange() { 1273 return OrigFormatExpr->getSourceRange(); 1274} 1275 1276CharSourceRange CheckFormatHandler:: 1277getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 1278 SourceLocation Start = getLocationOfByte(startSpecifier); 1279 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 1280 1281 // Advance the end SourceLocation by one due to half-open ranges. 1282 End = End.getFileLocWithOffset(1); 1283 1284 return CharSourceRange::getCharRange(Start, End); 1285} 1286 1287SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 1288 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 1289} 1290 1291void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 1292 unsigned specifierLen){ 1293 SourceLocation Loc = getLocationOfByte(startSpecifier); 1294 S.Diag(Loc, diag::warn_printf_incomplete_specifier) 1295 << getSpecifierRange(startSpecifier, specifierLen); 1296} 1297 1298void 1299CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 1300 analyze_format_string::PositionContext p) { 1301 SourceLocation Loc = getLocationOfByte(startPos); 1302 S.Diag(Loc, diag::warn_format_invalid_positional_specifier) 1303 << (unsigned) p << getSpecifierRange(startPos, posLen); 1304} 1305 1306void CheckFormatHandler::HandleZeroPosition(const char *startPos, 1307 unsigned posLen) { 1308 SourceLocation Loc = getLocationOfByte(startPos); 1309 S.Diag(Loc, diag::warn_format_zero_positional_specifier) 1310 << getSpecifierRange(startPos, posLen); 1311} 1312 1313void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 1314 if (!IsObjCLiteral) { 1315 // The presence of a null character is likely an error. 1316 S.Diag(getLocationOfByte(nullCharacter), 1317 diag::warn_printf_format_string_contains_null_char) 1318 << getFormatStringRange(); 1319 } 1320} 1321 1322const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 1323 return TheCall->getArg(FirstDataArg + i); 1324} 1325 1326void CheckFormatHandler::DoneProcessing() { 1327 // Does the number of data arguments exceed the number of 1328 // format conversions in the format string? 1329 if (!HasVAListArg) { 1330 // Find any arguments that weren't covered. 1331 CoveredArgs.flip(); 1332 signed notCoveredArg = CoveredArgs.find_first(); 1333 if (notCoveredArg >= 0) { 1334 assert((unsigned)notCoveredArg < NumDataArgs); 1335 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(), 1336 diag::warn_printf_data_arg_not_used) 1337 << getFormatStringRange(); 1338 } 1339 } 1340} 1341 1342bool 1343CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 1344 SourceLocation Loc, 1345 const char *startSpec, 1346 unsigned specifierLen, 1347 const char *csStart, 1348 unsigned csLen) { 1349 1350 bool keepGoing = true; 1351 if (argIndex < NumDataArgs) { 1352 // Consider the argument coverered, even though the specifier doesn't 1353 // make sense. 1354 CoveredArgs.set(argIndex); 1355 } 1356 else { 1357 // If argIndex exceeds the number of data arguments we 1358 // don't issue a warning because that is just a cascade of warnings (and 1359 // they may have intended '%%' anyway). We don't want to continue processing 1360 // the format string after this point, however, as we will like just get 1361 // gibberish when trying to match arguments. 1362 keepGoing = false; 1363 } 1364 1365 S.Diag(Loc, diag::warn_format_invalid_conversion) 1366 << StringRef(csStart, csLen) 1367 << getSpecifierRange(startSpec, specifierLen); 1368 1369 return keepGoing; 1370} 1371 1372bool 1373CheckFormatHandler::CheckNumArgs( 1374 const analyze_format_string::FormatSpecifier &FS, 1375 const analyze_format_string::ConversionSpecifier &CS, 1376 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 1377 1378 if (argIndex >= NumDataArgs) { 1379 if (FS.usesPositionalArg()) { 1380 S.Diag(getLocationOfByte(CS.getStart()), 1381 diag::warn_printf_positional_arg_exceeds_data_args) 1382 << (argIndex+1) << NumDataArgs 1383 << getSpecifierRange(startSpecifier, specifierLen); 1384 } 1385 else { 1386 S.Diag(getLocationOfByte(CS.getStart()), 1387 diag::warn_printf_insufficient_data_args) 1388 << getSpecifierRange(startSpecifier, specifierLen); 1389 } 1390 1391 return false; 1392 } 1393 return true; 1394} 1395 1396//===--- CHECK: Printf format string checking ------------------------------===// 1397 1398namespace { 1399class CheckPrintfHandler : public CheckFormatHandler { 1400public: 1401 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 1402 const Expr *origFormatExpr, unsigned firstDataArg, 1403 unsigned numDataArgs, bool isObjCLiteral, 1404 const char *beg, bool hasVAListArg, 1405 const CallExpr *theCall, unsigned formatIdx) 1406 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 1407 numDataArgs, isObjCLiteral, beg, hasVAListArg, 1408 theCall, formatIdx) {} 1409 1410 1411 bool HandleInvalidPrintfConversionSpecifier( 1412 const analyze_printf::PrintfSpecifier &FS, 1413 const char *startSpecifier, 1414 unsigned specifierLen); 1415 1416 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 1417 const char *startSpecifier, 1418 unsigned specifierLen); 1419 1420 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 1421 const char *startSpecifier, unsigned specifierLen); 1422 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 1423 const analyze_printf::OptionalAmount &Amt, 1424 unsigned type, 1425 const char *startSpecifier, unsigned specifierLen); 1426 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 1427 const analyze_printf::OptionalFlag &flag, 1428 const char *startSpecifier, unsigned specifierLen); 1429 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 1430 const analyze_printf::OptionalFlag &ignoredFlag, 1431 const analyze_printf::OptionalFlag &flag, 1432 const char *startSpecifier, unsigned specifierLen); 1433}; 1434} 1435 1436bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 1437 const analyze_printf::PrintfSpecifier &FS, 1438 const char *startSpecifier, 1439 unsigned specifierLen) { 1440 const analyze_printf::PrintfConversionSpecifier &CS = 1441 FS.getConversionSpecifier(); 1442 1443 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 1444 getLocationOfByte(CS.getStart()), 1445 startSpecifier, specifierLen, 1446 CS.getStart(), CS.getLength()); 1447} 1448 1449bool CheckPrintfHandler::HandleAmount( 1450 const analyze_format_string::OptionalAmount &Amt, 1451 unsigned k, const char *startSpecifier, 1452 unsigned specifierLen) { 1453 1454 if (Amt.hasDataArgument()) { 1455 if (!HasVAListArg) { 1456 unsigned argIndex = Amt.getArgIndex(); 1457 if (argIndex >= NumDataArgs) { 1458 S.Diag(getLocationOfByte(Amt.getStart()), 1459 diag::warn_printf_asterisk_missing_arg) 1460 << k << getSpecifierRange(startSpecifier, specifierLen); 1461 // Don't do any more checking. We will just emit 1462 // spurious errors. 1463 return false; 1464 } 1465 1466 // Type check the data argument. It should be an 'int'. 1467 // Although not in conformance with C99, we also allow the argument to be 1468 // an 'unsigned int' as that is a reasonably safe case. GCC also 1469 // doesn't emit a warning for that case. 1470 CoveredArgs.set(argIndex); 1471 const Expr *Arg = getDataArg(argIndex); 1472 QualType T = Arg->getType(); 1473 1474 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context); 1475 assert(ATR.isValid()); 1476 1477 if (!ATR.matchesType(S.Context, T)) { 1478 S.Diag(getLocationOfByte(Amt.getStart()), 1479 diag::warn_printf_asterisk_wrong_type) 1480 << k 1481 << ATR.getRepresentativeType(S.Context) << T 1482 << getSpecifierRange(startSpecifier, specifierLen) 1483 << Arg->getSourceRange(); 1484 // Don't do any more checking. We will just emit 1485 // spurious errors. 1486 return false; 1487 } 1488 } 1489 } 1490 return true; 1491} 1492 1493void CheckPrintfHandler::HandleInvalidAmount( 1494 const analyze_printf::PrintfSpecifier &FS, 1495 const analyze_printf::OptionalAmount &Amt, 1496 unsigned type, 1497 const char *startSpecifier, 1498 unsigned specifierLen) { 1499 const analyze_printf::PrintfConversionSpecifier &CS = 1500 FS.getConversionSpecifier(); 1501 switch (Amt.getHowSpecified()) { 1502 case analyze_printf::OptionalAmount::Constant: 1503 S.Diag(getLocationOfByte(Amt.getStart()), 1504 diag::warn_printf_nonsensical_optional_amount) 1505 << type 1506 << CS.toString() 1507 << getSpecifierRange(startSpecifier, specifierLen) 1508 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 1509 Amt.getConstantLength())); 1510 break; 1511 1512 default: 1513 S.Diag(getLocationOfByte(Amt.getStart()), 1514 diag::warn_printf_nonsensical_optional_amount) 1515 << type 1516 << CS.toString() 1517 << getSpecifierRange(startSpecifier, specifierLen); 1518 break; 1519 } 1520} 1521 1522void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 1523 const analyze_printf::OptionalFlag &flag, 1524 const char *startSpecifier, 1525 unsigned specifierLen) { 1526 // Warn about pointless flag with a fixit removal. 1527 const analyze_printf::PrintfConversionSpecifier &CS = 1528 FS.getConversionSpecifier(); 1529 S.Diag(getLocationOfByte(flag.getPosition()), 1530 diag::warn_printf_nonsensical_flag) 1531 << flag.toString() << CS.toString() 1532 << getSpecifierRange(startSpecifier, specifierLen) 1533 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1)); 1534} 1535 1536void CheckPrintfHandler::HandleIgnoredFlag( 1537 const analyze_printf::PrintfSpecifier &FS, 1538 const analyze_printf::OptionalFlag &ignoredFlag, 1539 const analyze_printf::OptionalFlag &flag, 1540 const char *startSpecifier, 1541 unsigned specifierLen) { 1542 // Warn about ignored flag with a fixit removal. 1543 S.Diag(getLocationOfByte(ignoredFlag.getPosition()), 1544 diag::warn_printf_ignored_flag) 1545 << ignoredFlag.toString() << flag.toString() 1546 << getSpecifierRange(startSpecifier, specifierLen) 1547 << FixItHint::CreateRemoval(getSpecifierRange( 1548 ignoredFlag.getPosition(), 1)); 1549} 1550 1551bool 1552CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 1553 &FS, 1554 const char *startSpecifier, 1555 unsigned specifierLen) { 1556 1557 using namespace analyze_format_string; 1558 using namespace analyze_printf; 1559 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 1560 1561 if (FS.consumesDataArgument()) { 1562 if (atFirstArg) { 1563 atFirstArg = false; 1564 usesPositionalArgs = FS.usesPositionalArg(); 1565 } 1566 else if (usesPositionalArgs != FS.usesPositionalArg()) { 1567 // Cannot mix-and-match positional and non-positional arguments. 1568 S.Diag(getLocationOfByte(CS.getStart()), 1569 diag::warn_format_mix_positional_nonpositional_args) 1570 << getSpecifierRange(startSpecifier, specifierLen); 1571 return false; 1572 } 1573 } 1574 1575 // First check if the field width, precision, and conversion specifier 1576 // have matching data arguments. 1577 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 1578 startSpecifier, specifierLen)) { 1579 return false; 1580 } 1581 1582 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 1583 startSpecifier, specifierLen)) { 1584 return false; 1585 } 1586 1587 if (!CS.consumesDataArgument()) { 1588 // FIXME: Technically specifying a precision or field width here 1589 // makes no sense. Worth issuing a warning at some point. 1590 return true; 1591 } 1592 1593 // Consume the argument. 1594 unsigned argIndex = FS.getArgIndex(); 1595 if (argIndex < NumDataArgs) { 1596 // The check to see if the argIndex is valid will come later. 1597 // We set the bit here because we may exit early from this 1598 // function if we encounter some other error. 1599 CoveredArgs.set(argIndex); 1600 } 1601 1602 // Check for using an Objective-C specific conversion specifier 1603 // in a non-ObjC literal. 1604 if (!IsObjCLiteral && CS.isObjCArg()) { 1605 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 1606 specifierLen); 1607 } 1608 1609 // Check for invalid use of field width 1610 if (!FS.hasValidFieldWidth()) { 1611 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 1612 startSpecifier, specifierLen); 1613 } 1614 1615 // Check for invalid use of precision 1616 if (!FS.hasValidPrecision()) { 1617 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 1618 startSpecifier, specifierLen); 1619 } 1620 1621 // Check each flag does not conflict with any other component. 1622 if (!FS.hasValidThousandsGroupingPrefix()) 1623 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 1624 if (!FS.hasValidLeadingZeros()) 1625 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 1626 if (!FS.hasValidPlusPrefix()) 1627 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 1628 if (!FS.hasValidSpacePrefix()) 1629 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 1630 if (!FS.hasValidAlternativeForm()) 1631 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 1632 if (!FS.hasValidLeftJustified()) 1633 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 1634 1635 // Check that flags are not ignored by another flag 1636 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 1637 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 1638 startSpecifier, specifierLen); 1639 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 1640 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 1641 startSpecifier, specifierLen); 1642 1643 // Check the length modifier is valid with the given conversion specifier. 1644 const LengthModifier &LM = FS.getLengthModifier(); 1645 if (!FS.hasValidLengthModifier()) 1646 S.Diag(getLocationOfByte(LM.getStart()), 1647 diag::warn_format_nonsensical_length) 1648 << LM.toString() << CS.toString() 1649 << getSpecifierRange(startSpecifier, specifierLen) 1650 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(), 1651 LM.getLength())); 1652 1653 // Are we using '%n'? 1654 if (CS.getKind() == ConversionSpecifier::nArg) { 1655 // Issue a warning about this being a possible security issue. 1656 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back) 1657 << getSpecifierRange(startSpecifier, specifierLen); 1658 // Continue checking the other format specifiers. 1659 return true; 1660 } 1661 1662 // The remaining checks depend on the data arguments. 1663 if (HasVAListArg) 1664 return true; 1665 1666 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 1667 return false; 1668 1669 // Now type check the data expression that matches the 1670 // format specifier. 1671 const Expr *Ex = getDataArg(argIndex); 1672 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context); 1673 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) { 1674 // Check if we didn't match because of an implicit cast from a 'char' 1675 // or 'short' to an 'int'. This is done because printf is a varargs 1676 // function. 1677 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex)) 1678 if (ICE->getType() == S.Context.IntTy) { 1679 // All further checking is done on the subexpression. 1680 Ex = ICE->getSubExpr(); 1681 if (ATR.matchesType(S.Context, Ex->getType())) 1682 return true; 1683 } 1684 1685 // We may be able to offer a FixItHint if it is a supported type. 1686 PrintfSpecifier fixedFS = FS; 1687 bool success = fixedFS.fixType(Ex->getType()); 1688 1689 if (success) { 1690 // Get the fix string from the fixed format specifier 1691 llvm::SmallString<128> buf; 1692 llvm::raw_svector_ostream os(buf); 1693 fixedFS.toString(os); 1694 1695 // FIXME: getRepresentativeType() perhaps should return a string 1696 // instead of a QualType to better handle when the representative 1697 // type is 'wint_t' (which is defined in the system headers). 1698 S.Diag(getLocationOfByte(CS.getStart()), 1699 diag::warn_printf_conversion_argument_type_mismatch) 1700 << ATR.getRepresentativeType(S.Context) << Ex->getType() 1701 << getSpecifierRange(startSpecifier, specifierLen) 1702 << Ex->getSourceRange() 1703 << FixItHint::CreateReplacement( 1704 getSpecifierRange(startSpecifier, specifierLen), 1705 os.str()); 1706 } 1707 else { 1708 S.Diag(getLocationOfByte(CS.getStart()), 1709 diag::warn_printf_conversion_argument_type_mismatch) 1710 << ATR.getRepresentativeType(S.Context) << Ex->getType() 1711 << getSpecifierRange(startSpecifier, specifierLen) 1712 << Ex->getSourceRange(); 1713 } 1714 } 1715 1716 return true; 1717} 1718 1719//===--- CHECK: Scanf format string checking ------------------------------===// 1720 1721namespace { 1722class CheckScanfHandler : public CheckFormatHandler { 1723public: 1724 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 1725 const Expr *origFormatExpr, unsigned firstDataArg, 1726 unsigned numDataArgs, bool isObjCLiteral, 1727 const char *beg, bool hasVAListArg, 1728 const CallExpr *theCall, unsigned formatIdx) 1729 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 1730 numDataArgs, isObjCLiteral, beg, hasVAListArg, 1731 theCall, formatIdx) {} 1732 1733 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 1734 const char *startSpecifier, 1735 unsigned specifierLen); 1736 1737 bool HandleInvalidScanfConversionSpecifier( 1738 const analyze_scanf::ScanfSpecifier &FS, 1739 const char *startSpecifier, 1740 unsigned specifierLen); 1741 1742 void HandleIncompleteScanList(const char *start, const char *end); 1743}; 1744} 1745 1746void CheckScanfHandler::HandleIncompleteScanList(const char *start, 1747 const char *end) { 1748 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete) 1749 << getSpecifierRange(start, end - start); 1750} 1751 1752bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 1753 const analyze_scanf::ScanfSpecifier &FS, 1754 const char *startSpecifier, 1755 unsigned specifierLen) { 1756 1757 const analyze_scanf::ScanfConversionSpecifier &CS = 1758 FS.getConversionSpecifier(); 1759 1760 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 1761 getLocationOfByte(CS.getStart()), 1762 startSpecifier, specifierLen, 1763 CS.getStart(), CS.getLength()); 1764} 1765 1766bool CheckScanfHandler::HandleScanfSpecifier( 1767 const analyze_scanf::ScanfSpecifier &FS, 1768 const char *startSpecifier, 1769 unsigned specifierLen) { 1770 1771 using namespace analyze_scanf; 1772 using namespace analyze_format_string; 1773 1774 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 1775 1776 // Handle case where '%' and '*' don't consume an argument. These shouldn't 1777 // be used to decide if we are using positional arguments consistently. 1778 if (FS.consumesDataArgument()) { 1779 if (atFirstArg) { 1780 atFirstArg = false; 1781 usesPositionalArgs = FS.usesPositionalArg(); 1782 } 1783 else if (usesPositionalArgs != FS.usesPositionalArg()) { 1784 // Cannot mix-and-match positional and non-positional arguments. 1785 S.Diag(getLocationOfByte(CS.getStart()), 1786 diag::warn_format_mix_positional_nonpositional_args) 1787 << getSpecifierRange(startSpecifier, specifierLen); 1788 return false; 1789 } 1790 } 1791 1792 // Check if the field with is non-zero. 1793 const OptionalAmount &Amt = FS.getFieldWidth(); 1794 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 1795 if (Amt.getConstantAmount() == 0) { 1796 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 1797 Amt.getConstantLength()); 1798 S.Diag(getLocationOfByte(Amt.getStart()), 1799 diag::warn_scanf_nonzero_width) 1800 << R << FixItHint::CreateRemoval(R); 1801 } 1802 } 1803 1804 if (!FS.consumesDataArgument()) { 1805 // FIXME: Technically specifying a precision or field width here 1806 // makes no sense. Worth issuing a warning at some point. 1807 return true; 1808 } 1809 1810 // Consume the argument. 1811 unsigned argIndex = FS.getArgIndex(); 1812 if (argIndex < NumDataArgs) { 1813 // The check to see if the argIndex is valid will come later. 1814 // We set the bit here because we may exit early from this 1815 // function if we encounter some other error. 1816 CoveredArgs.set(argIndex); 1817 } 1818 1819 // Check the length modifier is valid with the given conversion specifier. 1820 const LengthModifier &LM = FS.getLengthModifier(); 1821 if (!FS.hasValidLengthModifier()) { 1822 S.Diag(getLocationOfByte(LM.getStart()), 1823 diag::warn_format_nonsensical_length) 1824 << LM.toString() << CS.toString() 1825 << getSpecifierRange(startSpecifier, specifierLen) 1826 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(), 1827 LM.getLength())); 1828 } 1829 1830 // The remaining checks depend on the data arguments. 1831 if (HasVAListArg) 1832 return true; 1833 1834 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 1835 return false; 1836 1837 // FIXME: Check that the argument type matches the format specifier. 1838 1839 return true; 1840} 1841 1842void Sema::CheckFormatString(const StringLiteral *FExpr, 1843 const Expr *OrigFormatExpr, 1844 const CallExpr *TheCall, bool HasVAListArg, 1845 unsigned format_idx, unsigned firstDataArg, 1846 bool isPrintf) { 1847 1848 // CHECK: is the format string a wide literal? 1849 if (!FExpr->isAscii()) { 1850 Diag(FExpr->getLocStart(), 1851 diag::warn_format_string_is_wide_literal) 1852 << OrigFormatExpr->getSourceRange(); 1853 return; 1854 } 1855 1856 // Str - The format string. NOTE: this is NOT null-terminated! 1857 StringRef StrRef = FExpr->getString(); 1858 const char *Str = StrRef.data(); 1859 unsigned StrLen = StrRef.size(); 1860 1861 // CHECK: empty format string? 1862 if (StrLen == 0) { 1863 Diag(FExpr->getLocStart(), diag::warn_empty_format_string) 1864 << OrigFormatExpr->getSourceRange(); 1865 return; 1866 } 1867 1868 if (isPrintf) { 1869 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 1870 TheCall->getNumArgs() - firstDataArg, 1871 isa<ObjCStringLiteral>(OrigFormatExpr), Str, 1872 HasVAListArg, TheCall, format_idx); 1873 1874 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen)) 1875 H.DoneProcessing(); 1876 } 1877 else { 1878 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 1879 TheCall->getNumArgs() - firstDataArg, 1880 isa<ObjCStringLiteral>(OrigFormatExpr), Str, 1881 HasVAListArg, TheCall, format_idx); 1882 1883 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen)) 1884 H.DoneProcessing(); 1885 } 1886} 1887 1888//===--- CHECK: Standard memory functions ---------------------------------===// 1889 1890/// \brief Determine whether the given type is a dynamic class type (e.g., 1891/// whether it has a vtable). 1892static bool isDynamicClassType(QualType T) { 1893 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 1894 if (CXXRecordDecl *Definition = Record->getDefinition()) 1895 if (Definition->isDynamicClass()) 1896 return true; 1897 1898 return false; 1899} 1900 1901/// \brief If E is a sizeof expression, returns its argument expression, 1902/// otherwise returns NULL. 1903static const Expr *getSizeOfExprArg(const Expr* E) { 1904 if (const UnaryExprOrTypeTraitExpr *SizeOf = 1905 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 1906 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 1907 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 1908 1909 return 0; 1910} 1911 1912/// \brief If E is a sizeof expression, returns its argument type. 1913static QualType getSizeOfArgType(const Expr* E) { 1914 if (const UnaryExprOrTypeTraitExpr *SizeOf = 1915 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 1916 if (SizeOf->getKind() == clang::UETT_SizeOf) 1917 return SizeOf->getTypeOfArgument(); 1918 1919 return QualType(); 1920} 1921 1922/// \brief Check for dangerous or invalid arguments to memset(). 1923/// 1924/// This issues warnings on known problematic, dangerous or unspecified 1925/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 1926/// function calls. 1927/// 1928/// \param Call The call expression to diagnose. 1929void Sema::CheckMemaccessArguments(const CallExpr *Call, 1930 CheckedMemoryFunction CMF, 1931 IdentifierInfo *FnName) { 1932 // It is possible to have a non-standard definition of memset. Validate 1933 // we have enough arguments, and if not, abort further checking. 1934 if (Call->getNumArgs() < 3) 1935 return; 1936 1937 unsigned LastArg = (CMF == CMF_Memset? 1 : 2); 1938 const Expr *LenExpr = Call->getArg(2)->IgnoreParenImpCasts(); 1939 1940 // We have special checking when the length is a sizeof expression. 1941 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 1942 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 1943 llvm::FoldingSetNodeID SizeOfArgID; 1944 1945 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 1946 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 1947 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 1948 1949 QualType DestTy = Dest->getType(); 1950 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 1951 QualType PointeeTy = DestPtrTy->getPointeeType(); 1952 1953 // Never warn about void type pointers. This can be used to suppress 1954 // false positives. 1955 if (PointeeTy->isVoidType()) 1956 continue; 1957 1958 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 1959 // actually comparing the expressions for equality. Because computing the 1960 // expression IDs can be expensive, we only do this if the diagnostic is 1961 // enabled. 1962 if (SizeOfArg && 1963 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess, 1964 SizeOfArg->getExprLoc())) { 1965 // We only compute IDs for expressions if the warning is enabled, and 1966 // cache the sizeof arg's ID. 1967 if (SizeOfArgID == llvm::FoldingSetNodeID()) 1968 SizeOfArg->Profile(SizeOfArgID, Context, true); 1969 llvm::FoldingSetNodeID DestID; 1970 Dest->Profile(DestID, Context, true); 1971 if (DestID == SizeOfArgID) { 1972 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 1973 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 1974 if (UnaryOp->getOpcode() == UO_AddrOf) 1975 ActionIdx = 1; // If its an address-of operator, just remove it. 1976 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth()) 1977 ActionIdx = 2; // If the pointee's size is sizeof(char), 1978 // suggest an explicit length. 1979 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest, 1980 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 1981 << FnName << ArgIdx << ActionIdx 1982 << Dest->getSourceRange() 1983 << SizeOfArg->getSourceRange()); 1984 break; 1985 } 1986 } 1987 1988 // Also check for cases where the sizeof argument is the exact same 1989 // type as the memory argument, and where it points to a user-defined 1990 // record type. 1991 if (SizeOfArgTy != QualType()) { 1992 if (PointeeTy->isRecordType() && 1993 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 1994 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 1995 PDiag(diag::warn_sizeof_pointer_type_memaccess) 1996 << FnName << SizeOfArgTy << ArgIdx 1997 << PointeeTy << Dest->getSourceRange() 1998 << LenExpr->getSourceRange()); 1999 break; 2000 } 2001 } 2002 2003 // Always complain about dynamic classes. 2004 if (isDynamicClassType(PointeeTy)) 2005 DiagRuntimeBehavior( 2006 Dest->getExprLoc(), Dest, 2007 PDiag(diag::warn_dyn_class_memaccess) 2008 << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy 2009 // "overwritten" if we're warning about the destination for any call 2010 // but memcmp; otherwise a verb appropriate to the call. 2011 << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF) 2012 << Call->getCallee()->getSourceRange()); 2013 else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset) 2014 DiagRuntimeBehavior( 2015 Dest->getExprLoc(), Dest, 2016 PDiag(diag::warn_arc_object_memaccess) 2017 << ArgIdx << FnName << PointeeTy 2018 << Call->getCallee()->getSourceRange()); 2019 else 2020 continue; 2021 2022 DiagRuntimeBehavior( 2023 Dest->getExprLoc(), Dest, 2024 PDiag(diag::note_bad_memaccess_silence) 2025 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 2026 break; 2027 } 2028 } 2029} 2030 2031// A little helper routine: ignore addition and subtraction of integer literals. 2032// This intentionally does not ignore all integer constant expressions because 2033// we don't want to remove sizeof(). 2034static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 2035 Ex = Ex->IgnoreParenCasts(); 2036 2037 for (;;) { 2038 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 2039 if (!BO || !BO->isAdditiveOp()) 2040 break; 2041 2042 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 2043 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 2044 2045 if (isa<IntegerLiteral>(RHS)) 2046 Ex = LHS; 2047 else if (isa<IntegerLiteral>(LHS)) 2048 Ex = RHS; 2049 else 2050 break; 2051 } 2052 2053 return Ex; 2054} 2055 2056// Warn if the user has made the 'size' argument to strlcpy or strlcat 2057// be the size of the source, instead of the destination. 2058void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 2059 IdentifierInfo *FnName) { 2060 2061 // Don't crash if the user has the wrong number of arguments 2062 if (Call->getNumArgs() != 3) 2063 return; 2064 2065 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 2066 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 2067 const Expr *CompareWithSrc = NULL; 2068 2069 // Look for 'strlcpy(dst, x, sizeof(x))' 2070 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 2071 CompareWithSrc = Ex; 2072 else { 2073 // Look for 'strlcpy(dst, x, strlen(x))' 2074 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 2075 if (SizeCall->isBuiltinCall(Context) == Builtin::BIstrlen 2076 && SizeCall->getNumArgs() == 1) 2077 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 2078 } 2079 } 2080 2081 if (!CompareWithSrc) 2082 return; 2083 2084 // Determine if the argument to sizeof/strlen is equal to the source 2085 // argument. In principle there's all kinds of things you could do 2086 // here, for instance creating an == expression and evaluating it with 2087 // EvaluateAsBooleanCondition, but this uses a more direct technique: 2088 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 2089 if (!SrcArgDRE) 2090 return; 2091 2092 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 2093 if (!CompareWithSrcDRE || 2094 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 2095 return; 2096 2097 const Expr *OriginalSizeArg = Call->getArg(2); 2098 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 2099 << OriginalSizeArg->getSourceRange() << FnName; 2100 2101 // Output a FIXIT hint if the destination is an array (rather than a 2102 // pointer to an array). This could be enhanced to handle some 2103 // pointers if we know the actual size, like if DstArg is 'array+2' 2104 // we could say 'sizeof(array)-2'. 2105 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 2106 QualType DstArgTy = DstArg->getType(); 2107 2108 // Only handle constant-sized or VLAs, but not flexible members. 2109 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) { 2110 // Only issue the FIXIT for arrays of size > 1. 2111 if (CAT->getSize().getSExtValue() <= 1) 2112 return; 2113 } else if (!DstArgTy->isVariableArrayType()) { 2114 return; 2115 } 2116 2117 llvm::SmallString<128> sizeString; 2118 llvm::raw_svector_ostream OS(sizeString); 2119 OS << "sizeof("; 2120 DstArg->printPretty(OS, Context, 0, Context.PrintingPolicy); 2121 OS << ")"; 2122 2123 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 2124 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 2125 OS.str()); 2126} 2127 2128//===--- CHECK: Return Address of Stack Variable --------------------------===// 2129 2130static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars); 2131static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars); 2132 2133/// CheckReturnStackAddr - Check if a return statement returns the address 2134/// of a stack variable. 2135void 2136Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 2137 SourceLocation ReturnLoc) { 2138 2139 Expr *stackE = 0; 2140 SmallVector<DeclRefExpr *, 8> refVars; 2141 2142 // Perform checking for returned stack addresses, local blocks, 2143 // label addresses or references to temporaries. 2144 if (lhsType->isPointerType() || 2145 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 2146 stackE = EvalAddr(RetValExp, refVars); 2147 } else if (lhsType->isReferenceType()) { 2148 stackE = EvalVal(RetValExp, refVars); 2149 } 2150 2151 if (stackE == 0) 2152 return; // Nothing suspicious was found. 2153 2154 SourceLocation diagLoc; 2155 SourceRange diagRange; 2156 if (refVars.empty()) { 2157 diagLoc = stackE->getLocStart(); 2158 diagRange = stackE->getSourceRange(); 2159 } else { 2160 // We followed through a reference variable. 'stackE' contains the 2161 // problematic expression but we will warn at the return statement pointing 2162 // at the reference variable. We will later display the "trail" of 2163 // reference variables using notes. 2164 diagLoc = refVars[0]->getLocStart(); 2165 diagRange = refVars[0]->getSourceRange(); 2166 } 2167 2168 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var. 2169 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref 2170 : diag::warn_ret_stack_addr) 2171 << DR->getDecl()->getDeclName() << diagRange; 2172 } else if (isa<BlockExpr>(stackE)) { // local block. 2173 Diag(diagLoc, diag::err_ret_local_block) << diagRange; 2174 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 2175 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 2176 } else { // local temporary. 2177 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref 2178 : diag::warn_ret_local_temp_addr) 2179 << diagRange; 2180 } 2181 2182 // Display the "trail" of reference variables that we followed until we 2183 // found the problematic expression using notes. 2184 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 2185 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 2186 // If this var binds to another reference var, show the range of the next 2187 // var, otherwise the var binds to the problematic expression, in which case 2188 // show the range of the expression. 2189 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange() 2190 : stackE->getSourceRange(); 2191 Diag(VD->getLocation(), diag::note_ref_var_local_bind) 2192 << VD->getDeclName() << range; 2193 } 2194} 2195 2196/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 2197/// check if the expression in a return statement evaluates to an address 2198/// to a location on the stack, a local block, an address of a label, or a 2199/// reference to local temporary. The recursion is used to traverse the 2200/// AST of the return expression, with recursion backtracking when we 2201/// encounter a subexpression that (1) clearly does not lead to one of the 2202/// above problematic expressions (2) is something we cannot determine leads to 2203/// a problematic expression based on such local checking. 2204/// 2205/// Both EvalAddr and EvalVal follow through reference variables to evaluate 2206/// the expression that they point to. Such variables are added to the 2207/// 'refVars' vector so that we know what the reference variable "trail" was. 2208/// 2209/// EvalAddr processes expressions that are pointers that are used as 2210/// references (and not L-values). EvalVal handles all other values. 2211/// At the base case of the recursion is a check for the above problematic 2212/// expressions. 2213/// 2214/// This implementation handles: 2215/// 2216/// * pointer-to-pointer casts 2217/// * implicit conversions from array references to pointers 2218/// * taking the address of fields 2219/// * arbitrary interplay between "&" and "*" operators 2220/// * pointer arithmetic from an address of a stack variable 2221/// * taking the address of an array element where the array is on the stack 2222static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) { 2223 if (E->isTypeDependent()) 2224 return NULL; 2225 2226 // We should only be called for evaluating pointer expressions. 2227 assert((E->getType()->isAnyPointerType() || 2228 E->getType()->isBlockPointerType() || 2229 E->getType()->isObjCQualifiedIdType()) && 2230 "EvalAddr only works on pointers"); 2231 2232 E = E->IgnoreParens(); 2233 2234 // Our "symbolic interpreter" is just a dispatch off the currently 2235 // viewed AST node. We then recursively traverse the AST by calling 2236 // EvalAddr and EvalVal appropriately. 2237 switch (E->getStmtClass()) { 2238 case Stmt::DeclRefExprClass: { 2239 DeclRefExpr *DR = cast<DeclRefExpr>(E); 2240 2241 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 2242 // If this is a reference variable, follow through to the expression that 2243 // it points to. 2244 if (V->hasLocalStorage() && 2245 V->getType()->isReferenceType() && V->hasInit()) { 2246 // Add the reference variable to the "trail". 2247 refVars.push_back(DR); 2248 return EvalAddr(V->getInit(), refVars); 2249 } 2250 2251 return NULL; 2252 } 2253 2254 case Stmt::UnaryOperatorClass: { 2255 // The only unary operator that make sense to handle here 2256 // is AddrOf. All others don't make sense as pointers. 2257 UnaryOperator *U = cast<UnaryOperator>(E); 2258 2259 if (U->getOpcode() == UO_AddrOf) 2260 return EvalVal(U->getSubExpr(), refVars); 2261 else 2262 return NULL; 2263 } 2264 2265 case Stmt::BinaryOperatorClass: { 2266 // Handle pointer arithmetic. All other binary operators are not valid 2267 // in this context. 2268 BinaryOperator *B = cast<BinaryOperator>(E); 2269 BinaryOperatorKind op = B->getOpcode(); 2270 2271 if (op != BO_Add && op != BO_Sub) 2272 return NULL; 2273 2274 Expr *Base = B->getLHS(); 2275 2276 // Determine which argument is the real pointer base. It could be 2277 // the RHS argument instead of the LHS. 2278 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 2279 2280 assert (Base->getType()->isPointerType()); 2281 return EvalAddr(Base, refVars); 2282 } 2283 2284 // For conditional operators we need to see if either the LHS or RHS are 2285 // valid DeclRefExpr*s. If one of them is valid, we return it. 2286 case Stmt::ConditionalOperatorClass: { 2287 ConditionalOperator *C = cast<ConditionalOperator>(E); 2288 2289 // Handle the GNU extension for missing LHS. 2290 if (Expr *lhsExpr = C->getLHS()) { 2291 // In C++, we can have a throw-expression, which has 'void' type. 2292 if (!lhsExpr->getType()->isVoidType()) 2293 if (Expr* LHS = EvalAddr(lhsExpr, refVars)) 2294 return LHS; 2295 } 2296 2297 // In C++, we can have a throw-expression, which has 'void' type. 2298 if (C->getRHS()->getType()->isVoidType()) 2299 return NULL; 2300 2301 return EvalAddr(C->getRHS(), refVars); 2302 } 2303 2304 case Stmt::BlockExprClass: 2305 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 2306 return E; // local block. 2307 return NULL; 2308 2309 case Stmt::AddrLabelExprClass: 2310 return E; // address of label. 2311 2312 // For casts, we need to handle conversions from arrays to 2313 // pointer values, and pointer-to-pointer conversions. 2314 case Stmt::ImplicitCastExprClass: 2315 case Stmt::CStyleCastExprClass: 2316 case Stmt::CXXFunctionalCastExprClass: 2317 case Stmt::ObjCBridgedCastExprClass: { 2318 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 2319 QualType T = SubExpr->getType(); 2320 2321 if (SubExpr->getType()->isPointerType() || 2322 SubExpr->getType()->isBlockPointerType() || 2323 SubExpr->getType()->isObjCQualifiedIdType()) 2324 return EvalAddr(SubExpr, refVars); 2325 else if (T->isArrayType()) 2326 return EvalVal(SubExpr, refVars); 2327 else 2328 return 0; 2329 } 2330 2331 // C++ casts. For dynamic casts, static casts, and const casts, we 2332 // are always converting from a pointer-to-pointer, so we just blow 2333 // through the cast. In the case the dynamic cast doesn't fail (and 2334 // return NULL), we take the conservative route and report cases 2335 // where we return the address of a stack variable. For Reinterpre 2336 // FIXME: The comment about is wrong; we're not always converting 2337 // from pointer to pointer. I'm guessing that this code should also 2338 // handle references to objects. 2339 case Stmt::CXXStaticCastExprClass: 2340 case Stmt::CXXDynamicCastExprClass: 2341 case Stmt::CXXConstCastExprClass: 2342 case Stmt::CXXReinterpretCastExprClass: { 2343 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr(); 2344 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType()) 2345 return EvalAddr(S, refVars); 2346 else 2347 return NULL; 2348 } 2349 2350 case Stmt::MaterializeTemporaryExprClass: 2351 if (Expr *Result = EvalAddr( 2352 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 2353 refVars)) 2354 return Result; 2355 2356 return E; 2357 2358 // Everything else: we simply don't reason about them. 2359 default: 2360 return NULL; 2361 } 2362} 2363 2364 2365/// EvalVal - This function is complements EvalAddr in the mutual recursion. 2366/// See the comments for EvalAddr for more details. 2367static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) { 2368do { 2369 // We should only be called for evaluating non-pointer expressions, or 2370 // expressions with a pointer type that are not used as references but instead 2371 // are l-values (e.g., DeclRefExpr with a pointer type). 2372 2373 // Our "symbolic interpreter" is just a dispatch off the currently 2374 // viewed AST node. We then recursively traverse the AST by calling 2375 // EvalAddr and EvalVal appropriately. 2376 2377 E = E->IgnoreParens(); 2378 switch (E->getStmtClass()) { 2379 case Stmt::ImplicitCastExprClass: { 2380 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 2381 if (IE->getValueKind() == VK_LValue) { 2382 E = IE->getSubExpr(); 2383 continue; 2384 } 2385 return NULL; 2386 } 2387 2388 case Stmt::DeclRefExprClass: { 2389 // When we hit a DeclRefExpr we are looking at code that refers to a 2390 // variable's name. If it's not a reference variable we check if it has 2391 // local storage within the function, and if so, return the expression. 2392 DeclRefExpr *DR = cast<DeclRefExpr>(E); 2393 2394 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 2395 if (V->hasLocalStorage()) { 2396 if (!V->getType()->isReferenceType()) 2397 return DR; 2398 2399 // Reference variable, follow through to the expression that 2400 // it points to. 2401 if (V->hasInit()) { 2402 // Add the reference variable to the "trail". 2403 refVars.push_back(DR); 2404 return EvalVal(V->getInit(), refVars); 2405 } 2406 } 2407 2408 return NULL; 2409 } 2410 2411 case Stmt::UnaryOperatorClass: { 2412 // The only unary operator that make sense to handle here 2413 // is Deref. All others don't resolve to a "name." This includes 2414 // handling all sorts of rvalues passed to a unary operator. 2415 UnaryOperator *U = cast<UnaryOperator>(E); 2416 2417 if (U->getOpcode() == UO_Deref) 2418 return EvalAddr(U->getSubExpr(), refVars); 2419 2420 return NULL; 2421 } 2422 2423 case Stmt::ArraySubscriptExprClass: { 2424 // Array subscripts are potential references to data on the stack. We 2425 // retrieve the DeclRefExpr* for the array variable if it indeed 2426 // has local storage. 2427 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars); 2428 } 2429 2430 case Stmt::ConditionalOperatorClass: { 2431 // For conditional operators we need to see if either the LHS or RHS are 2432 // non-NULL Expr's. If one is non-NULL, we return it. 2433 ConditionalOperator *C = cast<ConditionalOperator>(E); 2434 2435 // Handle the GNU extension for missing LHS. 2436 if (Expr *lhsExpr = C->getLHS()) 2437 if (Expr *LHS = EvalVal(lhsExpr, refVars)) 2438 return LHS; 2439 2440 return EvalVal(C->getRHS(), refVars); 2441 } 2442 2443 // Accesses to members are potential references to data on the stack. 2444 case Stmt::MemberExprClass: { 2445 MemberExpr *M = cast<MemberExpr>(E); 2446 2447 // Check for indirect access. We only want direct field accesses. 2448 if (M->isArrow()) 2449 return NULL; 2450 2451 // Check whether the member type is itself a reference, in which case 2452 // we're not going to refer to the member, but to what the member refers to. 2453 if (M->getMemberDecl()->getType()->isReferenceType()) 2454 return NULL; 2455 2456 return EvalVal(M->getBase(), refVars); 2457 } 2458 2459 case Stmt::MaterializeTemporaryExprClass: 2460 if (Expr *Result = EvalVal( 2461 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 2462 refVars)) 2463 return Result; 2464 2465 return E; 2466 2467 default: 2468 // Check that we don't return or take the address of a reference to a 2469 // temporary. This is only useful in C++. 2470 if (!E->isTypeDependent() && E->isRValue()) 2471 return E; 2472 2473 // Everything else: we simply don't reason about them. 2474 return NULL; 2475 } 2476} while (true); 2477} 2478 2479//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 2480 2481/// Check for comparisons of floating point operands using != and ==. 2482/// Issue a warning if these are no self-comparisons, as they are not likely 2483/// to do what the programmer intended. 2484void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) { 2485 bool EmitWarning = true; 2486 2487 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts(); 2488 Expr* RightExprSansParen = rex->IgnoreParenImpCasts(); 2489 2490 // Special case: check for x == x (which is OK). 2491 // Do not emit warnings for such cases. 2492 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 2493 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 2494 if (DRL->getDecl() == DRR->getDecl()) 2495 EmitWarning = false; 2496 2497 2498 // Special case: check for comparisons against literals that can be exactly 2499 // represented by APFloat. In such cases, do not emit a warning. This 2500 // is a heuristic: often comparison against such literals are used to 2501 // detect if a value in a variable has not changed. This clearly can 2502 // lead to false negatives. 2503 if (EmitWarning) { 2504 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 2505 if (FLL->isExact()) 2506 EmitWarning = false; 2507 } else 2508 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){ 2509 if (FLR->isExact()) 2510 EmitWarning = false; 2511 } 2512 } 2513 2514 // Check for comparisons with builtin types. 2515 if (EmitWarning) 2516 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 2517 if (CL->isBuiltinCall(Context)) 2518 EmitWarning = false; 2519 2520 if (EmitWarning) 2521 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 2522 if (CR->isBuiltinCall(Context)) 2523 EmitWarning = false; 2524 2525 // Emit the diagnostic. 2526 if (EmitWarning) 2527 Diag(loc, diag::warn_floatingpoint_eq) 2528 << lex->getSourceRange() << rex->getSourceRange(); 2529} 2530 2531//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 2532//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 2533 2534namespace { 2535 2536/// Structure recording the 'active' range of an integer-valued 2537/// expression. 2538struct IntRange { 2539 /// The number of bits active in the int. 2540 unsigned Width; 2541 2542 /// True if the int is known not to have negative values. 2543 bool NonNegative; 2544 2545 IntRange(unsigned Width, bool NonNegative) 2546 : Width(Width), NonNegative(NonNegative) 2547 {} 2548 2549 /// Returns the range of the bool type. 2550 static IntRange forBoolType() { 2551 return IntRange(1, true); 2552 } 2553 2554 /// Returns the range of an opaque value of the given integral type. 2555 static IntRange forValueOfType(ASTContext &C, QualType T) { 2556 return forValueOfCanonicalType(C, 2557 T->getCanonicalTypeInternal().getTypePtr()); 2558 } 2559 2560 /// Returns the range of an opaque value of a canonical integral type. 2561 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 2562 assert(T->isCanonicalUnqualified()); 2563 2564 if (const VectorType *VT = dyn_cast<VectorType>(T)) 2565 T = VT->getElementType().getTypePtr(); 2566 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 2567 T = CT->getElementType().getTypePtr(); 2568 2569 // For enum types, use the known bit width of the enumerators. 2570 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 2571 EnumDecl *Enum = ET->getDecl(); 2572 if (!Enum->isDefinition()) 2573 return IntRange(C.getIntWidth(QualType(T, 0)), false); 2574 2575 unsigned NumPositive = Enum->getNumPositiveBits(); 2576 unsigned NumNegative = Enum->getNumNegativeBits(); 2577 2578 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0); 2579 } 2580 2581 const BuiltinType *BT = cast<BuiltinType>(T); 2582 assert(BT->isInteger()); 2583 2584 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 2585 } 2586 2587 /// Returns the "target" range of a canonical integral type, i.e. 2588 /// the range of values expressible in the type. 2589 /// 2590 /// This matches forValueOfCanonicalType except that enums have the 2591 /// full range of their type, not the range of their enumerators. 2592 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 2593 assert(T->isCanonicalUnqualified()); 2594 2595 if (const VectorType *VT = dyn_cast<VectorType>(T)) 2596 T = VT->getElementType().getTypePtr(); 2597 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 2598 T = CT->getElementType().getTypePtr(); 2599 if (const EnumType *ET = dyn_cast<EnumType>(T)) 2600 T = ET->getDecl()->getIntegerType().getTypePtr(); 2601 2602 const BuiltinType *BT = cast<BuiltinType>(T); 2603 assert(BT->isInteger()); 2604 2605 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 2606 } 2607 2608 /// Returns the supremum of two ranges: i.e. their conservative merge. 2609 static IntRange join(IntRange L, IntRange R) { 2610 return IntRange(std::max(L.Width, R.Width), 2611 L.NonNegative && R.NonNegative); 2612 } 2613 2614 /// Returns the infinum of two ranges: i.e. their aggressive merge. 2615 static IntRange meet(IntRange L, IntRange R) { 2616 return IntRange(std::min(L.Width, R.Width), 2617 L.NonNegative || R.NonNegative); 2618 } 2619}; 2620 2621IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 2622 if (value.isSigned() && value.isNegative()) 2623 return IntRange(value.getMinSignedBits(), false); 2624 2625 if (value.getBitWidth() > MaxWidth) 2626 value = value.trunc(MaxWidth); 2627 2628 // isNonNegative() just checks the sign bit without considering 2629 // signedness. 2630 return IntRange(value.getActiveBits(), true); 2631} 2632 2633IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 2634 unsigned MaxWidth) { 2635 if (result.isInt()) 2636 return GetValueRange(C, result.getInt(), MaxWidth); 2637 2638 if (result.isVector()) { 2639 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 2640 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 2641 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 2642 R = IntRange::join(R, El); 2643 } 2644 return R; 2645 } 2646 2647 if (result.isComplexInt()) { 2648 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 2649 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 2650 return IntRange::join(R, I); 2651 } 2652 2653 // This can happen with lossless casts to intptr_t of "based" lvalues. 2654 // Assume it might use arbitrary bits. 2655 // FIXME: The only reason we need to pass the type in here is to get 2656 // the sign right on this one case. It would be nice if APValue 2657 // preserved this. 2658 assert(result.isLValue()); 2659 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 2660} 2661 2662/// Pseudo-evaluate the given integer expression, estimating the 2663/// range of values it might take. 2664/// 2665/// \param MaxWidth - the width to which the value will be truncated 2666IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { 2667 E = E->IgnoreParens(); 2668 2669 // Try a full evaluation first. 2670 Expr::EvalResult result; 2671 if (E->Evaluate(result, C)) 2672 return GetValueRange(C, result.Val, E->getType(), MaxWidth); 2673 2674 // I think we only want to look through implicit casts here; if the 2675 // user has an explicit widening cast, we should treat the value as 2676 // being of the new, wider type. 2677 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 2678 if (CE->getCastKind() == CK_NoOp) 2679 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 2680 2681 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType()); 2682 2683 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast); 2684 2685 // Assume that non-integer casts can span the full range of the type. 2686 if (!isIntegerCast) 2687 return OutputTypeRange; 2688 2689 IntRange SubRange 2690 = GetExprRange(C, CE->getSubExpr(), 2691 std::min(MaxWidth, OutputTypeRange.Width)); 2692 2693 // Bail out if the subexpr's range is as wide as the cast type. 2694 if (SubRange.Width >= OutputTypeRange.Width) 2695 return OutputTypeRange; 2696 2697 // Otherwise, we take the smaller width, and we're non-negative if 2698 // either the output type or the subexpr is. 2699 return IntRange(SubRange.Width, 2700 SubRange.NonNegative || OutputTypeRange.NonNegative); 2701 } 2702 2703 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2704 // If we can fold the condition, just take that operand. 2705 bool CondResult; 2706 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 2707 return GetExprRange(C, CondResult ? CO->getTrueExpr() 2708 : CO->getFalseExpr(), 2709 MaxWidth); 2710 2711 // Otherwise, conservatively merge. 2712 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 2713 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 2714 return IntRange::join(L, R); 2715 } 2716 2717 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2718 switch (BO->getOpcode()) { 2719 2720 // Boolean-valued operations are single-bit and positive. 2721 case BO_LAnd: 2722 case BO_LOr: 2723 case BO_LT: 2724 case BO_GT: 2725 case BO_LE: 2726 case BO_GE: 2727 case BO_EQ: 2728 case BO_NE: 2729 return IntRange::forBoolType(); 2730 2731 // The type of the assignments is the type of the LHS, so the RHS 2732 // is not necessarily the same type. 2733 case BO_MulAssign: 2734 case BO_DivAssign: 2735 case BO_RemAssign: 2736 case BO_AddAssign: 2737 case BO_SubAssign: 2738 case BO_XorAssign: 2739 case BO_OrAssign: 2740 // TODO: bitfields? 2741 return IntRange::forValueOfType(C, E->getType()); 2742 2743 // Simple assignments just pass through the RHS, which will have 2744 // been coerced to the LHS type. 2745 case BO_Assign: 2746 // TODO: bitfields? 2747 return GetExprRange(C, BO->getRHS(), MaxWidth); 2748 2749 // Operations with opaque sources are black-listed. 2750 case BO_PtrMemD: 2751 case BO_PtrMemI: 2752 return IntRange::forValueOfType(C, E->getType()); 2753 2754 // Bitwise-and uses the *infinum* of the two source ranges. 2755 case BO_And: 2756 case BO_AndAssign: 2757 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 2758 GetExprRange(C, BO->getRHS(), MaxWidth)); 2759 2760 // Left shift gets black-listed based on a judgement call. 2761 case BO_Shl: 2762 // ...except that we want to treat '1 << (blah)' as logically 2763 // positive. It's an important idiom. 2764 if (IntegerLiteral *I 2765 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 2766 if (I->getValue() == 1) { 2767 IntRange R = IntRange::forValueOfType(C, E->getType()); 2768 return IntRange(R.Width, /*NonNegative*/ true); 2769 } 2770 } 2771 // fallthrough 2772 2773 case BO_ShlAssign: 2774 return IntRange::forValueOfType(C, E->getType()); 2775 2776 // Right shift by a constant can narrow its left argument. 2777 case BO_Shr: 2778 case BO_ShrAssign: { 2779 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 2780 2781 // If the shift amount is a positive constant, drop the width by 2782 // that much. 2783 llvm::APSInt shift; 2784 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 2785 shift.isNonNegative()) { 2786 unsigned zext = shift.getZExtValue(); 2787 if (zext >= L.Width) 2788 L.Width = (L.NonNegative ? 0 : 1); 2789 else 2790 L.Width -= zext; 2791 } 2792 2793 return L; 2794 } 2795 2796 // Comma acts as its right operand. 2797 case BO_Comma: 2798 return GetExprRange(C, BO->getRHS(), MaxWidth); 2799 2800 // Black-list pointer subtractions. 2801 case BO_Sub: 2802 if (BO->getLHS()->getType()->isPointerType()) 2803 return IntRange::forValueOfType(C, E->getType()); 2804 break; 2805 2806 // The width of a division result is mostly determined by the size 2807 // of the LHS. 2808 case BO_Div: { 2809 // Don't 'pre-truncate' the operands. 2810 unsigned opWidth = C.getIntWidth(E->getType()); 2811 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 2812 2813 // If the divisor is constant, use that. 2814 llvm::APSInt divisor; 2815 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 2816 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 2817 if (log2 >= L.Width) 2818 L.Width = (L.NonNegative ? 0 : 1); 2819 else 2820 L.Width = std::min(L.Width - log2, MaxWidth); 2821 return L; 2822 } 2823 2824 // Otherwise, just use the LHS's width. 2825 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 2826 return IntRange(L.Width, L.NonNegative && R.NonNegative); 2827 } 2828 2829 // The result of a remainder can't be larger than the result of 2830 // either side. 2831 case BO_Rem: { 2832 // Don't 'pre-truncate' the operands. 2833 unsigned opWidth = C.getIntWidth(E->getType()); 2834 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 2835 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 2836 2837 IntRange meet = IntRange::meet(L, R); 2838 meet.Width = std::min(meet.Width, MaxWidth); 2839 return meet; 2840 } 2841 2842 // The default behavior is okay for these. 2843 case BO_Mul: 2844 case BO_Add: 2845 case BO_Xor: 2846 case BO_Or: 2847 break; 2848 } 2849 2850 // The default case is to treat the operation as if it were closed 2851 // on the narrowest type that encompasses both operands. 2852 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 2853 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 2854 return IntRange::join(L, R); 2855 } 2856 2857 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 2858 switch (UO->getOpcode()) { 2859 // Boolean-valued operations are white-listed. 2860 case UO_LNot: 2861 return IntRange::forBoolType(); 2862 2863 // Operations with opaque sources are black-listed. 2864 case UO_Deref: 2865 case UO_AddrOf: // should be impossible 2866 return IntRange::forValueOfType(C, E->getType()); 2867 2868 default: 2869 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 2870 } 2871 } 2872 2873 if (dyn_cast<OffsetOfExpr>(E)) { 2874 IntRange::forValueOfType(C, E->getType()); 2875 } 2876 2877 FieldDecl *BitField = E->getBitField(); 2878 if (BitField) { 2879 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C); 2880 unsigned BitWidth = BitWidthAP.getZExtValue(); 2881 2882 return IntRange(BitWidth, 2883 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 2884 } 2885 2886 return IntRange::forValueOfType(C, E->getType()); 2887} 2888 2889IntRange GetExprRange(ASTContext &C, Expr *E) { 2890 return GetExprRange(C, E, C.getIntWidth(E->getType())); 2891} 2892 2893/// Checks whether the given value, which currently has the given 2894/// source semantics, has the same value when coerced through the 2895/// target semantics. 2896bool IsSameFloatAfterCast(const llvm::APFloat &value, 2897 const llvm::fltSemantics &Src, 2898 const llvm::fltSemantics &Tgt) { 2899 llvm::APFloat truncated = value; 2900 2901 bool ignored; 2902 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 2903 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 2904 2905 return truncated.bitwiseIsEqual(value); 2906} 2907 2908/// Checks whether the given value, which currently has the given 2909/// source semantics, has the same value when coerced through the 2910/// target semantics. 2911/// 2912/// The value might be a vector of floats (or a complex number). 2913bool IsSameFloatAfterCast(const APValue &value, 2914 const llvm::fltSemantics &Src, 2915 const llvm::fltSemantics &Tgt) { 2916 if (value.isFloat()) 2917 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 2918 2919 if (value.isVector()) { 2920 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 2921 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 2922 return false; 2923 return true; 2924 } 2925 2926 assert(value.isComplexFloat()); 2927 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 2928 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 2929} 2930 2931void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 2932 2933static bool IsZero(Sema &S, Expr *E) { 2934 // Suppress cases where we are comparing against an enum constant. 2935 if (const DeclRefExpr *DR = 2936 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 2937 if (isa<EnumConstantDecl>(DR->getDecl())) 2938 return false; 2939 2940 // Suppress cases where the '0' value is expanded from a macro. 2941 if (E->getLocStart().isMacroID()) 2942 return false; 2943 2944 llvm::APSInt Value; 2945 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 2946} 2947 2948static bool HasEnumType(Expr *E) { 2949 // Strip off implicit integral promotions. 2950 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 2951 if (ICE->getCastKind() != CK_IntegralCast && 2952 ICE->getCastKind() != CK_NoOp) 2953 break; 2954 E = ICE->getSubExpr(); 2955 } 2956 2957 return E->getType()->isEnumeralType(); 2958} 2959 2960void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 2961 BinaryOperatorKind op = E->getOpcode(); 2962 if (E->isValueDependent()) 2963 return; 2964 2965 if (op == BO_LT && IsZero(S, E->getRHS())) { 2966 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 2967 << "< 0" << "false" << HasEnumType(E->getLHS()) 2968 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 2969 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 2970 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 2971 << ">= 0" << "true" << HasEnumType(E->getLHS()) 2972 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 2973 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 2974 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 2975 << "0 >" << "false" << HasEnumType(E->getRHS()) 2976 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 2977 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 2978 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 2979 << "0 <=" << "true" << HasEnumType(E->getRHS()) 2980 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 2981 } 2982} 2983 2984/// Analyze the operands of the given comparison. Implements the 2985/// fallback case from AnalyzeComparison. 2986void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 2987 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 2988 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 2989} 2990 2991/// \brief Implements -Wsign-compare. 2992/// 2993/// \param lex the left-hand expression 2994/// \param rex the right-hand expression 2995/// \param OpLoc the location of the joining operator 2996/// \param BinOpc binary opcode or 0 2997void AnalyzeComparison(Sema &S, BinaryOperator *E) { 2998 // The type the comparison is being performed in. 2999 QualType T = E->getLHS()->getType(); 3000 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()) 3001 && "comparison with mismatched types"); 3002 3003 // We don't do anything special if this isn't an unsigned integral 3004 // comparison: we're only interested in integral comparisons, and 3005 // signed comparisons only happen in cases we don't care to warn about. 3006 // 3007 // We also don't care about value-dependent expressions or expressions 3008 // whose result is a constant. 3009 if (!T->hasUnsignedIntegerRepresentation() 3010 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context)) 3011 return AnalyzeImpConvsInComparison(S, E); 3012 3013 Expr *lex = E->getLHS()->IgnoreParenImpCasts(); 3014 Expr *rex = E->getRHS()->IgnoreParenImpCasts(); 3015 3016 // Check to see if one of the (unmodified) operands is of different 3017 // signedness. 3018 Expr *signedOperand, *unsignedOperand; 3019 if (lex->getType()->hasSignedIntegerRepresentation()) { 3020 assert(!rex->getType()->hasSignedIntegerRepresentation() && 3021 "unsigned comparison between two signed integer expressions?"); 3022 signedOperand = lex; 3023 unsignedOperand = rex; 3024 } else if (rex->getType()->hasSignedIntegerRepresentation()) { 3025 signedOperand = rex; 3026 unsignedOperand = lex; 3027 } else { 3028 CheckTrivialUnsignedComparison(S, E); 3029 return AnalyzeImpConvsInComparison(S, E); 3030 } 3031 3032 // Otherwise, calculate the effective range of the signed operand. 3033 IntRange signedRange = GetExprRange(S.Context, signedOperand); 3034 3035 // Go ahead and analyze implicit conversions in the operands. Note 3036 // that we skip the implicit conversions on both sides. 3037 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc()); 3038 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc()); 3039 3040 // If the signed range is non-negative, -Wsign-compare won't fire, 3041 // but we should still check for comparisons which are always true 3042 // or false. 3043 if (signedRange.NonNegative) 3044 return CheckTrivialUnsignedComparison(S, E); 3045 3046 // For (in)equality comparisons, if the unsigned operand is a 3047 // constant which cannot collide with a overflowed signed operand, 3048 // then reinterpreting the signed operand as unsigned will not 3049 // change the result of the comparison. 3050 if (E->isEqualityOp()) { 3051 unsigned comparisonWidth = S.Context.getIntWidth(T); 3052 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 3053 3054 // We should never be unable to prove that the unsigned operand is 3055 // non-negative. 3056 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 3057 3058 if (unsignedRange.Width < comparisonWidth) 3059 return; 3060 } 3061 3062 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison) 3063 << lex->getType() << rex->getType() 3064 << lex->getSourceRange() << rex->getSourceRange(); 3065} 3066 3067/// Analyzes an attempt to assign the given value to a bitfield. 3068/// 3069/// Returns true if there was something fishy about the attempt. 3070bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 3071 SourceLocation InitLoc) { 3072 assert(Bitfield->isBitField()); 3073 if (Bitfield->isInvalidDecl()) 3074 return false; 3075 3076 // White-list bool bitfields. 3077 if (Bitfield->getType()->isBooleanType()) 3078 return false; 3079 3080 // Ignore value- or type-dependent expressions. 3081 if (Bitfield->getBitWidth()->isValueDependent() || 3082 Bitfield->getBitWidth()->isTypeDependent() || 3083 Init->isValueDependent() || 3084 Init->isTypeDependent()) 3085 return false; 3086 3087 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 3088 3089 llvm::APSInt Width(32); 3090 Expr::EvalResult InitValue; 3091 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) || 3092 !OriginalInit->Evaluate(InitValue, S.Context) || 3093 !InitValue.Val.isInt()) 3094 return false; 3095 3096 const llvm::APSInt &Value = InitValue.Val.getInt(); 3097 unsigned OriginalWidth = Value.getBitWidth(); 3098 unsigned FieldWidth = Width.getZExtValue(); 3099 3100 if (OriginalWidth <= FieldWidth) 3101 return false; 3102 3103 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 3104 3105 // It's fairly common to write values into signed bitfields 3106 // that, if sign-extended, would end up becoming a different 3107 // value. We don't want to warn about that. 3108 if (Value.isSigned() && Value.isNegative()) 3109 TruncatedValue = TruncatedValue.sext(OriginalWidth); 3110 else 3111 TruncatedValue = TruncatedValue.zext(OriginalWidth); 3112 3113 if (Value == TruncatedValue) 3114 return false; 3115 3116 std::string PrettyValue = Value.toString(10); 3117 std::string PrettyTrunc = TruncatedValue.toString(10); 3118 3119 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 3120 << PrettyValue << PrettyTrunc << OriginalInit->getType() 3121 << Init->getSourceRange(); 3122 3123 return true; 3124} 3125 3126/// Analyze the given simple or compound assignment for warning-worthy 3127/// operations. 3128void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 3129 // Just recurse on the LHS. 3130 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 3131 3132 // We want to recurse on the RHS as normal unless we're assigning to 3133 // a bitfield. 3134 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) { 3135 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 3136 E->getOperatorLoc())) { 3137 // Recurse, ignoring any implicit conversions on the RHS. 3138 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 3139 E->getOperatorLoc()); 3140 } 3141 } 3142 3143 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 3144} 3145 3146/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 3147void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 3148 SourceLocation CContext, unsigned diag) { 3149 S.Diag(E->getExprLoc(), diag) 3150 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 3151} 3152 3153/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 3154void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 3155 unsigned diag) { 3156 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag); 3157} 3158 3159/// Diagnose an implicit cast from a literal expression. Also attemps to supply 3160/// fixit hints when the cast wouldn't lose information to simply write the 3161/// expression with the expected type. 3162void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T, 3163 SourceLocation CContext) { 3164 // Emit the primary warning first, then try to emit a fixit hint note if 3165 // reasonable. 3166 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer) 3167 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext); 3168 3169 const llvm::APFloat &Value = FL->getValue(); 3170 3171 // Don't attempt to fix PPC double double literals. 3172 if (&Value.getSemantics() == &llvm::APFloat::PPCDoubleDouble) 3173 return; 3174 3175 // Try to convert this exactly to an integer. 3176 bool isExact = false; 3177 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 3178 T->hasUnsignedIntegerRepresentation()); 3179 if (Value.convertToInteger(IntegerValue, 3180 llvm::APFloat::rmTowardZero, &isExact) 3181 != llvm::APFloat::opOK || !isExact) 3182 return; 3183 3184 std::string LiteralValue = IntegerValue.toString(10); 3185 S.Diag(FL->getExprLoc(), diag::note_fix_integral_float_as_integer) 3186 << FixItHint::CreateReplacement(FL->getSourceRange(), LiteralValue); 3187} 3188 3189std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 3190 if (!Range.Width) return "0"; 3191 3192 llvm::APSInt ValueInRange = Value; 3193 ValueInRange.setIsSigned(!Range.NonNegative); 3194 ValueInRange = ValueInRange.trunc(Range.Width); 3195 return ValueInRange.toString(10); 3196} 3197 3198static bool isFromSystemMacro(Sema &S, SourceLocation loc) { 3199 SourceManager &smgr = S.Context.getSourceManager(); 3200 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc)); 3201} 3202 3203void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 3204 SourceLocation CC, bool *ICContext = 0) { 3205 if (E->isTypeDependent() || E->isValueDependent()) return; 3206 3207 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 3208 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 3209 if (Source == Target) return; 3210 if (Target->isDependentType()) return; 3211 3212 // If the conversion context location is invalid don't complain. We also 3213 // don't want to emit a warning if the issue occurs from the expansion of 3214 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 3215 // delay this check as long as possible. Once we detect we are in that 3216 // scenario, we just return. 3217 if (CC.isInvalid()) 3218 return; 3219 3220 // Never diagnose implicit casts to bool. 3221 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 3222 return; 3223 3224 // Strip vector types. 3225 if (isa<VectorType>(Source)) { 3226 if (!isa<VectorType>(Target)) { 3227 if (isFromSystemMacro(S, CC)) 3228 return; 3229 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 3230 } 3231 3232 // If the vector cast is cast between two vectors of the same size, it is 3233 // a bitcast, not a conversion. 3234 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 3235 return; 3236 3237 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 3238 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 3239 } 3240 3241 // Strip complex types. 3242 if (isa<ComplexType>(Source)) { 3243 if (!isa<ComplexType>(Target)) { 3244 if (isFromSystemMacro(S, CC)) 3245 return; 3246 3247 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 3248 } 3249 3250 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 3251 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 3252 } 3253 3254 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 3255 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 3256 3257 // If the source is floating point... 3258 if (SourceBT && SourceBT->isFloatingPoint()) { 3259 // ...and the target is floating point... 3260 if (TargetBT && TargetBT->isFloatingPoint()) { 3261 // ...then warn if we're dropping FP rank. 3262 3263 // Builtin FP kinds are ordered by increasing FP rank. 3264 if (SourceBT->getKind() > TargetBT->getKind()) { 3265 // Don't warn about float constants that are precisely 3266 // representable in the target type. 3267 Expr::EvalResult result; 3268 if (E->Evaluate(result, S.Context)) { 3269 // Value might be a float, a float vector, or a float complex. 3270 if (IsSameFloatAfterCast(result.Val, 3271 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 3272 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 3273 return; 3274 } 3275 3276 if (isFromSystemMacro(S, CC)) 3277 return; 3278 3279 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 3280 } 3281 return; 3282 } 3283 3284 // If the target is integral, always warn. 3285 if ((TargetBT && TargetBT->isInteger())) { 3286 if (isFromSystemMacro(S, CC)) 3287 return; 3288 3289 Expr *InnerE = E->IgnoreParenImpCasts(); 3290 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) { 3291 DiagnoseFloatingLiteralImpCast(S, FL, T, CC); 3292 } else { 3293 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer); 3294 } 3295 } 3296 3297 return; 3298 } 3299 3300 if (!Source->isIntegerType() || !Target->isIntegerType()) 3301 return; 3302 3303 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) 3304 == Expr::NPCK_GNUNull) && Target->isIntegerType()) { 3305 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer) 3306 << E->getSourceRange() << clang::SourceRange(CC); 3307 return; 3308 } 3309 3310 IntRange SourceRange = GetExprRange(S.Context, E); 3311 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 3312 3313 if (SourceRange.Width > TargetRange.Width) { 3314 // If the source is a constant, use a default-on diagnostic. 3315 // TODO: this should happen for bitfield stores, too. 3316 llvm::APSInt Value(32); 3317 if (E->isIntegerConstantExpr(Value, S.Context)) { 3318 if (isFromSystemMacro(S, CC)) 3319 return; 3320 3321 std::string PrettySourceValue = Value.toString(10); 3322 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 3323 3324 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant) 3325 << PrettySourceValue << PrettyTargetValue 3326 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC); 3327 return; 3328 } 3329 3330 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 3331 if (isFromSystemMacro(S, CC)) 3332 return; 3333 3334 if (SourceRange.Width == 64 && TargetRange.Width == 32) 3335 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32); 3336 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 3337 } 3338 3339 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 3340 (!TargetRange.NonNegative && SourceRange.NonNegative && 3341 SourceRange.Width == TargetRange.Width)) { 3342 3343 if (isFromSystemMacro(S, CC)) 3344 return; 3345 3346 unsigned DiagID = diag::warn_impcast_integer_sign; 3347 3348 // Traditionally, gcc has warned about this under -Wsign-compare. 3349 // We also want to warn about it in -Wconversion. 3350 // So if -Wconversion is off, use a completely identical diagnostic 3351 // in the sign-compare group. 3352 // The conditional-checking code will 3353 if (ICContext) { 3354 DiagID = diag::warn_impcast_integer_sign_conditional; 3355 *ICContext = true; 3356 } 3357 3358 return DiagnoseImpCast(S, E, T, CC, DiagID); 3359 } 3360 3361 // Diagnose conversions between different enumeration types. 3362 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 3363 // type, to give us better diagnostics. 3364 QualType SourceType = E->getType(); 3365 if (!S.getLangOptions().CPlusPlus) { 3366 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 3367 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 3368 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 3369 SourceType = S.Context.getTypeDeclType(Enum); 3370 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 3371 } 3372 } 3373 3374 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 3375 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 3376 if ((SourceEnum->getDecl()->getIdentifier() || 3377 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) && 3378 (TargetEnum->getDecl()->getIdentifier() || 3379 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) && 3380 SourceEnum != TargetEnum) { 3381 if (isFromSystemMacro(S, CC)) 3382 return; 3383 3384 return DiagnoseImpCast(S, E, SourceType, T, CC, 3385 diag::warn_impcast_different_enum_types); 3386 } 3387 3388 return; 3389} 3390 3391void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T); 3392 3393void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 3394 SourceLocation CC, bool &ICContext) { 3395 E = E->IgnoreParenImpCasts(); 3396 3397 if (isa<ConditionalOperator>(E)) 3398 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T); 3399 3400 AnalyzeImplicitConversions(S, E, CC); 3401 if (E->getType() != T) 3402 return CheckImplicitConversion(S, E, T, CC, &ICContext); 3403 return; 3404} 3405 3406void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) { 3407 SourceLocation CC = E->getQuestionLoc(); 3408 3409 AnalyzeImplicitConversions(S, E->getCond(), CC); 3410 3411 bool Suspicious = false; 3412 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 3413 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 3414 3415 // If -Wconversion would have warned about either of the candidates 3416 // for a signedness conversion to the context type... 3417 if (!Suspicious) return; 3418 3419 // ...but it's currently ignored... 3420 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional, 3421 CC)) 3422 return; 3423 3424 // ...then check whether it would have warned about either of the 3425 // candidates for a signedness conversion to the condition type. 3426 if (E->getType() == T) return; 3427 3428 Suspicious = false; 3429 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 3430 E->getType(), CC, &Suspicious); 3431 if (!Suspicious) 3432 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 3433 E->getType(), CC, &Suspicious); 3434} 3435 3436/// AnalyzeImplicitConversions - Find and report any interesting 3437/// implicit conversions in the given expression. There are a couple 3438/// of competing diagnostics here, -Wconversion and -Wsign-compare. 3439void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 3440 QualType T = OrigE->getType(); 3441 Expr *E = OrigE->IgnoreParenImpCasts(); 3442 3443 // For conditional operators, we analyze the arguments as if they 3444 // were being fed directly into the output. 3445 if (isa<ConditionalOperator>(E)) { 3446 ConditionalOperator *CO = cast<ConditionalOperator>(E); 3447 CheckConditionalOperator(S, CO, T); 3448 return; 3449 } 3450 3451 // Go ahead and check any implicit conversions we might have skipped. 3452 // The non-canonical typecheck is just an optimization; 3453 // CheckImplicitConversion will filter out dead implicit conversions. 3454 if (E->getType() != T) 3455 CheckImplicitConversion(S, E, T, CC); 3456 3457 // Now continue drilling into this expression. 3458 3459 // Skip past explicit casts. 3460 if (isa<ExplicitCastExpr>(E)) { 3461 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 3462 return AnalyzeImplicitConversions(S, E, CC); 3463 } 3464 3465 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3466 // Do a somewhat different check with comparison operators. 3467 if (BO->isComparisonOp()) 3468 return AnalyzeComparison(S, BO); 3469 3470 // And with assignments and compound assignments. 3471 if (BO->isAssignmentOp()) 3472 return AnalyzeAssignment(S, BO); 3473 } 3474 3475 // These break the otherwise-useful invariant below. Fortunately, 3476 // we don't really need to recurse into them, because any internal 3477 // expressions should have been analyzed already when they were 3478 // built into statements. 3479 if (isa<StmtExpr>(E)) return; 3480 3481 // Don't descend into unevaluated contexts. 3482 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 3483 3484 // Now just recurse over the expression's children. 3485 CC = E->getExprLoc(); 3486 for (Stmt::child_range I = E->children(); I; ++I) 3487 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC); 3488} 3489 3490} // end anonymous namespace 3491 3492/// Diagnoses "dangerous" implicit conversions within the given 3493/// expression (which is a full expression). Implements -Wconversion 3494/// and -Wsign-compare. 3495/// 3496/// \param CC the "context" location of the implicit conversion, i.e. 3497/// the most location of the syntactic entity requiring the implicit 3498/// conversion 3499void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 3500 // Don't diagnose in unevaluated contexts. 3501 if (ExprEvalContexts.back().Context == Sema::Unevaluated) 3502 return; 3503 3504 // Don't diagnose for value- or type-dependent expressions. 3505 if (E->isTypeDependent() || E->isValueDependent()) 3506 return; 3507 3508 // Check for array bounds violations in cases where the check isn't triggered 3509 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 3510 // ArraySubscriptExpr is on the RHS of a variable initialization. 3511 CheckArrayAccess(E); 3512 3513 // This is not the right CC for (e.g.) a variable initialization. 3514 AnalyzeImplicitConversions(*this, E, CC); 3515} 3516 3517void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 3518 FieldDecl *BitField, 3519 Expr *Init) { 3520 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 3521} 3522 3523/// CheckParmsForFunctionDef - Check that the parameters of the given 3524/// function are appropriate for the definition of a function. This 3525/// takes care of any checks that cannot be performed on the 3526/// declaration itself, e.g., that the types of each of the function 3527/// parameters are complete. 3528bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd, 3529 bool CheckParameterNames) { 3530 bool HasInvalidParm = false; 3531 for (; P != PEnd; ++P) { 3532 ParmVarDecl *Param = *P; 3533 3534 // C99 6.7.5.3p4: the parameters in a parameter type list in a 3535 // function declarator that is part of a function definition of 3536 // that function shall not have incomplete type. 3537 // 3538 // This is also C++ [dcl.fct]p6. 3539 if (!Param->isInvalidDecl() && 3540 RequireCompleteType(Param->getLocation(), Param->getType(), 3541 diag::err_typecheck_decl_incomplete_type)) { 3542 Param->setInvalidDecl(); 3543 HasInvalidParm = true; 3544 } 3545 3546 // C99 6.9.1p5: If the declarator includes a parameter type list, the 3547 // declaration of each parameter shall include an identifier. 3548 if (CheckParameterNames && 3549 Param->getIdentifier() == 0 && 3550 !Param->isImplicit() && 3551 !getLangOptions().CPlusPlus) 3552 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 3553 3554 // C99 6.7.5.3p12: 3555 // If the function declarator is not part of a definition of that 3556 // function, parameters may have incomplete type and may use the [*] 3557 // notation in their sequences of declarator specifiers to specify 3558 // variable length array types. 3559 QualType PType = Param->getOriginalType(); 3560 if (const ArrayType *AT = Context.getAsArrayType(PType)) { 3561 if (AT->getSizeModifier() == ArrayType::Star) { 3562 // FIXME: This diagnosic should point the the '[*]' if source-location 3563 // information is added for it. 3564 Diag(Param->getLocation(), diag::err_array_star_in_function_definition); 3565 } 3566 } 3567 } 3568 3569 return HasInvalidParm; 3570} 3571 3572/// CheckCastAlign - Implements -Wcast-align, which warns when a 3573/// pointer cast increases the alignment requirements. 3574void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 3575 // This is actually a lot of work to potentially be doing on every 3576 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 3577 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align, 3578 TRange.getBegin()) 3579 == Diagnostic::Ignored) 3580 return; 3581 3582 // Ignore dependent types. 3583 if (T->isDependentType() || Op->getType()->isDependentType()) 3584 return; 3585 3586 // Require that the destination be a pointer type. 3587 const PointerType *DestPtr = T->getAs<PointerType>(); 3588 if (!DestPtr) return; 3589 3590 // If the destination has alignment 1, we're done. 3591 QualType DestPointee = DestPtr->getPointeeType(); 3592 if (DestPointee->isIncompleteType()) return; 3593 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 3594 if (DestAlign.isOne()) return; 3595 3596 // Require that the source be a pointer type. 3597 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 3598 if (!SrcPtr) return; 3599 QualType SrcPointee = SrcPtr->getPointeeType(); 3600 3601 // Whitelist casts from cv void*. We already implicitly 3602 // whitelisted casts to cv void*, since they have alignment 1. 3603 // Also whitelist casts involving incomplete types, which implicitly 3604 // includes 'void'. 3605 if (SrcPointee->isIncompleteType()) return; 3606 3607 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 3608 if (SrcAlign >= DestAlign) return; 3609 3610 Diag(TRange.getBegin(), diag::warn_cast_align) 3611 << Op->getType() << T 3612 << static_cast<unsigned>(SrcAlign.getQuantity()) 3613 << static_cast<unsigned>(DestAlign.getQuantity()) 3614 << TRange << Op->getSourceRange(); 3615} 3616 3617static const Type* getElementType(const Expr *BaseExpr) { 3618 const Type* EltType = BaseExpr->getType().getTypePtr(); 3619 if (EltType->isAnyPointerType()) 3620 return EltType->getPointeeType().getTypePtr(); 3621 else if (EltType->isArrayType()) 3622 return EltType->getBaseElementTypeUnsafe(); 3623 return EltType; 3624} 3625 3626/// \brief Check whether this array fits the idiom of a size-one tail padded 3627/// array member of a struct. 3628/// 3629/// We avoid emitting out-of-bounds access warnings for such arrays as they are 3630/// commonly used to emulate flexible arrays in C89 code. 3631static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size, 3632 const NamedDecl *ND) { 3633 if (Size != 1 || !ND) return false; 3634 3635 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 3636 if (!FD) return false; 3637 3638 // Don't consider sizes resulting from macro expansions or template argument 3639 // substitution to form C89 tail-padded arrays. 3640 ConstantArrayTypeLoc TL = 3641 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc()); 3642 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr()); 3643 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 3644 return false; 3645 3646 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 3647 if (!RD || !RD->isStruct()) 3648 return false; 3649 3650 // See if this is the last field decl in the record. 3651 const Decl *D = FD; 3652 while ((D = D->getNextDeclInContext())) 3653 if (isa<FieldDecl>(D)) 3654 return false; 3655 return true; 3656} 3657 3658void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 3659 bool isSubscript, bool AllowOnePastEnd) { 3660 const Type* EffectiveType = getElementType(BaseExpr); 3661 BaseExpr = BaseExpr->IgnoreParenCasts(); 3662 IndexExpr = IndexExpr->IgnoreParenCasts(); 3663 3664 const ConstantArrayType *ArrayTy = 3665 Context.getAsConstantArrayType(BaseExpr->getType()); 3666 if (!ArrayTy) 3667 return; 3668 3669 if (IndexExpr->isValueDependent()) 3670 return; 3671 llvm::APSInt index; 3672 if (!IndexExpr->isIntegerConstantExpr(index, Context)) 3673 return; 3674 3675 const NamedDecl *ND = NULL; 3676 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 3677 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 3678 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 3679 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 3680 3681 if (index.isUnsigned() || !index.isNegative()) { 3682 llvm::APInt size = ArrayTy->getSize(); 3683 if (!size.isStrictlyPositive()) 3684 return; 3685 3686 const Type* BaseType = getElementType(BaseExpr); 3687 if (!isSubscript && BaseType != EffectiveType) { 3688 // Make sure we're comparing apples to apples when comparing index to size 3689 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 3690 uint64_t array_typesize = Context.getTypeSize(BaseType); 3691 // Handle ptrarith_typesize being zero, such as when casting to void* 3692 if (!ptrarith_typesize) ptrarith_typesize = 1; 3693 if (ptrarith_typesize != array_typesize) { 3694 // There's a cast to a different size type involved 3695 uint64_t ratio = array_typesize / ptrarith_typesize; 3696 // TODO: Be smarter about handling cases where array_typesize is not a 3697 // multiple of ptrarith_typesize 3698 if (ptrarith_typesize * ratio == array_typesize) 3699 size *= llvm::APInt(size.getBitWidth(), ratio); 3700 } 3701 } 3702 3703 if (size.getBitWidth() > index.getBitWidth()) 3704 index = index.sext(size.getBitWidth()); 3705 else if (size.getBitWidth() < index.getBitWidth()) 3706 size = size.sext(index.getBitWidth()); 3707 3708 // For array subscripting the index must be less than size, but for pointer 3709 // arithmetic also allow the index (offset) to be equal to size since 3710 // computing the next address after the end of the array is legal and 3711 // commonly done e.g. in C++ iterators and range-based for loops. 3712 if (AllowOnePastEnd ? index.sle(size) : index.slt(size)) 3713 return; 3714 3715 // Also don't warn for arrays of size 1 which are members of some 3716 // structure. These are often used to approximate flexible arrays in C89 3717 // code. 3718 if (IsTailPaddedMemberArray(*this, size, ND)) 3719 return; 3720 3721 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 3722 if (isSubscript) 3723 DiagID = diag::warn_array_index_exceeds_bounds; 3724 3725 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 3726 PDiag(DiagID) << index.toString(10, true) 3727 << size.toString(10, true) 3728 << (unsigned)size.getLimitedValue(~0U) 3729 << IndexExpr->getSourceRange()); 3730 } else { 3731 unsigned DiagID = diag::warn_array_index_precedes_bounds; 3732 if (!isSubscript) { 3733 DiagID = diag::warn_ptr_arith_precedes_bounds; 3734 if (index.isNegative()) index = -index; 3735 } 3736 3737 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 3738 PDiag(DiagID) << index.toString(10, true) 3739 << IndexExpr->getSourceRange()); 3740 } 3741 3742 if (ND) 3743 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 3744 PDiag(diag::note_array_index_out_of_bounds) 3745 << ND->getDeclName()); 3746} 3747 3748void Sema::CheckArrayAccess(const Expr *expr) { 3749 int AllowOnePastEnd = 0; 3750 while (expr) { 3751 expr = expr->IgnoreParenImpCasts(); 3752 switch (expr->getStmtClass()) { 3753 case Stmt::ArraySubscriptExprClass: { 3754 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 3755 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true, 3756 AllowOnePastEnd > 0); 3757 return; 3758 } 3759 case Stmt::UnaryOperatorClass: { 3760 // Only unwrap the * and & unary operators 3761 const UnaryOperator *UO = cast<UnaryOperator>(expr); 3762 expr = UO->getSubExpr(); 3763 switch (UO->getOpcode()) { 3764 case UO_AddrOf: 3765 AllowOnePastEnd++; 3766 break; 3767 case UO_Deref: 3768 AllowOnePastEnd--; 3769 break; 3770 default: 3771 return; 3772 } 3773 break; 3774 } 3775 case Stmt::ConditionalOperatorClass: { 3776 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 3777 if (const Expr *lhs = cond->getLHS()) 3778 CheckArrayAccess(lhs); 3779 if (const Expr *rhs = cond->getRHS()) 3780 CheckArrayAccess(rhs); 3781 return; 3782 } 3783 default: 3784 return; 3785 } 3786 } 3787} 3788 3789//===--- CHECK: Objective-C retain cycles ----------------------------------// 3790 3791namespace { 3792 struct RetainCycleOwner { 3793 RetainCycleOwner() : Variable(0), Indirect(false) {} 3794 VarDecl *Variable; 3795 SourceRange Range; 3796 SourceLocation Loc; 3797 bool Indirect; 3798 3799 void setLocsFrom(Expr *e) { 3800 Loc = e->getExprLoc(); 3801 Range = e->getSourceRange(); 3802 } 3803 }; 3804} 3805 3806/// Consider whether capturing the given variable can possibly lead to 3807/// a retain cycle. 3808static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 3809 // In ARC, it's captured strongly iff the variable has __strong 3810 // lifetime. In MRR, it's captured strongly if the variable is 3811 // __block and has an appropriate type. 3812 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 3813 return false; 3814 3815 owner.Variable = var; 3816 owner.setLocsFrom(ref); 3817 return true; 3818} 3819 3820static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) { 3821 while (true) { 3822 e = e->IgnoreParens(); 3823 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 3824 switch (cast->getCastKind()) { 3825 case CK_BitCast: 3826 case CK_LValueBitCast: 3827 case CK_LValueToRValue: 3828 case CK_ObjCReclaimReturnedObject: 3829 e = cast->getSubExpr(); 3830 continue; 3831 3832 case CK_GetObjCProperty: { 3833 // Bail out if this isn't a strong explicit property. 3834 const ObjCPropertyRefExpr *pre = cast->getSubExpr()->getObjCProperty(); 3835 if (pre->isImplicitProperty()) return false; 3836 ObjCPropertyDecl *property = pre->getExplicitProperty(); 3837 if (!(property->getPropertyAttributes() & 3838 (ObjCPropertyDecl::OBJC_PR_retain | 3839 ObjCPropertyDecl::OBJC_PR_copy | 3840 ObjCPropertyDecl::OBJC_PR_strong)) && 3841 !(property->getPropertyIvarDecl() && 3842 property->getPropertyIvarDecl()->getType() 3843 .getObjCLifetime() == Qualifiers::OCL_Strong)) 3844 return false; 3845 3846 owner.Indirect = true; 3847 e = const_cast<Expr*>(pre->getBase()); 3848 continue; 3849 } 3850 3851 default: 3852 return false; 3853 } 3854 } 3855 3856 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 3857 ObjCIvarDecl *ivar = ref->getDecl(); 3858 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 3859 return false; 3860 3861 // Try to find a retain cycle in the base. 3862 if (!findRetainCycleOwner(ref->getBase(), owner)) 3863 return false; 3864 3865 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 3866 owner.Indirect = true; 3867 return true; 3868 } 3869 3870 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 3871 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 3872 if (!var) return false; 3873 return considerVariable(var, ref, owner); 3874 } 3875 3876 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) { 3877 owner.Variable = ref->getDecl(); 3878 owner.setLocsFrom(ref); 3879 return true; 3880 } 3881 3882 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 3883 if (member->isArrow()) return false; 3884 3885 // Don't count this as an indirect ownership. 3886 e = member->getBase(); 3887 continue; 3888 } 3889 3890 // Array ivars? 3891 3892 return false; 3893 } 3894} 3895 3896namespace { 3897 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 3898 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 3899 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 3900 Variable(variable), Capturer(0) {} 3901 3902 VarDecl *Variable; 3903 Expr *Capturer; 3904 3905 void VisitDeclRefExpr(DeclRefExpr *ref) { 3906 if (ref->getDecl() == Variable && !Capturer) 3907 Capturer = ref; 3908 } 3909 3910 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) { 3911 if (ref->getDecl() == Variable && !Capturer) 3912 Capturer = ref; 3913 } 3914 3915 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 3916 if (Capturer) return; 3917 Visit(ref->getBase()); 3918 if (Capturer && ref->isFreeIvar()) 3919 Capturer = ref; 3920 } 3921 3922 void VisitBlockExpr(BlockExpr *block) { 3923 // Look inside nested blocks 3924 if (block->getBlockDecl()->capturesVariable(Variable)) 3925 Visit(block->getBlockDecl()->getBody()); 3926 } 3927 }; 3928} 3929 3930/// Check whether the given argument is a block which captures a 3931/// variable. 3932static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 3933 assert(owner.Variable && owner.Loc.isValid()); 3934 3935 e = e->IgnoreParenCasts(); 3936 BlockExpr *block = dyn_cast<BlockExpr>(e); 3937 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 3938 return 0; 3939 3940 FindCaptureVisitor visitor(S.Context, owner.Variable); 3941 visitor.Visit(block->getBlockDecl()->getBody()); 3942 return visitor.Capturer; 3943} 3944 3945static void diagnoseRetainCycle(Sema &S, Expr *capturer, 3946 RetainCycleOwner &owner) { 3947 assert(capturer); 3948 assert(owner.Variable && owner.Loc.isValid()); 3949 3950 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 3951 << owner.Variable << capturer->getSourceRange(); 3952 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 3953 << owner.Indirect << owner.Range; 3954} 3955 3956/// Check for a keyword selector that starts with the word 'add' or 3957/// 'set'. 3958static bool isSetterLikeSelector(Selector sel) { 3959 if (sel.isUnarySelector()) return false; 3960 3961 StringRef str = sel.getNameForSlot(0); 3962 while (!str.empty() && str.front() == '_') str = str.substr(1); 3963 if (str.startswith("set") || str.startswith("add")) 3964 str = str.substr(3); 3965 else 3966 return false; 3967 3968 if (str.empty()) return true; 3969 return !islower(str.front()); 3970} 3971 3972/// Check a message send to see if it's likely to cause a retain cycle. 3973void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 3974 // Only check instance methods whose selector looks like a setter. 3975 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 3976 return; 3977 3978 // Try to find a variable that the receiver is strongly owned by. 3979 RetainCycleOwner owner; 3980 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 3981 if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner)) 3982 return; 3983 } else { 3984 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 3985 owner.Variable = getCurMethodDecl()->getSelfDecl(); 3986 owner.Loc = msg->getSuperLoc(); 3987 owner.Range = msg->getSuperLoc(); 3988 } 3989 3990 // Check whether the receiver is captured by any of the arguments. 3991 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 3992 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 3993 return diagnoseRetainCycle(*this, capturer, owner); 3994} 3995 3996/// Check a property assign to see if it's likely to cause a retain cycle. 3997void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 3998 RetainCycleOwner owner; 3999 if (!findRetainCycleOwner(receiver, owner)) 4000 return; 4001 4002 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 4003 diagnoseRetainCycle(*this, capturer, owner); 4004} 4005 4006bool Sema::checkUnsafeAssigns(SourceLocation Loc, 4007 QualType LHS, Expr *RHS) { 4008 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 4009 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 4010 return false; 4011 // strip off any implicit cast added to get to the one arc-specific 4012 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 4013 if (cast->getCastKind() == CK_ObjCConsumeObject) { 4014 Diag(Loc, diag::warn_arc_retained_assign) 4015 << (LT == Qualifiers::OCL_ExplicitNone) 4016 << RHS->getSourceRange(); 4017 return true; 4018 } 4019 RHS = cast->getSubExpr(); 4020 } 4021 return false; 4022} 4023 4024void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 4025 Expr *LHS, Expr *RHS) { 4026 QualType LHSType = LHS->getType(); 4027 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 4028 return; 4029 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 4030 // FIXME. Check for other life times. 4031 if (LT != Qualifiers::OCL_None) 4032 return; 4033 4034 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(LHS)) { 4035 if (PRE->isImplicitProperty()) 4036 return; 4037 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 4038 if (!PD) 4039 return; 4040 4041 unsigned Attributes = PD->getPropertyAttributes(); 4042 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) 4043 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 4044 if (cast->getCastKind() == CK_ObjCConsumeObject) { 4045 Diag(Loc, diag::warn_arc_retained_property_assign) 4046 << RHS->getSourceRange(); 4047 return; 4048 } 4049 RHS = cast->getSubExpr(); 4050 } 4051 } 4052} 4053