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