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