SemaChecking.cpp revision eebd9d2165a705ce6a8a6b6a7327864189d02785
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/AST/ASTContext.h" 17#include "clang/AST/DeclObjC.h" 18#include "clang/AST/ExprCXX.h" 19#include "clang/AST/ExprObjC.h" 20#include "clang/Lex/LiteralSupport.h" 21#include "clang/Lex/Preprocessor.h" 22using namespace clang; 23 24/// getLocationOfStringLiteralByte - Return a source location that points to the 25/// specified byte of the specified string literal. 26/// 27/// Strings are amazingly complex. They can be formed from multiple tokens and 28/// can have escape sequences in them in addition to the usual trigraph and 29/// escaped newline business. This routine handles this complexity. 30/// 31SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 32 unsigned ByteNo) const { 33 assert(!SL->isWide() && "This doesn't work for wide strings yet"); 34 35 // Loop over all of the tokens in this string until we find the one that 36 // contains the byte we're looking for. 37 unsigned TokNo = 0; 38 while (1) { 39 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!"); 40 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo); 41 42 // Get the spelling of the string so that we can get the data that makes up 43 // the string literal, not the identifier for the macro it is potentially 44 // expanded through. 45 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc); 46 47 // Re-lex the token to get its length and original spelling. 48 std::pair<FileID, unsigned> LocInfo = 49 SourceMgr.getDecomposedLoc(StrTokSpellingLoc); 50 std::pair<const char *,const char *> Buffer = 51 SourceMgr.getBufferData(LocInfo.first); 52 const char *StrData = Buffer.first+LocInfo.second; 53 54 // Create a langops struct and enable trigraphs. This is sufficient for 55 // relexing tokens. 56 LangOptions LangOpts; 57 LangOpts.Trigraphs = true; 58 59 // Create a lexer starting at the beginning of this token. 60 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData, 61 Buffer.second); 62 Token TheTok; 63 TheLexer.LexFromRawLexer(TheTok); 64 65 // Use the StringLiteralParser to compute the length of the string in bytes. 66 StringLiteralParser SLP(&TheTok, 1, PP); 67 unsigned TokNumBytes = SLP.GetStringLength(); 68 69 // If the byte is in this token, return the location of the byte. 70 if (ByteNo < TokNumBytes || 71 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) { 72 unsigned Offset = 73 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP); 74 75 // Now that we know the offset of the token in the spelling, use the 76 // preprocessor to get the offset in the original source. 77 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset); 78 } 79 80 // Move to the next string token. 81 ++TokNo; 82 ByteNo -= TokNumBytes; 83 } 84} 85 86 87/// CheckFunctionCall - Check a direct function call for various correctness 88/// and safety properties not strictly enforced by the C type system. 89Action::OwningExprResult 90Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) { 91 OwningExprResult TheCallResult(Owned(TheCall)); 92 // Get the IdentifierInfo* for the called function. 93 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 94 95 // None of the checks below are needed for functions that don't have 96 // simple names (e.g., C++ conversion functions). 97 if (!FnInfo) 98 return move(TheCallResult); 99 100 switch (FDecl->getBuiltinID(Context)) { 101 case Builtin::BI__builtin___CFStringMakeConstantString: 102 assert(TheCall->getNumArgs() == 1 && 103 "Wrong # arguments to builtin CFStringMakeConstantString"); 104 if (CheckObjCString(TheCall->getArg(0))) 105 return ExprError(); 106 return move(TheCallResult); 107 case Builtin::BI__builtin_stdarg_start: 108 case Builtin::BI__builtin_va_start: 109 if (SemaBuiltinVAStart(TheCall)) 110 return ExprError(); 111 return move(TheCallResult); 112 case Builtin::BI__builtin_isgreater: 113 case Builtin::BI__builtin_isgreaterequal: 114 case Builtin::BI__builtin_isless: 115 case Builtin::BI__builtin_islessequal: 116 case Builtin::BI__builtin_islessgreater: 117 case Builtin::BI__builtin_isunordered: 118 if (SemaBuiltinUnorderedCompare(TheCall)) 119 return ExprError(); 120 return move(TheCallResult); 121 case Builtin::BI__builtin_return_address: 122 case Builtin::BI__builtin_frame_address: 123 if (SemaBuiltinStackAddress(TheCall)) 124 return ExprError(); 125 return move(TheCallResult); 126 case Builtin::BI__builtin_shufflevector: 127 return SemaBuiltinShuffleVector(TheCall); 128 // TheCall will be freed by the smart pointer here, but that's fine, since 129 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 130 case Builtin::BI__builtin_prefetch: 131 if (SemaBuiltinPrefetch(TheCall)) 132 return ExprError(); 133 return move(TheCallResult); 134 case Builtin::BI__builtin_object_size: 135 if (SemaBuiltinObjectSize(TheCall)) 136 return ExprError(); 137 return move(TheCallResult); 138 case Builtin::BI__builtin_longjmp: 139 if (SemaBuiltinLongjmp(TheCall)) 140 return ExprError(); 141 return move(TheCallResult); 142 case Builtin::BI__sync_fetch_and_add: 143 case Builtin::BI__sync_fetch_and_sub: 144 case Builtin::BI__sync_fetch_and_or: 145 case Builtin::BI__sync_fetch_and_and: 146 case Builtin::BI__sync_fetch_and_xor: 147 case Builtin::BI__sync_fetch_and_nand: 148 case Builtin::BI__sync_add_and_fetch: 149 case Builtin::BI__sync_sub_and_fetch: 150 case Builtin::BI__sync_and_and_fetch: 151 case Builtin::BI__sync_or_and_fetch: 152 case Builtin::BI__sync_xor_and_fetch: 153 case Builtin::BI__sync_nand_and_fetch: 154 case Builtin::BI__sync_val_compare_and_swap: 155 case Builtin::BI__sync_bool_compare_and_swap: 156 case Builtin::BI__sync_lock_test_and_set: 157 case Builtin::BI__sync_lock_release: 158 if (SemaBuiltinAtomicOverloaded(TheCall)) 159 return ExprError(); 160 return move(TheCallResult); 161 } 162 163 // FIXME: This mechanism should be abstracted to be less fragile and 164 // more efficient. For example, just map function ids to custom 165 // handlers. 166 167 // Printf checking. 168 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) { 169 if (Format->getType() == "printf") { 170 bool HasVAListArg = Format->getFirstArg() == 0; 171 if (!HasVAListArg) { 172 if (const FunctionProtoType *Proto 173 = FDecl->getType()->getAsFunctionProtoType()) 174 HasVAListArg = !Proto->isVariadic(); 175 } 176 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1, 177 HasVAListArg ? 0 : Format->getFirstArg() - 1); 178 } 179 } 180 181 return move(TheCallResult); 182} 183 184/// SemaBuiltinAtomicOverloaded - We have a call to a function like 185/// __sync_fetch_and_add, which is an overloaded function based on the pointer 186/// type of its first argument. The main ActOnCallExpr routines have already 187/// promoted the types of arguments because all of these calls are prototyped as 188/// void(...). 189/// 190/// This function goes through and does final semantic checking for these 191/// builtins, 192bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) { 193 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 194 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 195 196 // Ensure that we have at least one argument to do type inference from. 197 if (TheCall->getNumArgs() < 1) 198 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 199 << 0 << TheCall->getCallee()->getSourceRange(); 200 201 // Inspect the first argument of the atomic builtin. This should always be 202 // a pointer type, whose element is an integral scalar or pointer type. 203 // Because it is a pointer type, we don't have to worry about any implicit 204 // casts here. 205 Expr *FirstArg = TheCall->getArg(0); 206 if (!FirstArg->getType()->isPointerType()) 207 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 208 << FirstArg->getType() << FirstArg->getSourceRange(); 209 210 QualType ValType = FirstArg->getType()->getAsPointerType()->getPointeeType(); 211 if (!ValType->isIntegerType() && !ValType->isPointerType() && 212 !ValType->isBlockPointerType()) 213 return Diag(DRE->getLocStart(), 214 diag::err_atomic_builtin_must_be_pointer_intptr) 215 << FirstArg->getType() << FirstArg->getSourceRange(); 216 217 // We need to figure out which concrete builtin this maps onto. For example, 218 // __sync_fetch_and_add with a 2 byte object turns into 219 // __sync_fetch_and_add_2. 220#define BUILTIN_ROW(x) \ 221 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 222 Builtin::BI##x##_8, Builtin::BI##x##_16 } 223 224 static const unsigned BuiltinIndices[][5] = { 225 BUILTIN_ROW(__sync_fetch_and_add), 226 BUILTIN_ROW(__sync_fetch_and_sub), 227 BUILTIN_ROW(__sync_fetch_and_or), 228 BUILTIN_ROW(__sync_fetch_and_and), 229 BUILTIN_ROW(__sync_fetch_and_xor), 230 BUILTIN_ROW(__sync_fetch_and_nand), 231 232 BUILTIN_ROW(__sync_add_and_fetch), 233 BUILTIN_ROW(__sync_sub_and_fetch), 234 BUILTIN_ROW(__sync_and_and_fetch), 235 BUILTIN_ROW(__sync_or_and_fetch), 236 BUILTIN_ROW(__sync_xor_and_fetch), 237 BUILTIN_ROW(__sync_nand_and_fetch), 238 239 BUILTIN_ROW(__sync_val_compare_and_swap), 240 BUILTIN_ROW(__sync_bool_compare_and_swap), 241 BUILTIN_ROW(__sync_lock_test_and_set), 242 BUILTIN_ROW(__sync_lock_release) 243 }; 244#undef BUILTIN_ROW 245 246 // Determine the index of the size. 247 unsigned SizeIndex; 248 switch (Context.getTypeSize(ValType)/8) { 249 case 1: SizeIndex = 0; break; 250 case 2: SizeIndex = 1; break; 251 case 4: SizeIndex = 2; break; 252 case 8: SizeIndex = 3; break; 253 case 16: SizeIndex = 4; break; 254 default: 255 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 256 << FirstArg->getType() << FirstArg->getSourceRange(); 257 } 258 259 // Each of these builtins has one pointer argument, followed by some number of 260 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 261 // that we ignore. Find out which row of BuiltinIndices to read from as well 262 // as the number of fixed args. 263 unsigned BuiltinID = FDecl->getBuiltinID(Context); 264 unsigned BuiltinIndex, NumFixed = 1; 265 switch (BuiltinID) { 266 default: assert(0 && "Unknown overloaded atomic builtin!"); 267 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break; 268 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break; 269 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break; 270 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break; 271 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break; 272 case Builtin::BI__sync_fetch_and_nand:BuiltinIndex = 5; break; 273 274 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 6; break; 275 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 7; break; 276 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 8; break; 277 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 9; break; 278 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =10; break; 279 case Builtin::BI__sync_nand_and_fetch:BuiltinIndex =11; break; 280 281 case Builtin::BI__sync_val_compare_and_swap: 282 BuiltinIndex = 12; 283 NumFixed = 2; 284 break; 285 case Builtin::BI__sync_bool_compare_and_swap: 286 BuiltinIndex = 13; 287 NumFixed = 2; 288 break; 289 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 14; break; 290 case Builtin::BI__sync_lock_release: 291 BuiltinIndex = 15; 292 NumFixed = 0; 293 break; 294 } 295 296 // Now that we know how many fixed arguments we expect, first check that we 297 // have at least that many. 298 if (TheCall->getNumArgs() < 1+NumFixed) 299 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 300 << 0 << TheCall->getCallee()->getSourceRange(); 301 302 303 // Get the decl for the concrete builtin from this, we can tell what the 304 // concrete integer type we should convert to is. 305 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 306 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID); 307 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName); 308 FunctionDecl *NewBuiltinDecl = 309 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID, 310 TUScope, false, DRE->getLocStart())); 311 const FunctionProtoType *BuiltinFT = 312 NewBuiltinDecl->getType()->getAsFunctionProtoType(); 313 ValType = BuiltinFT->getArgType(0)->getAsPointerType()->getPointeeType(); 314 315 // If the first type needs to be converted (e.g. void** -> int*), do it now. 316 if (BuiltinFT->getArgType(0) != FirstArg->getType()) { 317 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), false); 318 TheCall->setArg(0, FirstArg); 319 } 320 321 // Next, walk the valid ones promoting to the right type. 322 for (unsigned i = 0; i != NumFixed; ++i) { 323 Expr *Arg = TheCall->getArg(i+1); 324 325 // If the argument is an implicit cast, then there was a promotion due to 326 // "...", just remove it now. 327 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) { 328 Arg = ICE->getSubExpr(); 329 ICE->setSubExpr(0); 330 ICE->Destroy(Context); 331 TheCall->setArg(i+1, Arg); 332 } 333 334 // GCC does an implicit conversion to the pointer or integer ValType. This 335 // can fail in some cases (1i -> int**), check for this error case now. 336 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg)) 337 return true; 338 339 // Okay, we have something that *can* be converted to the right type. Check 340 // to see if there is a potentially weird extension going on here. This can 341 // happen when you do an atomic operation on something like an char* and 342 // pass in 42. The 42 gets converted to char. This is even more strange 343 // for things like 45.123 -> char, etc. 344 // FIXME: Do this check. 345 ImpCastExprToType(Arg, ValType, false); 346 TheCall->setArg(i+1, Arg); 347 } 348 349 // Switch the DeclRefExpr to refer to the new decl. 350 DRE->setDecl(NewBuiltinDecl); 351 DRE->setType(NewBuiltinDecl->getType()); 352 353 // Set the callee in the CallExpr. 354 // FIXME: This leaks the original parens and implicit casts. 355 Expr *PromotedCall = DRE; 356 UsualUnaryConversions(PromotedCall); 357 TheCall->setCallee(PromotedCall); 358 359 360 // Change the result type of the call to match the result type of the decl. 361 TheCall->setType(NewBuiltinDecl->getResultType()); 362 return false; 363} 364 365 366/// CheckObjCString - Checks that the argument to the builtin 367/// CFString constructor is correct 368/// FIXME: GCC currently emits the following warning: 369/// "warning: input conversion stopped due to an input byte that does not 370/// belong to the input codeset UTF-8" 371/// Note: It might also make sense to do the UTF-16 conversion here (would 372/// simplify the backend). 373bool Sema::CheckObjCString(Expr *Arg) { 374 Arg = Arg->IgnoreParenCasts(); 375 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 376 377 if (!Literal || Literal->isWide()) { 378 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 379 << Arg->getSourceRange(); 380 return true; 381 } 382 383 const char *Data = Literal->getStrData(); 384 unsigned Length = Literal->getByteLength(); 385 386 for (unsigned i = 0; i < Length; ++i) { 387 if (!Data[i]) { 388 Diag(getLocationOfStringLiteralByte(Literal, i), 389 diag::warn_cfstring_literal_contains_nul_character) 390 << Arg->getSourceRange(); 391 break; 392 } 393 } 394 395 return false; 396} 397 398/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 399/// Emit an error and return true on failure, return false on success. 400bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 401 Expr *Fn = TheCall->getCallee(); 402 if (TheCall->getNumArgs() > 2) { 403 Diag(TheCall->getArg(2)->getLocStart(), 404 diag::err_typecheck_call_too_many_args) 405 << 0 /*function call*/ << Fn->getSourceRange() 406 << SourceRange(TheCall->getArg(2)->getLocStart(), 407 (*(TheCall->arg_end()-1))->getLocEnd()); 408 return true; 409 } 410 411 if (TheCall->getNumArgs() < 2) { 412 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 413 << 0 /*function call*/; 414 } 415 416 // Determine whether the current function is variadic or not. 417 bool isVariadic; 418 if (CurBlock) 419 isVariadic = CurBlock->isVariadic; 420 else if (getCurFunctionDecl()) { 421 if (FunctionProtoType* FTP = 422 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType())) 423 isVariadic = FTP->isVariadic(); 424 else 425 isVariadic = false; 426 } else { 427 isVariadic = getCurMethodDecl()->isVariadic(); 428 } 429 430 if (!isVariadic) { 431 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 432 return true; 433 } 434 435 // Verify that the second argument to the builtin is the last argument of the 436 // current function or method. 437 bool SecondArgIsLastNamedArgument = false; 438 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 439 440 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 441 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 442 // FIXME: This isn't correct for methods (results in bogus warning). 443 // Get the last formal in the current function. 444 const ParmVarDecl *LastArg; 445 if (CurBlock) 446 LastArg = *(CurBlock->TheDecl->param_end()-1); 447 else if (FunctionDecl *FD = getCurFunctionDecl()) 448 LastArg = *(FD->param_end()-1); 449 else 450 LastArg = *(getCurMethodDecl()->param_end()-1); 451 SecondArgIsLastNamedArgument = PV == LastArg; 452 } 453 } 454 455 if (!SecondArgIsLastNamedArgument) 456 Diag(TheCall->getArg(1)->getLocStart(), 457 diag::warn_second_parameter_of_va_start_not_last_named_argument); 458 return false; 459} 460 461/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 462/// friends. This is declared to take (...), so we have to check everything. 463bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 464 if (TheCall->getNumArgs() < 2) 465 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 466 << 0 /*function call*/; 467 if (TheCall->getNumArgs() > 2) 468 return Diag(TheCall->getArg(2)->getLocStart(), 469 diag::err_typecheck_call_too_many_args) 470 << 0 /*function call*/ 471 << SourceRange(TheCall->getArg(2)->getLocStart(), 472 (*(TheCall->arg_end()-1))->getLocEnd()); 473 474 Expr *OrigArg0 = TheCall->getArg(0); 475 Expr *OrigArg1 = TheCall->getArg(1); 476 477 // Do standard promotions between the two arguments, returning their common 478 // type. 479 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 480 481 // Make sure any conversions are pushed back into the call; this is 482 // type safe since unordered compare builtins are declared as "_Bool 483 // foo(...)". 484 TheCall->setArg(0, OrigArg0); 485 TheCall->setArg(1, OrigArg1); 486 487 // If the common type isn't a real floating type, then the arguments were 488 // invalid for this operation. 489 if (!Res->isRealFloatingType()) 490 return Diag(OrigArg0->getLocStart(), 491 diag::err_typecheck_call_invalid_ordered_compare) 492 << OrigArg0->getType() << OrigArg1->getType() 493 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd()); 494 495 return false; 496} 497 498bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) { 499 // The signature for these builtins is exact; the only thing we need 500 // to check is that the argument is a constant. 501 SourceLocation Loc; 502 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc)) 503 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange(); 504 505 return false; 506} 507 508/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 509// This is declared to take (...), so we have to check everything. 510Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 511 if (TheCall->getNumArgs() < 3) 512 return ExprError(Diag(TheCall->getLocEnd(), 513 diag::err_typecheck_call_too_few_args) 514 << 0 /*function call*/ << TheCall->getSourceRange()); 515 516 QualType FAType = TheCall->getArg(0)->getType(); 517 QualType SAType = TheCall->getArg(1)->getType(); 518 519 if (!FAType->isVectorType() || !SAType->isVectorType()) { 520 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector) 521 << SourceRange(TheCall->getArg(0)->getLocStart(), 522 TheCall->getArg(1)->getLocEnd()); 523 return ExprError(); 524 } 525 526 if (Context.getCanonicalType(FAType).getUnqualifiedType() != 527 Context.getCanonicalType(SAType).getUnqualifiedType()) { 528 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 529 << SourceRange(TheCall->getArg(0)->getLocStart(), 530 TheCall->getArg(1)->getLocEnd()); 531 return ExprError(); 532 } 533 534 unsigned numElements = FAType->getAsVectorType()->getNumElements(); 535 if (TheCall->getNumArgs() != numElements+2) { 536 if (TheCall->getNumArgs() < numElements+2) 537 return ExprError(Diag(TheCall->getLocEnd(), 538 diag::err_typecheck_call_too_few_args) 539 << 0 /*function call*/ << TheCall->getSourceRange()); 540 return ExprError(Diag(TheCall->getLocEnd(), 541 diag::err_typecheck_call_too_many_args) 542 << 0 /*function call*/ << TheCall->getSourceRange()); 543 } 544 545 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 546 llvm::APSInt Result(32); 547 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 548 return ExprError(Diag(TheCall->getLocStart(), 549 diag::err_shufflevector_nonconstant_argument) 550 << TheCall->getArg(i)->getSourceRange()); 551 552 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 553 return ExprError(Diag(TheCall->getLocStart(), 554 diag::err_shufflevector_argument_too_large) 555 << TheCall->getArg(i)->getSourceRange()); 556 } 557 558 llvm::SmallVector<Expr*, 32> exprs; 559 560 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 561 exprs.push_back(TheCall->getArg(i)); 562 TheCall->setArg(i, 0); 563 } 564 565 return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), numElements+2, 566 FAType, 567 TheCall->getCallee()->getLocStart(), 568 TheCall->getRParenLoc())); 569} 570 571/// SemaBuiltinPrefetch - Handle __builtin_prefetch. 572// This is declared to take (const void*, ...) and can take two 573// optional constant int args. 574bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 575 unsigned NumArgs = TheCall->getNumArgs(); 576 577 if (NumArgs > 3) 578 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args) 579 << 0 /*function call*/ << TheCall->getSourceRange(); 580 581 // Argument 0 is checked for us and the remaining arguments must be 582 // constant integers. 583 for (unsigned i = 1; i != NumArgs; ++i) { 584 Expr *Arg = TheCall->getArg(i); 585 QualType RWType = Arg->getType(); 586 587 const BuiltinType *BT = RWType->getAsBuiltinType(); 588 llvm::APSInt Result; 589 if (!BT || BT->getKind() != BuiltinType::Int || 590 !Arg->isIntegerConstantExpr(Result, Context)) 591 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument) 592 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 593 594 // FIXME: gcc issues a warning and rewrites these to 0. These 595 // seems especially odd for the third argument since the default 596 // is 3. 597 if (i == 1) { 598 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1) 599 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 600 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 601 } else { 602 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) 603 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 604 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 605 } 606 } 607 608 return false; 609} 610 611/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, 612/// int type). This simply type checks that type is one of the defined 613/// constants (0-3). 614bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { 615 Expr *Arg = TheCall->getArg(1); 616 QualType ArgType = Arg->getType(); 617 const BuiltinType *BT = ArgType->getAsBuiltinType(); 618 llvm::APSInt Result(32); 619 if (!BT || BT->getKind() != BuiltinType::Int || 620 !Arg->isIntegerConstantExpr(Result, Context)) { 621 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument) 622 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 623 } 624 625 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { 626 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 627 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 628 } 629 630 return false; 631} 632 633/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 634/// This checks that val is a constant 1. 635bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 636 Expr *Arg = TheCall->getArg(1); 637 llvm::APSInt Result(32); 638 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1) 639 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 640 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 641 642 return false; 643} 644 645// Handle i > 1 ? "x" : "y", recursivelly 646bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall, 647 bool HasVAListArg, 648 unsigned format_idx, unsigned firstDataArg) { 649 650 switch (E->getStmtClass()) { 651 case Stmt::ConditionalOperatorClass: { 652 const ConditionalOperator *C = cast<ConditionalOperator>(E); 653 return SemaCheckStringLiteral(C->getLHS(), TheCall, 654 HasVAListArg, format_idx, firstDataArg) 655 && SemaCheckStringLiteral(C->getRHS(), TheCall, 656 HasVAListArg, format_idx, firstDataArg); 657 } 658 659 case Stmt::ImplicitCastExprClass: { 660 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E); 661 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg, 662 format_idx, firstDataArg); 663 } 664 665 case Stmt::ParenExprClass: { 666 const ParenExpr *Expr = cast<ParenExpr>(E); 667 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg, 668 format_idx, firstDataArg); 669 } 670 671 case Stmt::DeclRefExprClass: { 672 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 673 674 // As an exception, do not flag errors for variables binding to 675 // const string literals. 676 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 677 bool isConstant = false; 678 QualType T = DR->getType(); 679 680 if (const ArrayType *AT = Context.getAsArrayType(T)) { 681 isConstant = AT->getElementType().isConstant(Context); 682 } 683 else if (const PointerType *PT = T->getAsPointerType()) { 684 isConstant = T.isConstant(Context) && 685 PT->getPointeeType().isConstant(Context); 686 } 687 688 if (isConstant) { 689 const VarDecl *Def = 0; 690 if (const Expr *Init = VD->getDefinition(Def)) 691 return SemaCheckStringLiteral(Init, TheCall, 692 HasVAListArg, format_idx, firstDataArg); 693 } 694 } 695 696 return false; 697 } 698 699 case Stmt::ObjCStringLiteralClass: 700 case Stmt::StringLiteralClass: { 701 const StringLiteral *StrE = NULL; 702 703 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 704 StrE = ObjCFExpr->getString(); 705 else 706 StrE = cast<StringLiteral>(E); 707 708 if (StrE) { 709 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx, 710 firstDataArg); 711 return true; 712 } 713 714 return false; 715 } 716 717 default: 718 return false; 719 } 720} 721 722 723/// CheckPrintfArguments - Check calls to printf (and similar functions) for 724/// correct use of format strings. 725/// 726/// HasVAListArg - A predicate indicating whether the printf-like 727/// function is passed an explicit va_arg argument (e.g., vprintf) 728/// 729/// format_idx - The index into Args for the format string. 730/// 731/// Improper format strings to functions in the printf family can be 732/// the source of bizarre bugs and very serious security holes. A 733/// good source of information is available in the following paper 734/// (which includes additional references): 735/// 736/// FormatGuard: Automatic Protection From printf Format String 737/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001. 738/// 739/// Functionality implemented: 740/// 741/// We can statically check the following properties for string 742/// literal format strings for non v.*printf functions (where the 743/// arguments are passed directly): 744// 745/// (1) Are the number of format conversions equal to the number of 746/// data arguments? 747/// 748/// (2) Does each format conversion correctly match the type of the 749/// corresponding data argument? (TODO) 750/// 751/// Moreover, for all printf functions we can: 752/// 753/// (3) Check for a missing format string (when not caught by type checking). 754/// 755/// (4) Check for no-operation flags; e.g. using "#" with format 756/// conversion 'c' (TODO) 757/// 758/// (5) Check the use of '%n', a major source of security holes. 759/// 760/// (6) Check for malformed format conversions that don't specify anything. 761/// 762/// (7) Check for empty format strings. e.g: printf(""); 763/// 764/// (8) Check that the format string is a wide literal. 765/// 766/// (9) Also check the arguments of functions with the __format__ attribute. 767/// (TODO). 768/// 769/// All of these checks can be done by parsing the format string. 770/// 771/// For now, we ONLY do (1), (3), (5), (6), (7), and (8). 772void 773Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg, 774 unsigned format_idx, unsigned firstDataArg) { 775 const Expr *Fn = TheCall->getCallee(); 776 777 // CHECK: printf-like function is called with no format string. 778 if (format_idx >= TheCall->getNumArgs()) { 779 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string) 780 << Fn->getSourceRange(); 781 return; 782 } 783 784 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts(); 785 786 // CHECK: format string is not a string literal. 787 // 788 // Dynamically generated format strings are difficult to 789 // automatically vet at compile time. Requiring that format strings 790 // are string literals: (1) permits the checking of format strings by 791 // the compiler and thereby (2) can practically remove the source of 792 // many format string exploits. 793 794 // Format string can be either ObjC string (e.g. @"%d") or 795 // C string (e.g. "%d") 796 // ObjC string uses the same format specifiers as C string, so we can use 797 // the same format string checking logic for both ObjC and C strings. 798 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx, 799 firstDataArg)) 800 return; // Literal format string found, check done! 801 802 // For vprintf* functions (i.e., HasVAListArg==true), we add a 803 // special check to see if the format string is a function parameter 804 // of the function calling the printf function. If the function 805 // has an attribute indicating it is a printf-like function, then we 806 // should suppress warnings concerning non-literals being used in a call 807 // to a vprintf function. For example: 808 // 809 // void 810 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) { 811 // va_list ap; 812 // va_start(ap, fmt); 813 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 814 // ... 815 // 816 // 817 // FIXME: We don't have full attribute support yet, so just check to see 818 // if the argument is a DeclRefExpr that references a parameter. We'll 819 // add proper support for checking the attribute later. 820 if (HasVAListArg) 821 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OrigFormatExpr)) 822 if (isa<ParmVarDecl>(DR->getDecl())) 823 return; 824 825 // If there are no arguments specified, warn with -Wformat-security, otherwise 826 // warn only with -Wformat-nonliteral. 827 if (TheCall->getNumArgs() == format_idx+1) 828 Diag(TheCall->getArg(format_idx)->getLocStart(), 829 diag::warn_printf_nonliteral_noargs) 830 << OrigFormatExpr->getSourceRange(); 831 else 832 Diag(TheCall->getArg(format_idx)->getLocStart(), 833 diag::warn_printf_nonliteral) 834 << OrigFormatExpr->getSourceRange(); 835} 836 837void Sema::CheckPrintfString(const StringLiteral *FExpr, 838 const Expr *OrigFormatExpr, 839 const CallExpr *TheCall, bool HasVAListArg, 840 unsigned format_idx, unsigned firstDataArg) { 841 842 const ObjCStringLiteral *ObjCFExpr = 843 dyn_cast<ObjCStringLiteral>(OrigFormatExpr); 844 845 // CHECK: is the format string a wide literal? 846 if (FExpr->isWide()) { 847 Diag(FExpr->getLocStart(), 848 diag::warn_printf_format_string_is_wide_literal) 849 << OrigFormatExpr->getSourceRange(); 850 return; 851 } 852 853 // Str - The format string. NOTE: this is NOT null-terminated! 854 const char *Str = FExpr->getStrData(); 855 856 // CHECK: empty format string? 857 unsigned StrLen = FExpr->getByteLength(); 858 859 if (StrLen == 0) { 860 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string) 861 << OrigFormatExpr->getSourceRange(); 862 return; 863 } 864 865 // We process the format string using a binary state machine. The 866 // current state is stored in CurrentState. 867 enum { 868 state_OrdChr, 869 state_Conversion 870 } CurrentState = state_OrdChr; 871 872 // numConversions - The number of conversions seen so far. This is 873 // incremented as we traverse the format string. 874 unsigned numConversions = 0; 875 876 // numDataArgs - The number of data arguments after the format 877 // string. This can only be determined for non vprintf-like 878 // functions. For those functions, this value is 1 (the sole 879 // va_arg argument). 880 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg; 881 882 // Inspect the format string. 883 unsigned StrIdx = 0; 884 885 // LastConversionIdx - Index within the format string where we last saw 886 // a '%' character that starts a new format conversion. 887 unsigned LastConversionIdx = 0; 888 889 for (; StrIdx < StrLen; ++StrIdx) { 890 891 // Is the number of detected conversion conversions greater than 892 // the number of matching data arguments? If so, stop. 893 if (!HasVAListArg && numConversions > numDataArgs) break; 894 895 // Handle "\0" 896 if (Str[StrIdx] == '\0') { 897 // The string returned by getStrData() is not null-terminated, 898 // so the presence of a null character is likely an error. 899 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx), 900 diag::warn_printf_format_string_contains_null_char) 901 << OrigFormatExpr->getSourceRange(); 902 return; 903 } 904 905 // Ordinary characters (not processing a format conversion). 906 if (CurrentState == state_OrdChr) { 907 if (Str[StrIdx] == '%') { 908 CurrentState = state_Conversion; 909 LastConversionIdx = StrIdx; 910 } 911 continue; 912 } 913 914 // Seen '%'. Now processing a format conversion. 915 switch (Str[StrIdx]) { 916 // Handle dynamic precision or width specifier. 917 case '*': { 918 ++numConversions; 919 920 if (!HasVAListArg && numConversions > numDataArgs) { 921 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx); 922 923 if (Str[StrIdx-1] == '.') 924 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg) 925 << OrigFormatExpr->getSourceRange(); 926 else 927 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg) 928 << OrigFormatExpr->getSourceRange(); 929 930 // Don't do any more checking. We'll just emit spurious errors. 931 return; 932 } 933 934 // Perform type checking on width/precision specifier. 935 const Expr *E = TheCall->getArg(format_idx+numConversions); 936 if (const BuiltinType *BT = E->getType()->getAsBuiltinType()) 937 if (BT->getKind() == BuiltinType::Int) 938 break; 939 940 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx); 941 942 if (Str[StrIdx-1] == '.') 943 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type) 944 << E->getType() << E->getSourceRange(); 945 else 946 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type) 947 << E->getType() << E->getSourceRange(); 948 949 break; 950 } 951 952 // Characters which can terminate a format conversion 953 // (e.g. "%d"). Characters that specify length modifiers or 954 // other flags are handled by the default case below. 955 // 956 // FIXME: additional checks will go into the following cases. 957 case 'i': 958 case 'd': 959 case 'o': 960 case 'u': 961 case 'x': 962 case 'X': 963 case 'D': 964 case 'O': 965 case 'U': 966 case 'e': 967 case 'E': 968 case 'f': 969 case 'F': 970 case 'g': 971 case 'G': 972 case 'a': 973 case 'A': 974 case 'c': 975 case 'C': 976 case 'S': 977 case 's': 978 case 'p': 979 ++numConversions; 980 CurrentState = state_OrdChr; 981 break; 982 983 // CHECK: Are we using "%n"? Issue a warning. 984 case 'n': { 985 ++numConversions; 986 CurrentState = state_OrdChr; 987 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, 988 LastConversionIdx); 989 990 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange(); 991 break; 992 } 993 994 // Handle "%@" 995 case '@': 996 // %@ is allowed in ObjC format strings only. 997 if(ObjCFExpr != NULL) 998 CurrentState = state_OrdChr; 999 else { 1000 // Issue a warning: invalid format conversion. 1001 SourceLocation Loc = 1002 getLocationOfStringLiteralByte(FExpr, LastConversionIdx); 1003 1004 Diag(Loc, diag::warn_printf_invalid_conversion) 1005 << std::string(Str+LastConversionIdx, 1006 Str+std::min(LastConversionIdx+2, StrLen)) 1007 << OrigFormatExpr->getSourceRange(); 1008 } 1009 ++numConversions; 1010 break; 1011 1012 // Handle "%%" 1013 case '%': 1014 // Sanity check: Was the first "%" character the previous one? 1015 // If not, we will assume that we have a malformed format 1016 // conversion, and that the current "%" character is the start 1017 // of a new conversion. 1018 if (StrIdx - LastConversionIdx == 1) 1019 CurrentState = state_OrdChr; 1020 else { 1021 // Issue a warning: invalid format conversion. 1022 SourceLocation Loc = 1023 getLocationOfStringLiteralByte(FExpr, LastConversionIdx); 1024 1025 Diag(Loc, diag::warn_printf_invalid_conversion) 1026 << std::string(Str+LastConversionIdx, Str+StrIdx) 1027 << OrigFormatExpr->getSourceRange(); 1028 1029 // This conversion is broken. Advance to the next format 1030 // conversion. 1031 LastConversionIdx = StrIdx; 1032 ++numConversions; 1033 } 1034 break; 1035 1036 default: 1037 // This case catches all other characters: flags, widths, etc. 1038 // We should eventually process those as well. 1039 break; 1040 } 1041 } 1042 1043 if (CurrentState == state_Conversion) { 1044 // Issue a warning: invalid format conversion. 1045 SourceLocation Loc = 1046 getLocationOfStringLiteralByte(FExpr, LastConversionIdx); 1047 1048 Diag(Loc, diag::warn_printf_invalid_conversion) 1049 << std::string(Str+LastConversionIdx, 1050 Str+std::min(LastConversionIdx+2, StrLen)) 1051 << OrigFormatExpr->getSourceRange(); 1052 return; 1053 } 1054 1055 if (!HasVAListArg) { 1056 // CHECK: Does the number of format conversions exceed the number 1057 // of data arguments? 1058 if (numConversions > numDataArgs) { 1059 SourceLocation Loc = 1060 getLocationOfStringLiteralByte(FExpr, LastConversionIdx); 1061 1062 Diag(Loc, diag::warn_printf_insufficient_data_args) 1063 << OrigFormatExpr->getSourceRange(); 1064 } 1065 // CHECK: Does the number of data arguments exceed the number of 1066 // format conversions in the format string? 1067 else if (numConversions < numDataArgs) 1068 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(), 1069 diag::warn_printf_too_many_data_args) 1070 << OrigFormatExpr->getSourceRange(); 1071 } 1072} 1073 1074//===--- CHECK: Return Address of Stack Variable --------------------------===// 1075 1076static DeclRefExpr* EvalVal(Expr *E); 1077static DeclRefExpr* EvalAddr(Expr* E); 1078 1079/// CheckReturnStackAddr - Check if a return statement returns the address 1080/// of a stack variable. 1081void 1082Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 1083 SourceLocation ReturnLoc) { 1084 1085 // Perform checking for returned stack addresses. 1086 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) { 1087 if (DeclRefExpr *DR = EvalAddr(RetValExp)) 1088 Diag(DR->getLocStart(), diag::warn_ret_stack_addr) 1089 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange(); 1090 1091 // Skip over implicit cast expressions when checking for block expressions. 1092 if (ImplicitCastExpr *IcExpr = 1093 dyn_cast_or_null<ImplicitCastExpr>(RetValExp)) 1094 RetValExp = IcExpr->getSubExpr(); 1095 1096 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp)) 1097 if (C->hasBlockDeclRefExprs()) 1098 Diag(C->getLocStart(), diag::err_ret_local_block) 1099 << C->getSourceRange(); 1100 } 1101 // Perform checking for stack values returned by reference. 1102 else if (lhsType->isReferenceType()) { 1103 // Check for a reference to the stack 1104 if (DeclRefExpr *DR = EvalVal(RetValExp)) 1105 Diag(DR->getLocStart(), diag::warn_ret_stack_ref) 1106 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange(); 1107 } 1108} 1109 1110/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 1111/// check if the expression in a return statement evaluates to an address 1112/// to a location on the stack. The recursion is used to traverse the 1113/// AST of the return expression, with recursion backtracking when we 1114/// encounter a subexpression that (1) clearly does not lead to the address 1115/// of a stack variable or (2) is something we cannot determine leads to 1116/// the address of a stack variable based on such local checking. 1117/// 1118/// EvalAddr processes expressions that are pointers that are used as 1119/// references (and not L-values). EvalVal handles all other values. 1120/// At the base case of the recursion is a check for a DeclRefExpr* in 1121/// the refers to a stack variable. 1122/// 1123/// This implementation handles: 1124/// 1125/// * pointer-to-pointer casts 1126/// * implicit conversions from array references to pointers 1127/// * taking the address of fields 1128/// * arbitrary interplay between "&" and "*" operators 1129/// * pointer arithmetic from an address of a stack variable 1130/// * taking the address of an array element where the array is on the stack 1131static DeclRefExpr* EvalAddr(Expr *E) { 1132 // We should only be called for evaluating pointer expressions. 1133 assert((E->getType()->isPointerType() || 1134 E->getType()->isBlockPointerType() || 1135 E->getType()->isObjCQualifiedIdType()) && 1136 "EvalAddr only works on pointers"); 1137 1138 // Our "symbolic interpreter" is just a dispatch off the currently 1139 // viewed AST node. We then recursively traverse the AST by calling 1140 // EvalAddr and EvalVal appropriately. 1141 switch (E->getStmtClass()) { 1142 case Stmt::ParenExprClass: 1143 // Ignore parentheses. 1144 return EvalAddr(cast<ParenExpr>(E)->getSubExpr()); 1145 1146 case Stmt::UnaryOperatorClass: { 1147 // The only unary operator that make sense to handle here 1148 // is AddrOf. All others don't make sense as pointers. 1149 UnaryOperator *U = cast<UnaryOperator>(E); 1150 1151 if (U->getOpcode() == UnaryOperator::AddrOf) 1152 return EvalVal(U->getSubExpr()); 1153 else 1154 return NULL; 1155 } 1156 1157 case Stmt::BinaryOperatorClass: { 1158 // Handle pointer arithmetic. All other binary operators are not valid 1159 // in this context. 1160 BinaryOperator *B = cast<BinaryOperator>(E); 1161 BinaryOperator::Opcode op = B->getOpcode(); 1162 1163 if (op != BinaryOperator::Add && op != BinaryOperator::Sub) 1164 return NULL; 1165 1166 Expr *Base = B->getLHS(); 1167 1168 // Determine which argument is the real pointer base. It could be 1169 // the RHS argument instead of the LHS. 1170 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 1171 1172 assert (Base->getType()->isPointerType()); 1173 return EvalAddr(Base); 1174 } 1175 1176 // For conditional operators we need to see if either the LHS or RHS are 1177 // valid DeclRefExpr*s. If one of them is valid, we return it. 1178 case Stmt::ConditionalOperatorClass: { 1179 ConditionalOperator *C = cast<ConditionalOperator>(E); 1180 1181 // Handle the GNU extension for missing LHS. 1182 if (Expr *lhsExpr = C->getLHS()) 1183 if (DeclRefExpr* LHS = EvalAddr(lhsExpr)) 1184 return LHS; 1185 1186 return EvalAddr(C->getRHS()); 1187 } 1188 1189 // For casts, we need to handle conversions from arrays to 1190 // pointer values, and pointer-to-pointer conversions. 1191 case Stmt::ImplicitCastExprClass: 1192 case Stmt::CStyleCastExprClass: 1193 case Stmt::CXXFunctionalCastExprClass: { 1194 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 1195 QualType T = SubExpr->getType(); 1196 1197 if (SubExpr->getType()->isPointerType() || 1198 SubExpr->getType()->isBlockPointerType() || 1199 SubExpr->getType()->isObjCQualifiedIdType()) 1200 return EvalAddr(SubExpr); 1201 else if (T->isArrayType()) 1202 return EvalVal(SubExpr); 1203 else 1204 return 0; 1205 } 1206 1207 // C++ casts. For dynamic casts, static casts, and const casts, we 1208 // are always converting from a pointer-to-pointer, so we just blow 1209 // through the cast. In the case the dynamic cast doesn't fail (and 1210 // return NULL), we take the conservative route and report cases 1211 // where we return the address of a stack variable. For Reinterpre 1212 // FIXME: The comment about is wrong; we're not always converting 1213 // from pointer to pointer. I'm guessing that this code should also 1214 // handle references to objects. 1215 case Stmt::CXXStaticCastExprClass: 1216 case Stmt::CXXDynamicCastExprClass: 1217 case Stmt::CXXConstCastExprClass: 1218 case Stmt::CXXReinterpretCastExprClass: { 1219 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr(); 1220 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType()) 1221 return EvalAddr(S); 1222 else 1223 return NULL; 1224 } 1225 1226 // Everything else: we simply don't reason about them. 1227 default: 1228 return NULL; 1229 } 1230} 1231 1232 1233/// EvalVal - This function is complements EvalAddr in the mutual recursion. 1234/// See the comments for EvalAddr for more details. 1235static DeclRefExpr* EvalVal(Expr *E) { 1236 1237 // We should only be called for evaluating non-pointer expressions, or 1238 // expressions with a pointer type that are not used as references but instead 1239 // are l-values (e.g., DeclRefExpr with a pointer type). 1240 1241 // Our "symbolic interpreter" is just a dispatch off the currently 1242 // viewed AST node. We then recursively traverse the AST by calling 1243 // EvalAddr and EvalVal appropriately. 1244 switch (E->getStmtClass()) { 1245 case Stmt::DeclRefExprClass: 1246 case Stmt::QualifiedDeclRefExprClass: { 1247 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking 1248 // at code that refers to a variable's name. We check if it has local 1249 // storage within the function, and if so, return the expression. 1250 DeclRefExpr *DR = cast<DeclRefExpr>(E); 1251 1252 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 1253 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR; 1254 1255 return NULL; 1256 } 1257 1258 case Stmt::ParenExprClass: 1259 // Ignore parentheses. 1260 return EvalVal(cast<ParenExpr>(E)->getSubExpr()); 1261 1262 case Stmt::UnaryOperatorClass: { 1263 // The only unary operator that make sense to handle here 1264 // is Deref. All others don't resolve to a "name." This includes 1265 // handling all sorts of rvalues passed to a unary operator. 1266 UnaryOperator *U = cast<UnaryOperator>(E); 1267 1268 if (U->getOpcode() == UnaryOperator::Deref) 1269 return EvalAddr(U->getSubExpr()); 1270 1271 return NULL; 1272 } 1273 1274 case Stmt::ArraySubscriptExprClass: { 1275 // Array subscripts are potential references to data on the stack. We 1276 // retrieve the DeclRefExpr* for the array variable if it indeed 1277 // has local storage. 1278 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase()); 1279 } 1280 1281 case Stmt::ConditionalOperatorClass: { 1282 // For conditional operators we need to see if either the LHS or RHS are 1283 // non-NULL DeclRefExpr's. If one is non-NULL, we return it. 1284 ConditionalOperator *C = cast<ConditionalOperator>(E); 1285 1286 // Handle the GNU extension for missing LHS. 1287 if (Expr *lhsExpr = C->getLHS()) 1288 if (DeclRefExpr *LHS = EvalVal(lhsExpr)) 1289 return LHS; 1290 1291 return EvalVal(C->getRHS()); 1292 } 1293 1294 // Accesses to members are potential references to data on the stack. 1295 case Stmt::MemberExprClass: { 1296 MemberExpr *M = cast<MemberExpr>(E); 1297 1298 // Check for indirect access. We only want direct field accesses. 1299 if (!M->isArrow()) 1300 return EvalVal(M->getBase()); 1301 else 1302 return NULL; 1303 } 1304 1305 // Everything else: we simply don't reason about them. 1306 default: 1307 return NULL; 1308 } 1309} 1310 1311//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 1312 1313/// Check for comparisons of floating point operands using != and ==. 1314/// Issue a warning if these are no self-comparisons, as they are not likely 1315/// to do what the programmer intended. 1316void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) { 1317 bool EmitWarning = true; 1318 1319 Expr* LeftExprSansParen = lex->IgnoreParens(); 1320 Expr* RightExprSansParen = rex->IgnoreParens(); 1321 1322 // Special case: check for x == x (which is OK). 1323 // Do not emit warnings for such cases. 1324 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 1325 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 1326 if (DRL->getDecl() == DRR->getDecl()) 1327 EmitWarning = false; 1328 1329 1330 // Special case: check for comparisons against literals that can be exactly 1331 // represented by APFloat. In such cases, do not emit a warning. This 1332 // is a heuristic: often comparison against such literals are used to 1333 // detect if a value in a variable has not changed. This clearly can 1334 // lead to false negatives. 1335 if (EmitWarning) { 1336 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 1337 if (FLL->isExact()) 1338 EmitWarning = false; 1339 } 1340 else 1341 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){ 1342 if (FLR->isExact()) 1343 EmitWarning = false; 1344 } 1345 } 1346 1347 // Check for comparisons with builtin types. 1348 if (EmitWarning) 1349 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 1350 if (CL->isBuiltinCall(Context)) 1351 EmitWarning = false; 1352 1353 if (EmitWarning) 1354 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 1355 if (CR->isBuiltinCall(Context)) 1356 EmitWarning = false; 1357 1358 // Emit the diagnostic. 1359 if (EmitWarning) 1360 Diag(loc, diag::warn_floatingpoint_eq) 1361 << lex->getSourceRange() << rex->getSourceRange(); 1362} 1363