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