SemaChecking.cpp revision 9c127392efe91dadacbe28ca16b8a9a5fa7990b3
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 "Sema.h" 16#include "clang/Analysis/Analyses/PrintfFormatString.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/CharUnits.h" 19#include "clang/AST/DeclObjC.h" 20#include "clang/AST/ExprCXX.h" 21#include "clang/AST/ExprObjC.h" 22#include "clang/AST/DeclObjC.h" 23#include "clang/AST/StmtCXX.h" 24#include "clang/AST/StmtObjC.h" 25#include "clang/Lex/LiteralSupport.h" 26#include "clang/Lex/Preprocessor.h" 27#include "llvm/ADT/BitVector.h" 28#include "llvm/ADT/STLExtras.h" 29#include <limits> 30using namespace clang; 31 32/// getLocationOfStringLiteralByte - Return a source location that points to the 33/// specified byte of the specified string literal. 34/// 35/// Strings are amazingly complex. They can be formed from multiple tokens and 36/// can have escape sequences in them in addition to the usual trigraph and 37/// escaped newline business. This routine handles this complexity. 38/// 39SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 40 unsigned ByteNo) const { 41 assert(!SL->isWide() && "This doesn't work for wide strings yet"); 42 43 // Loop over all of the tokens in this string until we find the one that 44 // contains the byte we're looking for. 45 unsigned TokNo = 0; 46 while (1) { 47 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!"); 48 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo); 49 50 // Get the spelling of the string so that we can get the data that makes up 51 // the string literal, not the identifier for the macro it is potentially 52 // expanded through. 53 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc); 54 55 // Re-lex the token to get its length and original spelling. 56 std::pair<FileID, unsigned> LocInfo = 57 SourceMgr.getDecomposedLoc(StrTokSpellingLoc); 58 bool Invalid = false; 59 llvm::StringRef Buffer = SourceMgr.getBufferData(LocInfo.first, &Invalid); 60 if (Invalid) 61 return StrTokSpellingLoc; 62 63 const char *StrData = Buffer.data()+LocInfo.second; 64 65 // Create a langops struct and enable trigraphs. This is sufficient for 66 // relexing tokens. 67 LangOptions LangOpts; 68 LangOpts.Trigraphs = true; 69 70 // Create a lexer starting at the beginning of this token. 71 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.begin(), StrData, 72 Buffer.end()); 73 Token TheTok; 74 TheLexer.LexFromRawLexer(TheTok); 75 76 // Use the StringLiteralParser to compute the length of the string in bytes. 77 StringLiteralParser SLP(&TheTok, 1, PP); 78 unsigned TokNumBytes = SLP.GetStringLength(); 79 80 // If the byte is in this token, return the location of the byte. 81 if (ByteNo < TokNumBytes || 82 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) { 83 unsigned Offset = 84 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP); 85 86 // Now that we know the offset of the token in the spelling, use the 87 // preprocessor to get the offset in the original source. 88 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset); 89 } 90 91 // Move to the next string token. 92 ++TokNo; 93 ByteNo -= TokNumBytes; 94 } 95} 96 97/// CheckablePrintfAttr - does a function call have a "printf" attribute 98/// and arguments that merit checking? 99bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) { 100 if (Format->getType() == "printf") return true; 101 if (Format->getType() == "printf0") { 102 // printf0 allows null "format" string; if so don't check format/args 103 unsigned format_idx = Format->getFormatIdx() - 1; 104 // Does the index refer to the implicit object argument? 105 if (isa<CXXMemberCallExpr>(TheCall)) { 106 if (format_idx == 0) 107 return false; 108 --format_idx; 109 } 110 if (format_idx < TheCall->getNumArgs()) { 111 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts(); 112 if (!Format->isNullPointerConstant(Context, 113 Expr::NPC_ValueDependentIsNull)) 114 return true; 115 } 116 } 117 return false; 118} 119 120Action::OwningExprResult 121Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 122 OwningExprResult TheCallResult(Owned(TheCall)); 123 124 switch (BuiltinID) { 125 case Builtin::BI__builtin___CFStringMakeConstantString: 126 assert(TheCall->getNumArgs() == 1 && 127 "Wrong # arguments to builtin CFStringMakeConstantString"); 128 if (CheckObjCString(TheCall->getArg(0))) 129 return ExprError(); 130 break; 131 case Builtin::BI__builtin_stdarg_start: 132 case Builtin::BI__builtin_va_start: 133 if (SemaBuiltinVAStart(TheCall)) 134 return ExprError(); 135 break; 136 case Builtin::BI__builtin_isgreater: 137 case Builtin::BI__builtin_isgreaterequal: 138 case Builtin::BI__builtin_isless: 139 case Builtin::BI__builtin_islessequal: 140 case Builtin::BI__builtin_islessgreater: 141 case Builtin::BI__builtin_isunordered: 142 if (SemaBuiltinUnorderedCompare(TheCall)) 143 return ExprError(); 144 break; 145 case Builtin::BI__builtin_fpclassify: 146 if (SemaBuiltinFPClassification(TheCall, 6)) 147 return ExprError(); 148 break; 149 case Builtin::BI__builtin_isfinite: 150 case Builtin::BI__builtin_isinf: 151 case Builtin::BI__builtin_isinf_sign: 152 case Builtin::BI__builtin_isnan: 153 case Builtin::BI__builtin_isnormal: 154 if (SemaBuiltinFPClassification(TheCall, 1)) 155 return ExprError(); 156 break; 157 case Builtin::BI__builtin_return_address: 158 case Builtin::BI__builtin_frame_address: 159 if (SemaBuiltinStackAddress(TheCall)) 160 return ExprError(); 161 break; 162 case Builtin::BI__builtin_eh_return_data_regno: 163 if (SemaBuiltinEHReturnDataRegNo(TheCall)) 164 return ExprError(); 165 break; 166 case Builtin::BI__builtin_shufflevector: 167 return SemaBuiltinShuffleVector(TheCall); 168 // TheCall will be freed by the smart pointer here, but that's fine, since 169 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 170 case Builtin::BI__builtin_prefetch: 171 if (SemaBuiltinPrefetch(TheCall)) 172 return ExprError(); 173 break; 174 case Builtin::BI__builtin_object_size: 175 if (SemaBuiltinObjectSize(TheCall)) 176 return ExprError(); 177 break; 178 case Builtin::BI__builtin_longjmp: 179 if (SemaBuiltinLongjmp(TheCall)) 180 return ExprError(); 181 break; 182 case Builtin::BI__sync_fetch_and_add: 183 case Builtin::BI__sync_fetch_and_sub: 184 case Builtin::BI__sync_fetch_and_or: 185 case Builtin::BI__sync_fetch_and_and: 186 case Builtin::BI__sync_fetch_and_xor: 187 case Builtin::BI__sync_add_and_fetch: 188 case Builtin::BI__sync_sub_and_fetch: 189 case Builtin::BI__sync_and_and_fetch: 190 case Builtin::BI__sync_or_and_fetch: 191 case Builtin::BI__sync_xor_and_fetch: 192 case Builtin::BI__sync_val_compare_and_swap: 193 case Builtin::BI__sync_bool_compare_and_swap: 194 case Builtin::BI__sync_lock_test_and_set: 195 case Builtin::BI__sync_lock_release: 196 if (SemaBuiltinAtomicOverloaded(TheCall)) 197 return ExprError(); 198 break; 199 } 200 201 return move(TheCallResult); 202} 203 204/// CheckFunctionCall - Check a direct function call for various correctness 205/// and safety properties not strictly enforced by the C type system. 206bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) { 207 // Get the IdentifierInfo* for the called function. 208 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 209 210 // None of the checks below are needed for functions that don't have 211 // simple names (e.g., C++ conversion functions). 212 if (!FnInfo) 213 return false; 214 215 // FIXME: This mechanism should be abstracted to be less fragile and 216 // more efficient. For example, just map function ids to custom 217 // handlers. 218 219 // Printf checking. 220 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) { 221 if (CheckablePrintfAttr(Format, TheCall)) { 222 bool HasVAListArg = Format->getFirstArg() == 0; 223 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1, 224 HasVAListArg ? 0 : Format->getFirstArg() - 1); 225 } 226 } 227 228 for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull; 229 NonNull = NonNull->getNext<NonNullAttr>()) 230 CheckNonNullArguments(NonNull, TheCall); 231 232 return false; 233} 234 235bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) { 236 // Printf checking. 237 const FormatAttr *Format = NDecl->getAttr<FormatAttr>(); 238 if (!Format) 239 return false; 240 241 const VarDecl *V = dyn_cast<VarDecl>(NDecl); 242 if (!V) 243 return false; 244 245 QualType Ty = V->getType(); 246 if (!Ty->isBlockPointerType()) 247 return false; 248 249 if (!CheckablePrintfAttr(Format, TheCall)) 250 return false; 251 252 bool HasVAListArg = Format->getFirstArg() == 0; 253 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1, 254 HasVAListArg ? 0 : Format->getFirstArg() - 1); 255 256 return false; 257} 258 259/// SemaBuiltinAtomicOverloaded - We have a call to a function like 260/// __sync_fetch_and_add, which is an overloaded function based on the pointer 261/// type of its first argument. The main ActOnCallExpr routines have already 262/// promoted the types of arguments because all of these calls are prototyped as 263/// void(...). 264/// 265/// This function goes through and does final semantic checking for these 266/// builtins, 267bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) { 268 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 269 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 270 271 // Ensure that we have at least one argument to do type inference from. 272 if (TheCall->getNumArgs() < 1) 273 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 274 << 0 << TheCall->getCallee()->getSourceRange(); 275 276 // Inspect the first argument of the atomic builtin. This should always be 277 // a pointer type, whose element is an integral scalar or pointer type. 278 // Because it is a pointer type, we don't have to worry about any implicit 279 // casts here. 280 Expr *FirstArg = TheCall->getArg(0); 281 if (!FirstArg->getType()->isPointerType()) 282 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 283 << FirstArg->getType() << FirstArg->getSourceRange(); 284 285 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType(); 286 if (!ValType->isIntegerType() && !ValType->isPointerType() && 287 !ValType->isBlockPointerType()) 288 return Diag(DRE->getLocStart(), 289 diag::err_atomic_builtin_must_be_pointer_intptr) 290 << FirstArg->getType() << FirstArg->getSourceRange(); 291 292 // We need to figure out which concrete builtin this maps onto. For example, 293 // __sync_fetch_and_add with a 2 byte object turns into 294 // __sync_fetch_and_add_2. 295#define BUILTIN_ROW(x) \ 296 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 297 Builtin::BI##x##_8, Builtin::BI##x##_16 } 298 299 static const unsigned BuiltinIndices[][5] = { 300 BUILTIN_ROW(__sync_fetch_and_add), 301 BUILTIN_ROW(__sync_fetch_and_sub), 302 BUILTIN_ROW(__sync_fetch_and_or), 303 BUILTIN_ROW(__sync_fetch_and_and), 304 BUILTIN_ROW(__sync_fetch_and_xor), 305 306 BUILTIN_ROW(__sync_add_and_fetch), 307 BUILTIN_ROW(__sync_sub_and_fetch), 308 BUILTIN_ROW(__sync_and_and_fetch), 309 BUILTIN_ROW(__sync_or_and_fetch), 310 BUILTIN_ROW(__sync_xor_and_fetch), 311 312 BUILTIN_ROW(__sync_val_compare_and_swap), 313 BUILTIN_ROW(__sync_bool_compare_and_swap), 314 BUILTIN_ROW(__sync_lock_test_and_set), 315 BUILTIN_ROW(__sync_lock_release) 316 }; 317#undef BUILTIN_ROW 318 319 // Determine the index of the size. 320 unsigned SizeIndex; 321 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 322 case 1: SizeIndex = 0; break; 323 case 2: SizeIndex = 1; break; 324 case 4: SizeIndex = 2; break; 325 case 8: SizeIndex = 3; break; 326 case 16: SizeIndex = 4; break; 327 default: 328 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 329 << FirstArg->getType() << FirstArg->getSourceRange(); 330 } 331 332 // Each of these builtins has one pointer argument, followed by some number of 333 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 334 // that we ignore. Find out which row of BuiltinIndices to read from as well 335 // as the number of fixed args. 336 unsigned BuiltinID = FDecl->getBuiltinID(); 337 unsigned BuiltinIndex, NumFixed = 1; 338 switch (BuiltinID) { 339 default: assert(0 && "Unknown overloaded atomic builtin!"); 340 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break; 341 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break; 342 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break; 343 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break; 344 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break; 345 346 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break; 347 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break; 348 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break; 349 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break; 350 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break; 351 352 case Builtin::BI__sync_val_compare_and_swap: 353 BuiltinIndex = 10; 354 NumFixed = 2; 355 break; 356 case Builtin::BI__sync_bool_compare_and_swap: 357 BuiltinIndex = 11; 358 NumFixed = 2; 359 break; 360 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break; 361 case Builtin::BI__sync_lock_release: 362 BuiltinIndex = 13; 363 NumFixed = 0; 364 break; 365 } 366 367 // Now that we know how many fixed arguments we expect, first check that we 368 // have at least that many. 369 if (TheCall->getNumArgs() < 1+NumFixed) 370 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 371 << 0 << TheCall->getCallee()->getSourceRange(); 372 373 374 // Get the decl for the concrete builtin from this, we can tell what the 375 // concrete integer type we should convert to is. 376 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 377 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID); 378 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName); 379 FunctionDecl *NewBuiltinDecl = 380 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID, 381 TUScope, false, DRE->getLocStart())); 382 const FunctionProtoType *BuiltinFT = 383 NewBuiltinDecl->getType()->getAs<FunctionProtoType>(); 384 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType(); 385 386 // If the first type needs to be converted (e.g. void** -> int*), do it now. 387 if (BuiltinFT->getArgType(0) != FirstArg->getType()) { 388 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_BitCast); 389 TheCall->setArg(0, FirstArg); 390 } 391 392 // Next, walk the valid ones promoting to the right type. 393 for (unsigned i = 0; i != NumFixed; ++i) { 394 Expr *Arg = TheCall->getArg(i+1); 395 396 // If the argument is an implicit cast, then there was a promotion due to 397 // "...", just remove it now. 398 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) { 399 Arg = ICE->getSubExpr(); 400 ICE->setSubExpr(0); 401 ICE->Destroy(Context); 402 TheCall->setArg(i+1, Arg); 403 } 404 405 // GCC does an implicit conversion to the pointer or integer ValType. This 406 // can fail in some cases (1i -> int**), check for this error case now. 407 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 408 CXXMethodDecl *ConversionDecl = 0; 409 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, 410 ConversionDecl)) 411 return true; 412 413 // Okay, we have something that *can* be converted to the right type. Check 414 // to see if there is a potentially weird extension going on here. This can 415 // happen when you do an atomic operation on something like an char* and 416 // pass in 42. The 42 gets converted to char. This is even more strange 417 // for things like 45.123 -> char, etc. 418 // FIXME: Do this check. 419 ImpCastExprToType(Arg, ValType, Kind, /*isLvalue=*/false); 420 TheCall->setArg(i+1, Arg); 421 } 422 423 // Switch the DeclRefExpr to refer to the new decl. 424 DRE->setDecl(NewBuiltinDecl); 425 DRE->setType(NewBuiltinDecl->getType()); 426 427 // Set the callee in the CallExpr. 428 // FIXME: This leaks the original parens and implicit casts. 429 Expr *PromotedCall = DRE; 430 UsualUnaryConversions(PromotedCall); 431 TheCall->setCallee(PromotedCall); 432 433 434 // Change the result type of the call to match the result type of the decl. 435 TheCall->setType(NewBuiltinDecl->getResultType()); 436 return false; 437} 438 439 440/// CheckObjCString - Checks that the argument to the builtin 441/// CFString constructor is correct 442/// FIXME: GCC currently emits the following warning: 443/// "warning: input conversion stopped due to an input byte that does not 444/// belong to the input codeset UTF-8" 445/// Note: It might also make sense to do the UTF-16 conversion here (would 446/// simplify the backend). 447bool Sema::CheckObjCString(Expr *Arg) { 448 Arg = Arg->IgnoreParenCasts(); 449 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 450 451 if (!Literal || Literal->isWide()) { 452 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 453 << Arg->getSourceRange(); 454 return true; 455 } 456 457 const char *Data = Literal->getStrData(); 458 unsigned Length = Literal->getByteLength(); 459 460 for (unsigned i = 0; i < Length; ++i) { 461 if (!Data[i]) { 462 Diag(getLocationOfStringLiteralByte(Literal, i), 463 diag::warn_cfstring_literal_contains_nul_character) 464 << Arg->getSourceRange(); 465 break; 466 } 467 } 468 469 return false; 470} 471 472/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 473/// Emit an error and return true on failure, return false on success. 474bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 475 Expr *Fn = TheCall->getCallee(); 476 if (TheCall->getNumArgs() > 2) { 477 Diag(TheCall->getArg(2)->getLocStart(), 478 diag::err_typecheck_call_too_many_args) 479 << 0 /*function call*/ << Fn->getSourceRange() 480 << SourceRange(TheCall->getArg(2)->getLocStart(), 481 (*(TheCall->arg_end()-1))->getLocEnd()); 482 return true; 483 } 484 485 if (TheCall->getNumArgs() < 2) { 486 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 487 << 0 /*function call*/; 488 } 489 490 // Determine whether the current function is variadic or not. 491 BlockScopeInfo *CurBlock = getCurBlock(); 492 bool isVariadic; 493 if (CurBlock) 494 isVariadic = CurBlock->isVariadic; 495 else if (getCurFunctionDecl()) { 496 if (FunctionProtoType* FTP = 497 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType())) 498 isVariadic = FTP->isVariadic(); 499 else 500 isVariadic = false; 501 } else { 502 isVariadic = getCurMethodDecl()->isVariadic(); 503 } 504 505 if (!isVariadic) { 506 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 507 return true; 508 } 509 510 // Verify that the second argument to the builtin is the last argument of the 511 // current function or method. 512 bool SecondArgIsLastNamedArgument = false; 513 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 514 515 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 516 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 517 // FIXME: This isn't correct for methods (results in bogus warning). 518 // Get the last formal in the current function. 519 const ParmVarDecl *LastArg; 520 if (CurBlock) 521 LastArg = *(CurBlock->TheDecl->param_end()-1); 522 else if (FunctionDecl *FD = getCurFunctionDecl()) 523 LastArg = *(FD->param_end()-1); 524 else 525 LastArg = *(getCurMethodDecl()->param_end()-1); 526 SecondArgIsLastNamedArgument = PV == LastArg; 527 } 528 } 529 530 if (!SecondArgIsLastNamedArgument) 531 Diag(TheCall->getArg(1)->getLocStart(), 532 diag::warn_second_parameter_of_va_start_not_last_named_argument); 533 return false; 534} 535 536/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 537/// friends. This is declared to take (...), so we have to check everything. 538bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 539 if (TheCall->getNumArgs() < 2) 540 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 541 << 0 /*function call*/; 542 if (TheCall->getNumArgs() > 2) 543 return Diag(TheCall->getArg(2)->getLocStart(), 544 diag::err_typecheck_call_too_many_args) 545 << 0 /*function call*/ 546 << SourceRange(TheCall->getArg(2)->getLocStart(), 547 (*(TheCall->arg_end()-1))->getLocEnd()); 548 549 Expr *OrigArg0 = TheCall->getArg(0); 550 Expr *OrigArg1 = TheCall->getArg(1); 551 552 // Do standard promotions between the two arguments, returning their common 553 // type. 554 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 555 556 // Make sure any conversions are pushed back into the call; this is 557 // type safe since unordered compare builtins are declared as "_Bool 558 // foo(...)". 559 TheCall->setArg(0, OrigArg0); 560 TheCall->setArg(1, OrigArg1); 561 562 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent()) 563 return false; 564 565 // If the common type isn't a real floating type, then the arguments were 566 // invalid for this operation. 567 if (!Res->isRealFloatingType()) 568 return Diag(OrigArg0->getLocStart(), 569 diag::err_typecheck_call_invalid_ordered_compare) 570 << OrigArg0->getType() << OrigArg1->getType() 571 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd()); 572 573 return false; 574} 575 576/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 577/// __builtin_isnan and friends. This is declared to take (...), so we have 578/// to check everything. We expect the last argument to be a floating point 579/// value. 580bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 581 if (TheCall->getNumArgs() < NumArgs) 582 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 583 << 0 /*function call*/; 584 if (TheCall->getNumArgs() > NumArgs) 585 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 586 diag::err_typecheck_call_too_many_args) 587 << 0 /*function call*/ 588 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 589 (*(TheCall->arg_end()-1))->getLocEnd()); 590 591 Expr *OrigArg = TheCall->getArg(NumArgs-1); 592 593 if (OrigArg->isTypeDependent()) 594 return false; 595 596 // This operation requires a floating-point number 597 if (!OrigArg->getType()->isRealFloatingType()) 598 return Diag(OrigArg->getLocStart(), 599 diag::err_typecheck_call_invalid_unary_fp) 600 << OrigArg->getType() << OrigArg->getSourceRange(); 601 602 return false; 603} 604 605bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) { 606 // The signature for these builtins is exact; the only thing we need 607 // to check is that the argument is a constant. 608 SourceLocation Loc; 609 if (!TheCall->getArg(0)->isTypeDependent() && 610 !TheCall->getArg(0)->isValueDependent() && 611 !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc)) 612 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange(); 613 614 return false; 615} 616 617/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 618// This is declared to take (...), so we have to check everything. 619Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 620 if (TheCall->getNumArgs() < 3) 621 return ExprError(Diag(TheCall->getLocEnd(), 622 diag::err_typecheck_call_too_few_args) 623 << 0 /*function call*/ << TheCall->getSourceRange()); 624 625 unsigned numElements = std::numeric_limits<unsigned>::max(); 626 if (!TheCall->getArg(0)->isTypeDependent() && 627 !TheCall->getArg(1)->isTypeDependent()) { 628 QualType FAType = TheCall->getArg(0)->getType(); 629 QualType SAType = TheCall->getArg(1)->getType(); 630 631 if (!FAType->isVectorType() || !SAType->isVectorType()) { 632 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector) 633 << SourceRange(TheCall->getArg(0)->getLocStart(), 634 TheCall->getArg(1)->getLocEnd()); 635 return ExprError(); 636 } 637 638 if (!Context.hasSameUnqualifiedType(FAType, SAType)) { 639 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 640 << SourceRange(TheCall->getArg(0)->getLocStart(), 641 TheCall->getArg(1)->getLocEnd()); 642 return ExprError(); 643 } 644 645 numElements = FAType->getAs<VectorType>()->getNumElements(); 646 if (TheCall->getNumArgs() != numElements+2) { 647 if (TheCall->getNumArgs() < numElements+2) 648 return ExprError(Diag(TheCall->getLocEnd(), 649 diag::err_typecheck_call_too_few_args) 650 << 0 /*function call*/ << TheCall->getSourceRange()); 651 return ExprError(Diag(TheCall->getLocEnd(), 652 diag::err_typecheck_call_too_many_args) 653 << 0 /*function call*/ << TheCall->getSourceRange()); 654 } 655 } 656 657 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 658 if (TheCall->getArg(i)->isTypeDependent() || 659 TheCall->getArg(i)->isValueDependent()) 660 continue; 661 662 llvm::APSInt Result(32); 663 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 664 return ExprError(Diag(TheCall->getLocStart(), 665 diag::err_shufflevector_nonconstant_argument) 666 << TheCall->getArg(i)->getSourceRange()); 667 668 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 669 return ExprError(Diag(TheCall->getLocStart(), 670 diag::err_shufflevector_argument_too_large) 671 << TheCall->getArg(i)->getSourceRange()); 672 } 673 674 llvm::SmallVector<Expr*, 32> exprs; 675 676 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 677 exprs.push_back(TheCall->getArg(i)); 678 TheCall->setArg(i, 0); 679 } 680 681 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(), 682 exprs.size(), exprs[0]->getType(), 683 TheCall->getCallee()->getLocStart(), 684 TheCall->getRParenLoc())); 685} 686 687/// SemaBuiltinPrefetch - Handle __builtin_prefetch. 688// This is declared to take (const void*, ...) and can take two 689// optional constant int args. 690bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 691 unsigned NumArgs = TheCall->getNumArgs(); 692 693 if (NumArgs > 3) 694 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args) 695 << 0 /*function call*/ << TheCall->getSourceRange(); 696 697 // Argument 0 is checked for us and the remaining arguments must be 698 // constant integers. 699 for (unsigned i = 1; i != NumArgs; ++i) { 700 Expr *Arg = TheCall->getArg(i); 701 if (Arg->isTypeDependent()) 702 continue; 703 704 if (!Arg->getType()->isIntegralType()) 705 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_type) 706 << Arg->getSourceRange(); 707 708 ImpCastExprToType(Arg, Context.IntTy, CastExpr::CK_IntegralCast); 709 TheCall->setArg(i, Arg); 710 711 if (Arg->isValueDependent()) 712 continue; 713 714 llvm::APSInt Result; 715 if (!Arg->isIntegerConstantExpr(Result, Context)) 716 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_ice) 717 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 718 719 // FIXME: gcc issues a warning and rewrites these to 0. These 720 // seems especially odd for the third argument since the default 721 // is 3. 722 if (i == 1) { 723 if (Result.getLimitedValue() > 1) 724 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 725 << "0" << "1" << Arg->getSourceRange(); 726 } else { 727 if (Result.getLimitedValue() > 3) 728 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 729 << "0" << "3" << Arg->getSourceRange(); 730 } 731 } 732 733 return false; 734} 735 736/// SemaBuiltinEHReturnDataRegNo - Handle __builtin_eh_return_data_regno, the 737/// operand must be an integer constant. 738bool Sema::SemaBuiltinEHReturnDataRegNo(CallExpr *TheCall) { 739 llvm::APSInt Result; 740 if (!TheCall->getArg(0)->isIntegerConstantExpr(Result, Context)) 741 return Diag(TheCall->getLocStart(), diag::err_expr_not_ice) 742 << TheCall->getArg(0)->getSourceRange(); 743 744 return false; 745} 746 747 748/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, 749/// int type). This simply type checks that type is one of the defined 750/// constants (0-3). 751// For compatability check 0-3, llvm only handles 0 and 2. 752bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { 753 Expr *Arg = TheCall->getArg(1); 754 if (Arg->isTypeDependent()) 755 return false; 756 757 QualType ArgType = Arg->getType(); 758 const BuiltinType *BT = ArgType->getAs<BuiltinType>(); 759 llvm::APSInt Result(32); 760 if (!BT || BT->getKind() != BuiltinType::Int) 761 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument) 762 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 763 764 if (Arg->isValueDependent()) 765 return false; 766 767 if (!Arg->isIntegerConstantExpr(Result, Context)) { 768 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument) 769 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 770 } 771 772 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { 773 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 774 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 775 } 776 777 return false; 778} 779 780/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 781/// This checks that val is a constant 1. 782bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 783 Expr *Arg = TheCall->getArg(1); 784 if (Arg->isTypeDependent() || Arg->isValueDependent()) 785 return false; 786 787 llvm::APSInt Result(32); 788 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1) 789 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 790 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 791 792 return false; 793} 794 795// Handle i > 1 ? "x" : "y", recursivelly 796bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall, 797 bool HasVAListArg, 798 unsigned format_idx, unsigned firstDataArg) { 799 if (E->isTypeDependent() || E->isValueDependent()) 800 return false; 801 802 switch (E->getStmtClass()) { 803 case Stmt::ConditionalOperatorClass: { 804 const ConditionalOperator *C = cast<ConditionalOperator>(E); 805 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, 806 HasVAListArg, format_idx, firstDataArg) 807 && SemaCheckStringLiteral(C->getRHS(), TheCall, 808 HasVAListArg, format_idx, firstDataArg); 809 } 810 811 case Stmt::ImplicitCastExprClass: { 812 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E); 813 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg, 814 format_idx, firstDataArg); 815 } 816 817 case Stmt::ParenExprClass: { 818 const ParenExpr *Expr = cast<ParenExpr>(E); 819 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg, 820 format_idx, firstDataArg); 821 } 822 823 case Stmt::DeclRefExprClass: { 824 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 825 826 // As an exception, do not flag errors for variables binding to 827 // const string literals. 828 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 829 bool isConstant = false; 830 QualType T = DR->getType(); 831 832 if (const ArrayType *AT = Context.getAsArrayType(T)) { 833 isConstant = AT->getElementType().isConstant(Context); 834 } else if (const PointerType *PT = T->getAs<PointerType>()) { 835 isConstant = T.isConstant(Context) && 836 PT->getPointeeType().isConstant(Context); 837 } 838 839 if (isConstant) { 840 if (const Expr *Init = VD->getAnyInitializer()) 841 return SemaCheckStringLiteral(Init, TheCall, 842 HasVAListArg, format_idx, firstDataArg); 843 } 844 845 // For vprintf* functions (i.e., HasVAListArg==true), we add a 846 // special check to see if the format string is a function parameter 847 // of the function calling the printf function. If the function 848 // has an attribute indicating it is a printf-like function, then we 849 // should suppress warnings concerning non-literals being used in a call 850 // to a vprintf function. For example: 851 // 852 // void 853 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 854 // va_list ap; 855 // va_start(ap, fmt); 856 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 857 // ... 858 // 859 // 860 // FIXME: We don't have full attribute support yet, so just check to see 861 // if the argument is a DeclRefExpr that references a parameter. We'll 862 // add proper support for checking the attribute later. 863 if (HasVAListArg) 864 if (isa<ParmVarDecl>(VD)) 865 return true; 866 } 867 868 return false; 869 } 870 871 case Stmt::CallExprClass: { 872 const CallExpr *CE = cast<CallExpr>(E); 873 if (const ImplicitCastExpr *ICE 874 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) { 875 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) { 876 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 877 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) { 878 unsigned ArgIndex = FA->getFormatIdx(); 879 const Expr *Arg = CE->getArg(ArgIndex - 1); 880 881 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg, 882 format_idx, firstDataArg); 883 } 884 } 885 } 886 } 887 888 return false; 889 } 890 case Stmt::ObjCStringLiteralClass: 891 case Stmt::StringLiteralClass: { 892 const StringLiteral *StrE = NULL; 893 894 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 895 StrE = ObjCFExpr->getString(); 896 else 897 StrE = cast<StringLiteral>(E); 898 899 if (StrE) { 900 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx, 901 firstDataArg); 902 return true; 903 } 904 905 return false; 906 } 907 908 default: 909 return false; 910 } 911} 912 913void 914Sema::CheckNonNullArguments(const NonNullAttr *NonNull, 915 const CallExpr *TheCall) { 916 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end(); 917 i != e; ++i) { 918 const Expr *ArgExpr = TheCall->getArg(*i); 919 if (ArgExpr->isNullPointerConstant(Context, 920 Expr::NPC_ValueDependentIsNotNull)) 921 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg) 922 << ArgExpr->getSourceRange(); 923 } 924} 925 926/// CheckPrintfArguments - Check calls to printf (and similar functions) for 927/// correct use of format strings. 928/// 929/// HasVAListArg - A predicate indicating whether the printf-like 930/// function is passed an explicit va_arg argument (e.g., vprintf) 931/// 932/// format_idx - The index into Args for the format string. 933/// 934/// Improper format strings to functions in the printf family can be 935/// the source of bizarre bugs and very serious security holes. A 936/// good source of information is available in the following paper 937/// (which includes additional references): 938/// 939/// FormatGuard: Automatic Protection From printf Format String 940/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001. 941/// 942/// TODO: 943/// Functionality implemented: 944/// 945/// We can statically check the following properties for string 946/// literal format strings for non v.*printf functions (where the 947/// arguments are passed directly): 948// 949/// (1) Are the number of format conversions equal to the number of 950/// data arguments? 951/// 952/// (2) Does each format conversion correctly match the type of the 953/// corresponding data argument? 954/// 955/// Moreover, for all printf functions we can: 956/// 957/// (3) Check for a missing format string (when not caught by type checking). 958/// 959/// (4) Check for no-operation flags; e.g. using "#" with format 960/// conversion 'c' (TODO) 961/// 962/// (5) Check the use of '%n', a major source of security holes. 963/// 964/// (6) Check for malformed format conversions that don't specify anything. 965/// 966/// (7) Check for empty format strings. e.g: printf(""); 967/// 968/// (8) Check that the format string is a wide literal. 969/// 970/// All of these checks can be done by parsing the format string. 971/// 972void 973Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg, 974 unsigned format_idx, unsigned firstDataArg) { 975 const Expr *Fn = TheCall->getCallee(); 976 977 // The way the format attribute works in GCC, the implicit this argument 978 // of member functions is counted. However, it doesn't appear in our own 979 // lists, so decrement format_idx in that case. 980 if (isa<CXXMemberCallExpr>(TheCall)) { 981 // Catch a format attribute mistakenly referring to the object argument. 982 if (format_idx == 0) 983 return; 984 --format_idx; 985 if(firstDataArg != 0) 986 --firstDataArg; 987 } 988 989 // CHECK: printf-like function is called with no format string. 990 if (format_idx >= TheCall->getNumArgs()) { 991 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string) 992 << Fn->getSourceRange(); 993 return; 994 } 995 996 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts(); 997 998 // CHECK: format string is not a string literal. 999 // 1000 // Dynamically generated format strings are difficult to 1001 // automatically vet at compile time. Requiring that format strings 1002 // are string literals: (1) permits the checking of format strings by 1003 // the compiler and thereby (2) can practically remove the source of 1004 // many format string exploits. 1005 1006 // Format string can be either ObjC string (e.g. @"%d") or 1007 // C string (e.g. "%d") 1008 // ObjC string uses the same format specifiers as C string, so we can use 1009 // the same format string checking logic for both ObjC and C strings. 1010 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx, 1011 firstDataArg)) 1012 return; // Literal format string found, check done! 1013 1014 // If there are no arguments specified, warn with -Wformat-security, otherwise 1015 // warn only with -Wformat-nonliteral. 1016 if (TheCall->getNumArgs() == format_idx+1) 1017 Diag(TheCall->getArg(format_idx)->getLocStart(), 1018 diag::warn_printf_nonliteral_noargs) 1019 << OrigFormatExpr->getSourceRange(); 1020 else 1021 Diag(TheCall->getArg(format_idx)->getLocStart(), 1022 diag::warn_printf_nonliteral) 1023 << OrigFormatExpr->getSourceRange(); 1024} 1025 1026namespace { 1027class CheckPrintfHandler : public analyze_printf::FormatStringHandler { 1028 Sema &S; 1029 const StringLiteral *FExpr; 1030 const Expr *OrigFormatExpr; 1031 const unsigned FirstDataArg; 1032 const unsigned NumDataArgs; 1033 const bool IsObjCLiteral; 1034 const char *Beg; // Start of format string. 1035 const bool HasVAListArg; 1036 const CallExpr *TheCall; 1037 unsigned FormatIdx; 1038 llvm::BitVector CoveredArgs; 1039 bool usesPositionalArgs; 1040 bool atFirstArg; 1041public: 1042 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 1043 const Expr *origFormatExpr, unsigned firstDataArg, 1044 unsigned numDataArgs, bool isObjCLiteral, 1045 const char *beg, bool hasVAListArg, 1046 const CallExpr *theCall, unsigned formatIdx) 1047 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 1048 FirstDataArg(firstDataArg), 1049 NumDataArgs(numDataArgs), 1050 IsObjCLiteral(isObjCLiteral), Beg(beg), 1051 HasVAListArg(hasVAListArg), 1052 TheCall(theCall), FormatIdx(formatIdx), 1053 usesPositionalArgs(false), atFirstArg(true) { 1054 CoveredArgs.resize(numDataArgs); 1055 CoveredArgs.reset(); 1056 } 1057 1058 void DoneProcessing(); 1059 1060 void HandleIncompleteFormatSpecifier(const char *startSpecifier, 1061 unsigned specifierLen); 1062 1063 bool 1064 HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS, 1065 const char *startSpecifier, 1066 unsigned specifierLen); 1067 1068 virtual void HandleInvalidPosition(const char *startSpecifier, 1069 unsigned specifierLen, 1070 analyze_printf::PositionContext p); 1071 1072 virtual void HandleZeroPosition(const char *startPos, unsigned posLen); 1073 1074 void HandleNullChar(const char *nullCharacter); 1075 1076 bool HandleFormatSpecifier(const analyze_printf::FormatSpecifier &FS, 1077 const char *startSpecifier, 1078 unsigned specifierLen); 1079private: 1080 SourceRange getFormatStringRange(); 1081 SourceRange getFormatSpecifierRange(const char *startSpecifier, 1082 unsigned specifierLen); 1083 SourceLocation getLocationOfByte(const char *x); 1084 1085 bool HandleAmount(const analyze_printf::OptionalAmount &Amt, unsigned k, 1086 const char *startSpecifier, unsigned specifierLen); 1087 void HandleFlags(const analyze_printf::FormatSpecifier &FS, 1088 llvm::StringRef flag, llvm::StringRef cspec, 1089 const char *startSpecifier, unsigned specifierLen); 1090 1091 const Expr *getDataArg(unsigned i) const; 1092}; 1093} 1094 1095SourceRange CheckPrintfHandler::getFormatStringRange() { 1096 return OrigFormatExpr->getSourceRange(); 1097} 1098 1099SourceRange CheckPrintfHandler:: 1100getFormatSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 1101 return SourceRange(getLocationOfByte(startSpecifier), 1102 getLocationOfByte(startSpecifier+specifierLen-1)); 1103} 1104 1105SourceLocation CheckPrintfHandler::getLocationOfByte(const char *x) { 1106 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 1107} 1108 1109void CheckPrintfHandler:: 1110HandleIncompleteFormatSpecifier(const char *startSpecifier, 1111 unsigned specifierLen) { 1112 SourceLocation Loc = getLocationOfByte(startSpecifier); 1113 S.Diag(Loc, diag::warn_printf_incomplete_specifier) 1114 << getFormatSpecifierRange(startSpecifier, specifierLen); 1115} 1116 1117void 1118CheckPrintfHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 1119 analyze_printf::PositionContext p) { 1120 SourceLocation Loc = getLocationOfByte(startPos); 1121 S.Diag(Loc, diag::warn_printf_invalid_positional_specifier) 1122 << (unsigned) p << getFormatSpecifierRange(startPos, posLen); 1123} 1124 1125void CheckPrintfHandler::HandleZeroPosition(const char *startPos, 1126 unsigned posLen) { 1127 SourceLocation Loc = getLocationOfByte(startPos); 1128 S.Diag(Loc, diag::warn_printf_zero_positional_specifier) 1129 << getFormatSpecifierRange(startPos, posLen); 1130} 1131 1132bool CheckPrintfHandler:: 1133HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS, 1134 const char *startSpecifier, 1135 unsigned specifierLen) { 1136 1137 unsigned argIndex = FS.getArgIndex(); 1138 bool keepGoing = true; 1139 if (argIndex < NumDataArgs) { 1140 // Consider the argument coverered, even though the specifier doesn't 1141 // make sense. 1142 CoveredArgs.set(argIndex); 1143 } 1144 else { 1145 // If argIndex exceeds the number of data arguments we 1146 // don't issue a warning because that is just a cascade of warnings (and 1147 // they may have intended '%%' anyway). We don't want to continue processing 1148 // the format string after this point, however, as we will like just get 1149 // gibberish when trying to match arguments. 1150 keepGoing = false; 1151 } 1152 1153 const analyze_printf::ConversionSpecifier &CS = 1154 FS.getConversionSpecifier(); 1155 SourceLocation Loc = getLocationOfByte(CS.getStart()); 1156 S.Diag(Loc, diag::warn_printf_invalid_conversion) 1157 << llvm::StringRef(CS.getStart(), CS.getLength()) 1158 << getFormatSpecifierRange(startSpecifier, specifierLen); 1159 1160 return keepGoing; 1161} 1162 1163void CheckPrintfHandler::HandleNullChar(const char *nullCharacter) { 1164 // The presence of a null character is likely an error. 1165 S.Diag(getLocationOfByte(nullCharacter), 1166 diag::warn_printf_format_string_contains_null_char) 1167 << getFormatStringRange(); 1168} 1169 1170const Expr *CheckPrintfHandler::getDataArg(unsigned i) const { 1171 return TheCall->getArg(FirstDataArg + i); 1172} 1173 1174void CheckPrintfHandler::HandleFlags(const analyze_printf::FormatSpecifier &FS, 1175 llvm::StringRef flag, 1176 llvm::StringRef cspec, 1177 const char *startSpecifier, 1178 unsigned specifierLen) { 1179 const analyze_printf::ConversionSpecifier &CS = FS.getConversionSpecifier(); 1180 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_nonsensical_flag) 1181 << flag << cspec << getFormatSpecifierRange(startSpecifier, specifierLen); 1182} 1183 1184bool 1185CheckPrintfHandler::HandleAmount(const analyze_printf::OptionalAmount &Amt, 1186 unsigned k, const char *startSpecifier, 1187 unsigned specifierLen) { 1188 1189 if (Amt.hasDataArgument()) { 1190 if (!HasVAListArg) { 1191 unsigned argIndex = Amt.getArgIndex(); 1192 if (argIndex >= NumDataArgs) { 1193 S.Diag(getLocationOfByte(Amt.getStart()), 1194 diag::warn_printf_asterisk_missing_arg) 1195 << k << getFormatSpecifierRange(startSpecifier, specifierLen); 1196 // Don't do any more checking. We will just emit 1197 // spurious errors. 1198 return false; 1199 } 1200 1201 // Type check the data argument. It should be an 'int'. 1202 // Although not in conformance with C99, we also allow the argument to be 1203 // an 'unsigned int' as that is a reasonably safe case. GCC also 1204 // doesn't emit a warning for that case. 1205 CoveredArgs.set(argIndex); 1206 const Expr *Arg = getDataArg(argIndex); 1207 QualType T = Arg->getType(); 1208 1209 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context); 1210 assert(ATR.isValid()); 1211 1212 if (!ATR.matchesType(S.Context, T)) { 1213 S.Diag(getLocationOfByte(Amt.getStart()), 1214 diag::warn_printf_asterisk_wrong_type) 1215 << k 1216 << ATR.getRepresentativeType(S.Context) << T 1217 << getFormatSpecifierRange(startSpecifier, specifierLen) 1218 << Arg->getSourceRange(); 1219 // Don't do any more checking. We will just emit 1220 // spurious errors. 1221 return false; 1222 } 1223 } 1224 } 1225 return true; 1226} 1227 1228bool 1229CheckPrintfHandler::HandleFormatSpecifier(const analyze_printf::FormatSpecifier 1230 &FS, 1231 const char *startSpecifier, 1232 unsigned specifierLen) { 1233 1234 using namespace analyze_printf; 1235 const ConversionSpecifier &CS = FS.getConversionSpecifier(); 1236 1237 if (atFirstArg) { 1238 atFirstArg = false; 1239 usesPositionalArgs = FS.usesPositionalArg(); 1240 } 1241 else if (usesPositionalArgs != FS.usesPositionalArg()) { 1242 // Cannot mix-and-match positional and non-positional arguments. 1243 S.Diag(getLocationOfByte(CS.getStart()), 1244 diag::warn_printf_mix_positional_nonpositional_args) 1245 << getFormatSpecifierRange(startSpecifier, specifierLen); 1246 return false; 1247 } 1248 1249 // First check if the field width, precision, and conversion specifier 1250 // have matching data arguments. 1251 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 1252 startSpecifier, specifierLen)) { 1253 return false; 1254 } 1255 1256 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 1257 startSpecifier, specifierLen)) { 1258 return false; 1259 } 1260 1261 if (!CS.consumesDataArgument()) { 1262 // FIXME: Technically specifying a precision or field width here 1263 // makes no sense. Worth issuing a warning at some point. 1264 return true; 1265 } 1266 1267 // Consume the argument. 1268 unsigned argIndex = FS.getArgIndex(); 1269 if (argIndex < NumDataArgs) { 1270 // The check to see if the argIndex is valid will come later. 1271 // We set the bit here because we may exit early from this 1272 // function if we encounter some other error. 1273 CoveredArgs.set(argIndex); 1274 } 1275 1276 // Check for using an Objective-C specific conversion specifier 1277 // in a non-ObjC literal. 1278 if (!IsObjCLiteral && CS.isObjCArg()) { 1279 return HandleInvalidConversionSpecifier(FS, startSpecifier, specifierLen); 1280 } 1281 1282 // Are we using '%n'? Issue a warning about this being 1283 // a possible security issue. 1284 if (CS.getKind() == ConversionSpecifier::OutIntPtrArg) { 1285 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back) 1286 << getFormatSpecifierRange(startSpecifier, specifierLen); 1287 // Continue checking the other format specifiers. 1288 return true; 1289 } 1290 1291 if (CS.getKind() == ConversionSpecifier::VoidPtrArg) { 1292 if (FS.getPrecision().getHowSpecified() != OptionalAmount::NotSpecified) 1293 S.Diag(getLocationOfByte(CS.getStart()), 1294 diag::warn_printf_nonsensical_precision) 1295 << CS.getCharacters() 1296 << getFormatSpecifierRange(startSpecifier, specifierLen); 1297 } 1298 if (CS.getKind() == ConversionSpecifier::VoidPtrArg || 1299 CS.getKind() == ConversionSpecifier::CStrArg) { 1300 // FIXME: Instead of using "0", "+", etc., eventually get them from 1301 // the FormatSpecifier. 1302 if (FS.hasLeadingZeros()) 1303 HandleFlags(FS, "0", CS.getCharacters(), startSpecifier, specifierLen); 1304 if (FS.hasPlusPrefix()) 1305 HandleFlags(FS, "+", CS.getCharacters(), startSpecifier, specifierLen); 1306 if (FS.hasSpacePrefix()) 1307 HandleFlags(FS, " ", CS.getCharacters(), startSpecifier, specifierLen); 1308 } 1309 1310 // The remaining checks depend on the data arguments. 1311 if (HasVAListArg) 1312 return true; 1313 1314 if (argIndex >= NumDataArgs) { 1315 if (FS.usesPositionalArg()) { 1316 S.Diag(getLocationOfByte(CS.getStart()), 1317 diag::warn_printf_positional_arg_exceeds_data_args) 1318 << (argIndex+1) << NumDataArgs 1319 << getFormatSpecifierRange(startSpecifier, specifierLen); 1320 } 1321 else { 1322 S.Diag(getLocationOfByte(CS.getStart()), 1323 diag::warn_printf_insufficient_data_args) 1324 << getFormatSpecifierRange(startSpecifier, specifierLen); 1325 } 1326 1327 // Don't do any more checking. 1328 return false; 1329 } 1330 1331 // Now type check the data expression that matches the 1332 // format specifier. 1333 const Expr *Ex = getDataArg(argIndex); 1334 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context); 1335 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) { 1336 // Check if we didn't match because of an implicit cast from a 'char' 1337 // or 'short' to an 'int'. This is done because printf is a varargs 1338 // function. 1339 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex)) 1340 if (ICE->getType() == S.Context.IntTy) 1341 if (ATR.matchesType(S.Context, ICE->getSubExpr()->getType())) 1342 return true; 1343 1344 S.Diag(getLocationOfByte(CS.getStart()), 1345 diag::warn_printf_conversion_argument_type_mismatch) 1346 << ATR.getRepresentativeType(S.Context) << Ex->getType() 1347 << getFormatSpecifierRange(startSpecifier, specifierLen) 1348 << Ex->getSourceRange(); 1349 } 1350 1351 return true; 1352} 1353 1354void CheckPrintfHandler::DoneProcessing() { 1355 // Does the number of data arguments exceed the number of 1356 // format conversions in the format string? 1357 if (!HasVAListArg) { 1358 // Find any arguments that weren't covered. 1359 CoveredArgs.flip(); 1360 signed notCoveredArg = CoveredArgs.find_first(); 1361 if (notCoveredArg >= 0) { 1362 assert((unsigned)notCoveredArg < NumDataArgs); 1363 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(), 1364 diag::warn_printf_data_arg_not_used) 1365 << getFormatStringRange(); 1366 } 1367 } 1368} 1369 1370void Sema::CheckPrintfString(const StringLiteral *FExpr, 1371 const Expr *OrigFormatExpr, 1372 const CallExpr *TheCall, bool HasVAListArg, 1373 unsigned format_idx, unsigned firstDataArg) { 1374 1375 // CHECK: is the format string a wide literal? 1376 if (FExpr->isWide()) { 1377 Diag(FExpr->getLocStart(), 1378 diag::warn_printf_format_string_is_wide_literal) 1379 << OrigFormatExpr->getSourceRange(); 1380 return; 1381 } 1382 1383 // Str - The format string. NOTE: this is NOT null-terminated! 1384 const char *Str = FExpr->getStrData(); 1385 1386 // CHECK: empty format string? 1387 unsigned StrLen = FExpr->getByteLength(); 1388 1389 if (StrLen == 0) { 1390 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string) 1391 << OrigFormatExpr->getSourceRange(); 1392 return; 1393 } 1394 1395 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 1396 TheCall->getNumArgs() - firstDataArg, 1397 isa<ObjCStringLiteral>(OrigFormatExpr), Str, 1398 HasVAListArg, TheCall, format_idx); 1399 1400 if (!analyze_printf::ParseFormatString(H, Str, Str + StrLen)) 1401 H.DoneProcessing(); 1402} 1403 1404//===--- CHECK: Return Address of Stack Variable --------------------------===// 1405 1406static DeclRefExpr* EvalVal(Expr *E); 1407static DeclRefExpr* EvalAddr(Expr* E); 1408 1409/// CheckReturnStackAddr - Check if a return statement returns the address 1410/// of a stack variable. 1411void 1412Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 1413 SourceLocation ReturnLoc) { 1414 1415 // Perform checking for returned stack addresses. 1416 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) { 1417 if (DeclRefExpr *DR = EvalAddr(RetValExp)) 1418 Diag(DR->getLocStart(), diag::warn_ret_stack_addr) 1419 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange(); 1420 1421 // Skip over implicit cast expressions when checking for block expressions. 1422 RetValExp = RetValExp->IgnoreParenCasts(); 1423 1424 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp)) 1425 if (C->hasBlockDeclRefExprs()) 1426 Diag(C->getLocStart(), diag::err_ret_local_block) 1427 << C->getSourceRange(); 1428 1429 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp)) 1430 Diag(ALE->getLocStart(), diag::warn_ret_addr_label) 1431 << ALE->getSourceRange(); 1432 1433 } else if (lhsType->isReferenceType()) { 1434 // Perform checking for stack values returned by reference. 1435 // Check for a reference to the stack 1436 if (DeclRefExpr *DR = EvalVal(RetValExp)) 1437 Diag(DR->getLocStart(), diag::warn_ret_stack_ref) 1438 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange(); 1439 } 1440} 1441 1442/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 1443/// check if the expression in a return statement evaluates to an address 1444/// to a location on the stack. The recursion is used to traverse the 1445/// AST of the return expression, with recursion backtracking when we 1446/// encounter a subexpression that (1) clearly does not lead to the address 1447/// of a stack variable or (2) is something we cannot determine leads to 1448/// the address of a stack variable based on such local checking. 1449/// 1450/// EvalAddr processes expressions that are pointers that are used as 1451/// references (and not L-values). EvalVal handles all other values. 1452/// At the base case of the recursion is a check for a DeclRefExpr* in 1453/// the refers to a stack variable. 1454/// 1455/// This implementation handles: 1456/// 1457/// * pointer-to-pointer casts 1458/// * implicit conversions from array references to pointers 1459/// * taking the address of fields 1460/// * arbitrary interplay between "&" and "*" operators 1461/// * pointer arithmetic from an address of a stack variable 1462/// * taking the address of an array element where the array is on the stack 1463static DeclRefExpr* EvalAddr(Expr *E) { 1464 // We should only be called for evaluating pointer expressions. 1465 assert((E->getType()->isAnyPointerType() || 1466 E->getType()->isBlockPointerType() || 1467 E->getType()->isObjCQualifiedIdType()) && 1468 "EvalAddr only works on pointers"); 1469 1470 // Our "symbolic interpreter" is just a dispatch off the currently 1471 // viewed AST node. We then recursively traverse the AST by calling 1472 // EvalAddr and EvalVal appropriately. 1473 switch (E->getStmtClass()) { 1474 case Stmt::ParenExprClass: 1475 // Ignore parentheses. 1476 return EvalAddr(cast<ParenExpr>(E)->getSubExpr()); 1477 1478 case Stmt::UnaryOperatorClass: { 1479 // The only unary operator that make sense to handle here 1480 // is AddrOf. All others don't make sense as pointers. 1481 UnaryOperator *U = cast<UnaryOperator>(E); 1482 1483 if (U->getOpcode() == UnaryOperator::AddrOf) 1484 return EvalVal(U->getSubExpr()); 1485 else 1486 return NULL; 1487 } 1488 1489 case Stmt::BinaryOperatorClass: { 1490 // Handle pointer arithmetic. All other binary operators are not valid 1491 // in this context. 1492 BinaryOperator *B = cast<BinaryOperator>(E); 1493 BinaryOperator::Opcode op = B->getOpcode(); 1494 1495 if (op != BinaryOperator::Add && op != BinaryOperator::Sub) 1496 return NULL; 1497 1498 Expr *Base = B->getLHS(); 1499 1500 // Determine which argument is the real pointer base. It could be 1501 // the RHS argument instead of the LHS. 1502 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 1503 1504 assert (Base->getType()->isPointerType()); 1505 return EvalAddr(Base); 1506 } 1507 1508 // For conditional operators we need to see if either the LHS or RHS are 1509 // valid DeclRefExpr*s. If one of them is valid, we return it. 1510 case Stmt::ConditionalOperatorClass: { 1511 ConditionalOperator *C = cast<ConditionalOperator>(E); 1512 1513 // Handle the GNU extension for missing LHS. 1514 if (Expr *lhsExpr = C->getLHS()) 1515 if (DeclRefExpr* LHS = EvalAddr(lhsExpr)) 1516 return LHS; 1517 1518 return EvalAddr(C->getRHS()); 1519 } 1520 1521 // For casts, we need to handle conversions from arrays to 1522 // pointer values, and pointer-to-pointer conversions. 1523 case Stmt::ImplicitCastExprClass: 1524 case Stmt::CStyleCastExprClass: 1525 case Stmt::CXXFunctionalCastExprClass: { 1526 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 1527 QualType T = SubExpr->getType(); 1528 1529 if (SubExpr->getType()->isPointerType() || 1530 SubExpr->getType()->isBlockPointerType() || 1531 SubExpr->getType()->isObjCQualifiedIdType()) 1532 return EvalAddr(SubExpr); 1533 else if (T->isArrayType()) 1534 return EvalVal(SubExpr); 1535 else 1536 return 0; 1537 } 1538 1539 // C++ casts. For dynamic casts, static casts, and const casts, we 1540 // are always converting from a pointer-to-pointer, so we just blow 1541 // through the cast. In the case the dynamic cast doesn't fail (and 1542 // return NULL), we take the conservative route and report cases 1543 // where we return the address of a stack variable. For Reinterpre 1544 // FIXME: The comment about is wrong; we're not always converting 1545 // from pointer to pointer. I'm guessing that this code should also 1546 // handle references to objects. 1547 case Stmt::CXXStaticCastExprClass: 1548 case Stmt::CXXDynamicCastExprClass: 1549 case Stmt::CXXConstCastExprClass: 1550 case Stmt::CXXReinterpretCastExprClass: { 1551 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr(); 1552 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType()) 1553 return EvalAddr(S); 1554 else 1555 return NULL; 1556 } 1557 1558 // Everything else: we simply don't reason about them. 1559 default: 1560 return NULL; 1561 } 1562} 1563 1564 1565/// EvalVal - This function is complements EvalAddr in the mutual recursion. 1566/// See the comments for EvalAddr for more details. 1567static DeclRefExpr* EvalVal(Expr *E) { 1568 1569 // We should only be called for evaluating non-pointer expressions, or 1570 // expressions with a pointer type that are not used as references but instead 1571 // are l-values (e.g., DeclRefExpr with a pointer type). 1572 1573 // Our "symbolic interpreter" is just a dispatch off the currently 1574 // viewed AST node. We then recursively traverse the AST by calling 1575 // EvalAddr and EvalVal appropriately. 1576 switch (E->getStmtClass()) { 1577 case Stmt::DeclRefExprClass: { 1578 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking 1579 // at code that refers to a variable's name. We check if it has local 1580 // storage within the function, and if so, return the expression. 1581 DeclRefExpr *DR = cast<DeclRefExpr>(E); 1582 1583 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 1584 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR; 1585 1586 return NULL; 1587 } 1588 1589 case Stmt::ParenExprClass: 1590 // Ignore parentheses. 1591 return EvalVal(cast<ParenExpr>(E)->getSubExpr()); 1592 1593 case Stmt::UnaryOperatorClass: { 1594 // The only unary operator that make sense to handle here 1595 // is Deref. All others don't resolve to a "name." This includes 1596 // handling all sorts of rvalues passed to a unary operator. 1597 UnaryOperator *U = cast<UnaryOperator>(E); 1598 1599 if (U->getOpcode() == UnaryOperator::Deref) 1600 return EvalAddr(U->getSubExpr()); 1601 1602 return NULL; 1603 } 1604 1605 case Stmt::ArraySubscriptExprClass: { 1606 // Array subscripts are potential references to data on the stack. We 1607 // retrieve the DeclRefExpr* for the array variable if it indeed 1608 // has local storage. 1609 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase()); 1610 } 1611 1612 case Stmt::ConditionalOperatorClass: { 1613 // For conditional operators we need to see if either the LHS or RHS are 1614 // non-NULL DeclRefExpr's. If one is non-NULL, we return it. 1615 ConditionalOperator *C = cast<ConditionalOperator>(E); 1616 1617 // Handle the GNU extension for missing LHS. 1618 if (Expr *lhsExpr = C->getLHS()) 1619 if (DeclRefExpr *LHS = EvalVal(lhsExpr)) 1620 return LHS; 1621 1622 return EvalVal(C->getRHS()); 1623 } 1624 1625 // Accesses to members are potential references to data on the stack. 1626 case Stmt::MemberExprClass: { 1627 MemberExpr *M = cast<MemberExpr>(E); 1628 1629 // Check for indirect access. We only want direct field accesses. 1630 if (!M->isArrow()) 1631 return EvalVal(M->getBase()); 1632 else 1633 return NULL; 1634 } 1635 1636 // Everything else: we simply don't reason about them. 1637 default: 1638 return NULL; 1639 } 1640} 1641 1642//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 1643 1644/// Check for comparisons of floating point operands using != and ==. 1645/// Issue a warning if these are no self-comparisons, as they are not likely 1646/// to do what the programmer intended. 1647void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) { 1648 bool EmitWarning = true; 1649 1650 Expr* LeftExprSansParen = lex->IgnoreParens(); 1651 Expr* RightExprSansParen = rex->IgnoreParens(); 1652 1653 // Special case: check for x == x (which is OK). 1654 // Do not emit warnings for such cases. 1655 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 1656 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 1657 if (DRL->getDecl() == DRR->getDecl()) 1658 EmitWarning = false; 1659 1660 1661 // Special case: check for comparisons against literals that can be exactly 1662 // represented by APFloat. In such cases, do not emit a warning. This 1663 // is a heuristic: often comparison against such literals are used to 1664 // detect if a value in a variable has not changed. This clearly can 1665 // lead to false negatives. 1666 if (EmitWarning) { 1667 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 1668 if (FLL->isExact()) 1669 EmitWarning = false; 1670 } else 1671 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){ 1672 if (FLR->isExact()) 1673 EmitWarning = false; 1674 } 1675 } 1676 1677 // Check for comparisons with builtin types. 1678 if (EmitWarning) 1679 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 1680 if (CL->isBuiltinCall(Context)) 1681 EmitWarning = false; 1682 1683 if (EmitWarning) 1684 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 1685 if (CR->isBuiltinCall(Context)) 1686 EmitWarning = false; 1687 1688 // Emit the diagnostic. 1689 if (EmitWarning) 1690 Diag(loc, diag::warn_floatingpoint_eq) 1691 << lex->getSourceRange() << rex->getSourceRange(); 1692} 1693 1694//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 1695//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 1696 1697namespace { 1698 1699/// Structure recording the 'active' range of an integer-valued 1700/// expression. 1701struct IntRange { 1702 /// The number of bits active in the int. 1703 unsigned Width; 1704 1705 /// True if the int is known not to have negative values. 1706 bool NonNegative; 1707 1708 IntRange() {} 1709 IntRange(unsigned Width, bool NonNegative) 1710 : Width(Width), NonNegative(NonNegative) 1711 {} 1712 1713 // Returns the range of the bool type. 1714 static IntRange forBoolType() { 1715 return IntRange(1, true); 1716 } 1717 1718 // Returns the range of an integral type. 1719 static IntRange forType(ASTContext &C, QualType T) { 1720 return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr()); 1721 } 1722 1723 // Returns the range of an integeral type based on its canonical 1724 // representation. 1725 static IntRange forCanonicalType(ASTContext &C, const Type *T) { 1726 assert(T->isCanonicalUnqualified()); 1727 1728 if (const VectorType *VT = dyn_cast<VectorType>(T)) 1729 T = VT->getElementType().getTypePtr(); 1730 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 1731 T = CT->getElementType().getTypePtr(); 1732 if (const EnumType *ET = dyn_cast<EnumType>(T)) 1733 T = ET->getDecl()->getIntegerType().getTypePtr(); 1734 1735 const BuiltinType *BT = cast<BuiltinType>(T); 1736 assert(BT->isInteger()); 1737 1738 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 1739 } 1740 1741 // Returns the supremum of two ranges: i.e. their conservative merge. 1742 static IntRange join(IntRange L, IntRange R) { 1743 return IntRange(std::max(L.Width, R.Width), 1744 L.NonNegative && R.NonNegative); 1745 } 1746 1747 // Returns the infinum of two ranges: i.e. their aggressive merge. 1748 static IntRange meet(IntRange L, IntRange R) { 1749 return IntRange(std::min(L.Width, R.Width), 1750 L.NonNegative || R.NonNegative); 1751 } 1752}; 1753 1754IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 1755 if (value.isSigned() && value.isNegative()) 1756 return IntRange(value.getMinSignedBits(), false); 1757 1758 if (value.getBitWidth() > MaxWidth) 1759 value.trunc(MaxWidth); 1760 1761 // isNonNegative() just checks the sign bit without considering 1762 // signedness. 1763 return IntRange(value.getActiveBits(), true); 1764} 1765 1766IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 1767 unsigned MaxWidth) { 1768 if (result.isInt()) 1769 return GetValueRange(C, result.getInt(), MaxWidth); 1770 1771 if (result.isVector()) { 1772 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 1773 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 1774 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 1775 R = IntRange::join(R, El); 1776 } 1777 return R; 1778 } 1779 1780 if (result.isComplexInt()) { 1781 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 1782 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 1783 return IntRange::join(R, I); 1784 } 1785 1786 // This can happen with lossless casts to intptr_t of "based" lvalues. 1787 // Assume it might use arbitrary bits. 1788 // FIXME: The only reason we need to pass the type in here is to get 1789 // the sign right on this one case. It would be nice if APValue 1790 // preserved this. 1791 assert(result.isLValue()); 1792 return IntRange(MaxWidth, Ty->isUnsignedIntegerType()); 1793} 1794 1795/// Pseudo-evaluate the given integer expression, estimating the 1796/// range of values it might take. 1797/// 1798/// \param MaxWidth - the width to which the value will be truncated 1799IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { 1800 E = E->IgnoreParens(); 1801 1802 // Try a full evaluation first. 1803 Expr::EvalResult result; 1804 if (E->Evaluate(result, C)) 1805 return GetValueRange(C, result.Val, E->getType(), MaxWidth); 1806 1807 // I think we only want to look through implicit casts here; if the 1808 // user has an explicit widening cast, we should treat the value as 1809 // being of the new, wider type. 1810 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 1811 if (CE->getCastKind() == CastExpr::CK_NoOp) 1812 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 1813 1814 IntRange OutputTypeRange = IntRange::forType(C, CE->getType()); 1815 1816 bool isIntegerCast = (CE->getCastKind() == CastExpr::CK_IntegralCast); 1817 if (!isIntegerCast && CE->getCastKind() == CastExpr::CK_Unknown) 1818 isIntegerCast = CE->getSubExpr()->getType()->isIntegerType(); 1819 1820 // Assume that non-integer casts can span the full range of the type. 1821 if (!isIntegerCast) 1822 return OutputTypeRange; 1823 1824 IntRange SubRange 1825 = GetExprRange(C, CE->getSubExpr(), 1826 std::min(MaxWidth, OutputTypeRange.Width)); 1827 1828 // Bail out if the subexpr's range is as wide as the cast type. 1829 if (SubRange.Width >= OutputTypeRange.Width) 1830 return OutputTypeRange; 1831 1832 // Otherwise, we take the smaller width, and we're non-negative if 1833 // either the output type or the subexpr is. 1834 return IntRange(SubRange.Width, 1835 SubRange.NonNegative || OutputTypeRange.NonNegative); 1836 } 1837 1838 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 1839 // If we can fold the condition, just take that operand. 1840 bool CondResult; 1841 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 1842 return GetExprRange(C, CondResult ? CO->getTrueExpr() 1843 : CO->getFalseExpr(), 1844 MaxWidth); 1845 1846 // Otherwise, conservatively merge. 1847 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 1848 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 1849 return IntRange::join(L, R); 1850 } 1851 1852 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 1853 switch (BO->getOpcode()) { 1854 1855 // Boolean-valued operations are single-bit and positive. 1856 case BinaryOperator::LAnd: 1857 case BinaryOperator::LOr: 1858 case BinaryOperator::LT: 1859 case BinaryOperator::GT: 1860 case BinaryOperator::LE: 1861 case BinaryOperator::GE: 1862 case BinaryOperator::EQ: 1863 case BinaryOperator::NE: 1864 return IntRange::forBoolType(); 1865 1866 // The type of these compound assignments is the type of the LHS, 1867 // so the RHS is not necessarily an integer. 1868 case BinaryOperator::MulAssign: 1869 case BinaryOperator::DivAssign: 1870 case BinaryOperator::RemAssign: 1871 case BinaryOperator::AddAssign: 1872 case BinaryOperator::SubAssign: 1873 return IntRange::forType(C, E->getType()); 1874 1875 // Operations with opaque sources are black-listed. 1876 case BinaryOperator::PtrMemD: 1877 case BinaryOperator::PtrMemI: 1878 return IntRange::forType(C, E->getType()); 1879 1880 // Bitwise-and uses the *infinum* of the two source ranges. 1881 case BinaryOperator::And: 1882 case BinaryOperator::AndAssign: 1883 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 1884 GetExprRange(C, BO->getRHS(), MaxWidth)); 1885 1886 // Left shift gets black-listed based on a judgement call. 1887 case BinaryOperator::Shl: 1888 case BinaryOperator::ShlAssign: 1889 return IntRange::forType(C, E->getType()); 1890 1891 // Right shift by a constant can narrow its left argument. 1892 case BinaryOperator::Shr: 1893 case BinaryOperator::ShrAssign: { 1894 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 1895 1896 // If the shift amount is a positive constant, drop the width by 1897 // that much. 1898 llvm::APSInt shift; 1899 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 1900 shift.isNonNegative()) { 1901 unsigned zext = shift.getZExtValue(); 1902 if (zext >= L.Width) 1903 L.Width = (L.NonNegative ? 0 : 1); 1904 else 1905 L.Width -= zext; 1906 } 1907 1908 return L; 1909 } 1910 1911 // Comma acts as its right operand. 1912 case BinaryOperator::Comma: 1913 return GetExprRange(C, BO->getRHS(), MaxWidth); 1914 1915 // Black-list pointer subtractions. 1916 case BinaryOperator::Sub: 1917 if (BO->getLHS()->getType()->isPointerType()) 1918 return IntRange::forType(C, E->getType()); 1919 // fallthrough 1920 1921 default: 1922 break; 1923 } 1924 1925 // Treat every other operator as if it were closed on the 1926 // narrowest type that encompasses both operands. 1927 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 1928 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 1929 return IntRange::join(L, R); 1930 } 1931 1932 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 1933 switch (UO->getOpcode()) { 1934 // Boolean-valued operations are white-listed. 1935 case UnaryOperator::LNot: 1936 return IntRange::forBoolType(); 1937 1938 // Operations with opaque sources are black-listed. 1939 case UnaryOperator::Deref: 1940 case UnaryOperator::AddrOf: // should be impossible 1941 case UnaryOperator::OffsetOf: 1942 return IntRange::forType(C, E->getType()); 1943 1944 default: 1945 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 1946 } 1947 } 1948 1949 FieldDecl *BitField = E->getBitField(); 1950 if (BitField) { 1951 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C); 1952 unsigned BitWidth = BitWidthAP.getZExtValue(); 1953 1954 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType()); 1955 } 1956 1957 return IntRange::forType(C, E->getType()); 1958} 1959 1960/// Checks whether the given value, which currently has the given 1961/// source semantics, has the same value when coerced through the 1962/// target semantics. 1963bool IsSameFloatAfterCast(const llvm::APFloat &value, 1964 const llvm::fltSemantics &Src, 1965 const llvm::fltSemantics &Tgt) { 1966 llvm::APFloat truncated = value; 1967 1968 bool ignored; 1969 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 1970 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 1971 1972 return truncated.bitwiseIsEqual(value); 1973} 1974 1975/// Checks whether the given value, which currently has the given 1976/// source semantics, has the same value when coerced through the 1977/// target semantics. 1978/// 1979/// The value might be a vector of floats (or a complex number). 1980bool IsSameFloatAfterCast(const APValue &value, 1981 const llvm::fltSemantics &Src, 1982 const llvm::fltSemantics &Tgt) { 1983 if (value.isFloat()) 1984 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 1985 1986 if (value.isVector()) { 1987 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 1988 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 1989 return false; 1990 return true; 1991 } 1992 1993 assert(value.isComplexFloat()); 1994 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 1995 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 1996} 1997 1998} // end anonymous namespace 1999 2000/// \brief Implements -Wsign-compare. 2001/// 2002/// \param lex the left-hand expression 2003/// \param rex the right-hand expression 2004/// \param OpLoc the location of the joining operator 2005/// \param BinOpc binary opcode or 0 2006void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc, 2007 const BinaryOperator::Opcode* BinOpc) { 2008 // Don't warn if we're in an unevaluated context. 2009 if (ExprEvalContexts.back().Context == Unevaluated) 2010 return; 2011 2012 // If either expression is value-dependent, don't warn. We'll get another 2013 // chance at instantiation time. 2014 if (lex->isValueDependent() || rex->isValueDependent()) 2015 return; 2016 2017 QualType lt = lex->getType(), rt = rex->getType(); 2018 2019 // Only warn if both operands are integral. 2020 if (!lt->isIntegerType() || !rt->isIntegerType()) 2021 return; 2022 2023 // In C, the width of a bitfield determines its type, and the 2024 // declared type only contributes the signedness. This duplicates 2025 // the work that will later be done by UsualUnaryConversions. 2026 // Eventually, this check will be reorganized in a way that avoids 2027 // this duplication. 2028 if (!getLangOptions().CPlusPlus) { 2029 QualType tmp; 2030 tmp = Context.isPromotableBitField(lex); 2031 if (!tmp.isNull()) lt = tmp; 2032 tmp = Context.isPromotableBitField(rex); 2033 if (!tmp.isNull()) rt = tmp; 2034 } 2035 2036 if (const EnumType *E = lt->getAs<EnumType>()) 2037 lt = E->getDecl()->getPromotionType(); 2038 if (const EnumType *E = rt->getAs<EnumType>()) 2039 rt = E->getDecl()->getPromotionType(); 2040 2041 // The rule is that the signed operand becomes unsigned, so isolate the 2042 // signed operand. 2043 Expr *signedOperand = lex, *unsignedOperand = rex; 2044 QualType signedType = lt, unsignedType = rt; 2045 if (lt->isSignedIntegerType()) { 2046 if (rt->isSignedIntegerType()) return; 2047 } else { 2048 if (!rt->isSignedIntegerType()) return; 2049 std::swap(signedOperand, unsignedOperand); 2050 std::swap(signedType, unsignedType); 2051 } 2052 2053 unsigned unsignedWidth = Context.getIntWidth(unsignedType); 2054 unsigned signedWidth = Context.getIntWidth(signedType); 2055 2056 // If the unsigned type is strictly smaller than the signed type, 2057 // then (1) the result type will be signed and (2) the unsigned 2058 // value will fit fully within the signed type, and thus the result 2059 // of the comparison will be exact. 2060 if (signedWidth > unsignedWidth) 2061 return; 2062 2063 // Otherwise, calculate the effective ranges. 2064 IntRange signedRange = GetExprRange(Context, signedOperand, signedWidth); 2065 IntRange unsignedRange = GetExprRange(Context, unsignedOperand, unsignedWidth); 2066 2067 // We should never be unable to prove that the unsigned operand is 2068 // non-negative. 2069 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 2070 2071 // If the signed operand is non-negative, then the signed->unsigned 2072 // conversion won't change it. 2073 if (signedRange.NonNegative) { 2074 // Emit warnings for comparisons of unsigned to integer constant 0. 2075 // always false: x < 0 (or 0 > x) 2076 // always true: x >= 0 (or 0 <= x) 2077 llvm::APSInt X; 2078 if (BinOpc && signedOperand->isIntegerConstantExpr(X, Context) && X == 0) { 2079 if (signedOperand != lex) { 2080 if (*BinOpc == BinaryOperator::LT) { 2081 Diag(OpLoc, diag::warn_lunsigned_always_true_comparison) 2082 << "< 0" << "false" 2083 << lex->getSourceRange() << rex->getSourceRange(); 2084 } 2085 else if (*BinOpc == BinaryOperator::GE) { 2086 Diag(OpLoc, diag::warn_lunsigned_always_true_comparison) 2087 << ">= 0" << "true" 2088 << lex->getSourceRange() << rex->getSourceRange(); 2089 } 2090 } 2091 else { 2092 if (*BinOpc == BinaryOperator::GT) { 2093 Diag(OpLoc, diag::warn_runsigned_always_true_comparison) 2094 << "0 >" << "false" 2095 << lex->getSourceRange() << rex->getSourceRange(); 2096 } 2097 else if (*BinOpc == BinaryOperator::LE) { 2098 Diag(OpLoc, diag::warn_runsigned_always_true_comparison) 2099 << "0 <=" << "true" 2100 << lex->getSourceRange() << rex->getSourceRange(); 2101 } 2102 } 2103 } 2104 return; 2105 } 2106 2107 // For (in)equality comparisons, if the unsigned operand is a 2108 // constant which cannot collide with a overflowed signed operand, 2109 // then reinterpreting the signed operand as unsigned will not 2110 // change the result of the comparison. 2111 if (BinOpc && 2112 (*BinOpc == BinaryOperator::EQ || *BinOpc == BinaryOperator::NE) && 2113 unsignedRange.Width < unsignedWidth) 2114 return; 2115 2116 Diag(OpLoc, BinOpc ? diag::warn_mixed_sign_comparison 2117 : diag::warn_mixed_sign_conditional) 2118 << lt << rt << lex->getSourceRange() << rex->getSourceRange(); 2119} 2120 2121/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 2122static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) { 2123 S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange(); 2124} 2125 2126/// Implements -Wconversion. 2127void Sema::CheckImplicitConversion(Expr *E, QualType T) { 2128 // Don't diagnose in unevaluated contexts. 2129 if (ExprEvalContexts.back().Context == Sema::Unevaluated) 2130 return; 2131 2132 // Don't diagnose for value-dependent expressions. 2133 if (E->isValueDependent()) 2134 return; 2135 2136 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr(); 2137 const Type *Target = Context.getCanonicalType(T).getTypePtr(); 2138 2139 // Never diagnose implicit casts to bool. 2140 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 2141 return; 2142 2143 // Strip vector types. 2144 if (isa<VectorType>(Source)) { 2145 if (!isa<VectorType>(Target)) 2146 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_vector_scalar); 2147 2148 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 2149 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 2150 } 2151 2152 // Strip complex types. 2153 if (isa<ComplexType>(Source)) { 2154 if (!isa<ComplexType>(Target)) 2155 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_complex_scalar); 2156 2157 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 2158 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 2159 } 2160 2161 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 2162 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 2163 2164 // If the source is floating point... 2165 if (SourceBT && SourceBT->isFloatingPoint()) { 2166 // ...and the target is floating point... 2167 if (TargetBT && TargetBT->isFloatingPoint()) { 2168 // ...then warn if we're dropping FP rank. 2169 2170 // Builtin FP kinds are ordered by increasing FP rank. 2171 if (SourceBT->getKind() > TargetBT->getKind()) { 2172 // Don't warn about float constants that are precisely 2173 // representable in the target type. 2174 Expr::EvalResult result; 2175 if (E->Evaluate(result, Context)) { 2176 // Value might be a float, a float vector, or a float complex. 2177 if (IsSameFloatAfterCast(result.Val, 2178 Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 2179 Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 2180 return; 2181 } 2182 2183 DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_precision); 2184 } 2185 return; 2186 } 2187 2188 // If the target is integral, always warn. 2189 if ((TargetBT && TargetBT->isInteger())) 2190 // TODO: don't warn for integer values? 2191 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_integer); 2192 2193 return; 2194 } 2195 2196 if (!Source->isIntegerType() || !Target->isIntegerType()) 2197 return; 2198 2199 IntRange SourceRange = GetExprRange(Context, E, Context.getIntWidth(E->getType())); 2200 IntRange TargetRange = IntRange::forCanonicalType(Context, Target); 2201 2202 // FIXME: also signed<->unsigned? 2203 2204 if (SourceRange.Width > TargetRange.Width) { 2205 // People want to build with -Wshorten-64-to-32 and not -Wconversion 2206 // and by god we'll let them. 2207 if (SourceRange.Width == 64 && TargetRange.Width == 32) 2208 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_64_32); 2209 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_precision); 2210 } 2211 2212 return; 2213} 2214 2215/// CheckParmsForFunctionDef - Check that the parameters of the given 2216/// function are appropriate for the definition of a function. This 2217/// takes care of any checks that cannot be performed on the 2218/// declaration itself, e.g., that the types of each of the function 2219/// parameters are complete. 2220bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) { 2221 bool HasInvalidParm = false; 2222 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 2223 ParmVarDecl *Param = FD->getParamDecl(p); 2224 2225 // C99 6.7.5.3p4: the parameters in a parameter type list in a 2226 // function declarator that is part of a function definition of 2227 // that function shall not have incomplete type. 2228 // 2229 // This is also C++ [dcl.fct]p6. 2230 if (!Param->isInvalidDecl() && 2231 RequireCompleteType(Param->getLocation(), Param->getType(), 2232 diag::err_typecheck_decl_incomplete_type)) { 2233 Param->setInvalidDecl(); 2234 HasInvalidParm = true; 2235 } 2236 2237 // C99 6.9.1p5: If the declarator includes a parameter type list, the 2238 // declaration of each parameter shall include an identifier. 2239 if (Param->getIdentifier() == 0 && 2240 !Param->isImplicit() && 2241 !getLangOptions().CPlusPlus) 2242 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 2243 2244 // C99 6.7.5.3p12: 2245 // If the function declarator is not part of a definition of that 2246 // function, parameters may have incomplete type and may use the [*] 2247 // notation in their sequences of declarator specifiers to specify 2248 // variable length array types. 2249 QualType PType = Param->getOriginalType(); 2250 if (const ArrayType *AT = Context.getAsArrayType(PType)) { 2251 if (AT->getSizeModifier() == ArrayType::Star) { 2252 // FIXME: This diagnosic should point the the '[*]' if source-location 2253 // information is added for it. 2254 Diag(Param->getLocation(), diag::err_array_star_in_function_definition); 2255 } 2256 } 2257 } 2258 2259 return HasInvalidParm; 2260} 2261