SemaChecking.cpp revision be0ee875d8a91c031a085cbbd73ad9e8dc1aa8ff
1//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements extra semantic analysis beyond what is enforced 11// by the C type system. 12// 13//===----------------------------------------------------------------------===// 14 15#include "clang/Sema/Initialization.h" 16#include "clang/Sema/Sema.h" 17#include "clang/Sema/SemaInternal.h" 18#include "clang/Sema/Initialization.h" 19#include "clang/Sema/ScopeInfo.h" 20#include "clang/Analysis/Analyses/FormatString.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/CharUnits.h" 23#include "clang/AST/DeclCXX.h" 24#include "clang/AST/DeclObjC.h" 25#include "clang/AST/Expr.h" 26#include "clang/AST/ExprCXX.h" 27#include "clang/AST/ExprObjC.h" 28#include "clang/AST/EvaluatedExprVisitor.h" 29#include "clang/AST/DeclObjC.h" 30#include "clang/AST/StmtCXX.h" 31#include "clang/AST/StmtObjC.h" 32#include "clang/Lex/Preprocessor.h" 33#include "llvm/ADT/BitVector.h" 34#include "llvm/ADT/SmallString.h" 35#include "llvm/ADT/STLExtras.h" 36#include "llvm/Support/raw_ostream.h" 37#include "clang/Basic/TargetBuiltins.h" 38#include "clang/Basic/TargetInfo.h" 39#include "clang/Basic/ConvertUTF.h" 40#include <limits> 41using namespace clang; 42using namespace sema; 43 44SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 45 unsigned ByteNo) const { 46 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(), 47 PP.getLangOpts(), PP.getTargetInfo()); 48} 49 50/// Checks that a call expression's argument count is the desired number. 51/// This is useful when doing custom type-checking. Returns true on error. 52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 53 unsigned argCount = call->getNumArgs(); 54 if (argCount == desiredArgCount) return false; 55 56 if (argCount < desiredArgCount) 57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 58 << 0 /*function call*/ << desiredArgCount << argCount 59 << call->getSourceRange(); 60 61 // Highlight all the excess arguments. 62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 63 call->getArg(argCount - 1)->getLocEnd()); 64 65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 66 << 0 /*function call*/ << desiredArgCount << argCount 67 << call->getArg(1)->getSourceRange(); 68} 69 70/// Check that the first argument to __builtin_annotation is an integer 71/// and the second argument is a non-wide string literal. 72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 73 if (checkArgCount(S, TheCall, 2)) 74 return true; 75 76 // First argument should be an integer. 77 Expr *ValArg = TheCall->getArg(0); 78 QualType Ty = ValArg->getType(); 79 if (!Ty->isIntegerType()) { 80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 81 << ValArg->getSourceRange(); 82 return true; 83 } 84 85 // Second argument should be a constant string. 86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 88 if (!Literal || !Literal->isAscii()) { 89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 90 << StrArg->getSourceRange(); 91 return true; 92 } 93 94 TheCall->setType(Ty); 95 return false; 96} 97 98ExprResult 99Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 100 ExprResult TheCallResult(Owned(TheCall)); 101 102 // Find out if any arguments are required to be integer constant expressions. 103 unsigned ICEArguments = 0; 104 ASTContext::GetBuiltinTypeError Error; 105 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 106 if (Error != ASTContext::GE_None) 107 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 108 109 // If any arguments are required to be ICE's, check and diagnose. 110 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 111 // Skip arguments not required to be ICE's. 112 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 113 114 llvm::APSInt Result; 115 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 116 return true; 117 ICEArguments &= ~(1 << ArgNo); 118 } 119 120 switch (BuiltinID) { 121 case Builtin::BI__builtin___CFStringMakeConstantString: 122 assert(TheCall->getNumArgs() == 1 && 123 "Wrong # arguments to builtin CFStringMakeConstantString"); 124 if (CheckObjCString(TheCall->getArg(0))) 125 return ExprError(); 126 break; 127 case Builtin::BI__builtin_stdarg_start: 128 case Builtin::BI__builtin_va_start: 129 if (SemaBuiltinVAStart(TheCall)) 130 return ExprError(); 131 break; 132 case Builtin::BI__builtin_isgreater: 133 case Builtin::BI__builtin_isgreaterequal: 134 case Builtin::BI__builtin_isless: 135 case Builtin::BI__builtin_islessequal: 136 case Builtin::BI__builtin_islessgreater: 137 case Builtin::BI__builtin_isunordered: 138 if (SemaBuiltinUnorderedCompare(TheCall)) 139 return ExprError(); 140 break; 141 case Builtin::BI__builtin_fpclassify: 142 if (SemaBuiltinFPClassification(TheCall, 6)) 143 return ExprError(); 144 break; 145 case Builtin::BI__builtin_isfinite: 146 case Builtin::BI__builtin_isinf: 147 case Builtin::BI__builtin_isinf_sign: 148 case Builtin::BI__builtin_isnan: 149 case Builtin::BI__builtin_isnormal: 150 if (SemaBuiltinFPClassification(TheCall, 1)) 151 return ExprError(); 152 break; 153 case Builtin::BI__builtin_shufflevector: 154 return SemaBuiltinShuffleVector(TheCall); 155 // TheCall will be freed by the smart pointer here, but that's fine, since 156 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 157 case Builtin::BI__builtin_prefetch: 158 if (SemaBuiltinPrefetch(TheCall)) 159 return ExprError(); 160 break; 161 case Builtin::BI__builtin_object_size: 162 if (SemaBuiltinObjectSize(TheCall)) 163 return ExprError(); 164 break; 165 case Builtin::BI__builtin_longjmp: 166 if (SemaBuiltinLongjmp(TheCall)) 167 return ExprError(); 168 break; 169 170 case Builtin::BI__builtin_classify_type: 171 if (checkArgCount(*this, TheCall, 1)) return true; 172 TheCall->setType(Context.IntTy); 173 break; 174 case Builtin::BI__builtin_constant_p: 175 if (checkArgCount(*this, TheCall, 1)) return true; 176 TheCall->setType(Context.IntTy); 177 break; 178 case Builtin::BI__sync_fetch_and_add: 179 case Builtin::BI__sync_fetch_and_add_1: 180 case Builtin::BI__sync_fetch_and_add_2: 181 case Builtin::BI__sync_fetch_and_add_4: 182 case Builtin::BI__sync_fetch_and_add_8: 183 case Builtin::BI__sync_fetch_and_add_16: 184 case Builtin::BI__sync_fetch_and_sub: 185 case Builtin::BI__sync_fetch_and_sub_1: 186 case Builtin::BI__sync_fetch_and_sub_2: 187 case Builtin::BI__sync_fetch_and_sub_4: 188 case Builtin::BI__sync_fetch_and_sub_8: 189 case Builtin::BI__sync_fetch_and_sub_16: 190 case Builtin::BI__sync_fetch_and_or: 191 case Builtin::BI__sync_fetch_and_or_1: 192 case Builtin::BI__sync_fetch_and_or_2: 193 case Builtin::BI__sync_fetch_and_or_4: 194 case Builtin::BI__sync_fetch_and_or_8: 195 case Builtin::BI__sync_fetch_and_or_16: 196 case Builtin::BI__sync_fetch_and_and: 197 case Builtin::BI__sync_fetch_and_and_1: 198 case Builtin::BI__sync_fetch_and_and_2: 199 case Builtin::BI__sync_fetch_and_and_4: 200 case Builtin::BI__sync_fetch_and_and_8: 201 case Builtin::BI__sync_fetch_and_and_16: 202 case Builtin::BI__sync_fetch_and_xor: 203 case Builtin::BI__sync_fetch_and_xor_1: 204 case Builtin::BI__sync_fetch_and_xor_2: 205 case Builtin::BI__sync_fetch_and_xor_4: 206 case Builtin::BI__sync_fetch_and_xor_8: 207 case Builtin::BI__sync_fetch_and_xor_16: 208 case Builtin::BI__sync_add_and_fetch: 209 case Builtin::BI__sync_add_and_fetch_1: 210 case Builtin::BI__sync_add_and_fetch_2: 211 case Builtin::BI__sync_add_and_fetch_4: 212 case Builtin::BI__sync_add_and_fetch_8: 213 case Builtin::BI__sync_add_and_fetch_16: 214 case Builtin::BI__sync_sub_and_fetch: 215 case Builtin::BI__sync_sub_and_fetch_1: 216 case Builtin::BI__sync_sub_and_fetch_2: 217 case Builtin::BI__sync_sub_and_fetch_4: 218 case Builtin::BI__sync_sub_and_fetch_8: 219 case Builtin::BI__sync_sub_and_fetch_16: 220 case Builtin::BI__sync_and_and_fetch: 221 case Builtin::BI__sync_and_and_fetch_1: 222 case Builtin::BI__sync_and_and_fetch_2: 223 case Builtin::BI__sync_and_and_fetch_4: 224 case Builtin::BI__sync_and_and_fetch_8: 225 case Builtin::BI__sync_and_and_fetch_16: 226 case Builtin::BI__sync_or_and_fetch: 227 case Builtin::BI__sync_or_and_fetch_1: 228 case Builtin::BI__sync_or_and_fetch_2: 229 case Builtin::BI__sync_or_and_fetch_4: 230 case Builtin::BI__sync_or_and_fetch_8: 231 case Builtin::BI__sync_or_and_fetch_16: 232 case Builtin::BI__sync_xor_and_fetch: 233 case Builtin::BI__sync_xor_and_fetch_1: 234 case Builtin::BI__sync_xor_and_fetch_2: 235 case Builtin::BI__sync_xor_and_fetch_4: 236 case Builtin::BI__sync_xor_and_fetch_8: 237 case Builtin::BI__sync_xor_and_fetch_16: 238 case Builtin::BI__sync_val_compare_and_swap: 239 case Builtin::BI__sync_val_compare_and_swap_1: 240 case Builtin::BI__sync_val_compare_and_swap_2: 241 case Builtin::BI__sync_val_compare_and_swap_4: 242 case Builtin::BI__sync_val_compare_and_swap_8: 243 case Builtin::BI__sync_val_compare_and_swap_16: 244 case Builtin::BI__sync_bool_compare_and_swap: 245 case Builtin::BI__sync_bool_compare_and_swap_1: 246 case Builtin::BI__sync_bool_compare_and_swap_2: 247 case Builtin::BI__sync_bool_compare_and_swap_4: 248 case Builtin::BI__sync_bool_compare_and_swap_8: 249 case Builtin::BI__sync_bool_compare_and_swap_16: 250 case Builtin::BI__sync_lock_test_and_set: 251 case Builtin::BI__sync_lock_test_and_set_1: 252 case Builtin::BI__sync_lock_test_and_set_2: 253 case Builtin::BI__sync_lock_test_and_set_4: 254 case Builtin::BI__sync_lock_test_and_set_8: 255 case Builtin::BI__sync_lock_test_and_set_16: 256 case Builtin::BI__sync_lock_release: 257 case Builtin::BI__sync_lock_release_1: 258 case Builtin::BI__sync_lock_release_2: 259 case Builtin::BI__sync_lock_release_4: 260 case Builtin::BI__sync_lock_release_8: 261 case Builtin::BI__sync_lock_release_16: 262 case Builtin::BI__sync_swap: 263 case Builtin::BI__sync_swap_1: 264 case Builtin::BI__sync_swap_2: 265 case Builtin::BI__sync_swap_4: 266 case Builtin::BI__sync_swap_8: 267 case Builtin::BI__sync_swap_16: 268 return SemaBuiltinAtomicOverloaded(move(TheCallResult)); 269#define BUILTIN(ID, TYPE, ATTRS) 270#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 271 case Builtin::BI##ID: \ 272 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::AO##ID); 273#include "clang/Basic/Builtins.def" 274 case Builtin::BI__builtin_annotation: 275 if (SemaBuiltinAnnotation(*this, TheCall)) 276 return ExprError(); 277 break; 278 } 279 280 // Since the target specific builtins for each arch overlap, only check those 281 // of the arch we are compiling for. 282 if (BuiltinID >= Builtin::FirstTSBuiltin) { 283 switch (Context.getTargetInfo().getTriple().getArch()) { 284 case llvm::Triple::arm: 285 case llvm::Triple::thumb: 286 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 287 return ExprError(); 288 break; 289 default: 290 break; 291 } 292 } 293 294 return move(TheCallResult); 295} 296 297// Get the valid immediate range for the specified NEON type code. 298static unsigned RFT(unsigned t, bool shift = false) { 299 NeonTypeFlags Type(t); 300 int IsQuad = Type.isQuad(); 301 switch (Type.getEltType()) { 302 case NeonTypeFlags::Int8: 303 case NeonTypeFlags::Poly8: 304 return shift ? 7 : (8 << IsQuad) - 1; 305 case NeonTypeFlags::Int16: 306 case NeonTypeFlags::Poly16: 307 return shift ? 15 : (4 << IsQuad) - 1; 308 case NeonTypeFlags::Int32: 309 return shift ? 31 : (2 << IsQuad) - 1; 310 case NeonTypeFlags::Int64: 311 return shift ? 63 : (1 << IsQuad) - 1; 312 case NeonTypeFlags::Float16: 313 assert(!shift && "cannot shift float types!"); 314 return (4 << IsQuad) - 1; 315 case NeonTypeFlags::Float32: 316 assert(!shift && "cannot shift float types!"); 317 return (2 << IsQuad) - 1; 318 } 319 llvm_unreachable("Invalid NeonTypeFlag!"); 320} 321 322/// getNeonEltType - Return the QualType corresponding to the elements of 323/// the vector type specified by the NeonTypeFlags. This is used to check 324/// the pointer arguments for Neon load/store intrinsics. 325static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) { 326 switch (Flags.getEltType()) { 327 case NeonTypeFlags::Int8: 328 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 329 case NeonTypeFlags::Int16: 330 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 331 case NeonTypeFlags::Int32: 332 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 333 case NeonTypeFlags::Int64: 334 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy; 335 case NeonTypeFlags::Poly8: 336 return Context.SignedCharTy; 337 case NeonTypeFlags::Poly16: 338 return Context.ShortTy; 339 case NeonTypeFlags::Float16: 340 return Context.UnsignedShortTy; 341 case NeonTypeFlags::Float32: 342 return Context.FloatTy; 343 } 344 llvm_unreachable("Invalid NeonTypeFlag!"); 345} 346 347bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 348 llvm::APSInt Result; 349 350 unsigned mask = 0; 351 unsigned TV = 0; 352 int PtrArgNum = -1; 353 bool HasConstPtr = false; 354 switch (BuiltinID) { 355#define GET_NEON_OVERLOAD_CHECK 356#include "clang/Basic/arm_neon.inc" 357#undef GET_NEON_OVERLOAD_CHECK 358 } 359 360 // For NEON intrinsics which are overloaded on vector element type, validate 361 // the immediate which specifies which variant to emit. 362 unsigned ImmArg = TheCall->getNumArgs()-1; 363 if (mask) { 364 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 365 return true; 366 367 TV = Result.getLimitedValue(64); 368 if ((TV > 63) || (mask & (1 << TV)) == 0) 369 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 370 << TheCall->getArg(ImmArg)->getSourceRange(); 371 } 372 373 if (PtrArgNum >= 0) { 374 // Check that pointer arguments have the specified type. 375 Expr *Arg = TheCall->getArg(PtrArgNum); 376 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 377 Arg = ICE->getSubExpr(); 378 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 379 QualType RHSTy = RHS.get()->getType(); 380 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context); 381 if (HasConstPtr) 382 EltTy = EltTy.withConst(); 383 QualType LHSTy = Context.getPointerType(EltTy); 384 AssignConvertType ConvTy; 385 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 386 if (RHS.isInvalid()) 387 return true; 388 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 389 RHS.get(), AA_Assigning)) 390 return true; 391 } 392 393 // For NEON intrinsics which take an immediate value as part of the 394 // instruction, range check them here. 395 unsigned i = 0, l = 0, u = 0; 396 switch (BuiltinID) { 397 default: return false; 398 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 399 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 400 case ARM::BI__builtin_arm_vcvtr_f: 401 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 402#define GET_NEON_IMMEDIATE_CHECK 403#include "clang/Basic/arm_neon.inc" 404#undef GET_NEON_IMMEDIATE_CHECK 405 }; 406 407 // Check that the immediate argument is actually a constant. 408 if (SemaBuiltinConstantArg(TheCall, i, Result)) 409 return true; 410 411 // Range check against the upper/lower values for this isntruction. 412 unsigned Val = Result.getZExtValue(); 413 if (Val < l || Val > (u + l)) 414 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 415 << l << u+l << TheCall->getArg(i)->getSourceRange(); 416 417 // FIXME: VFP Intrinsics should error if VFP not present. 418 return false; 419} 420 421/// CheckFunctionCall - Check a direct function call for various correctness 422/// and safety properties not strictly enforced by the C type system. 423bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) { 424 // Get the IdentifierInfo* for the called function. 425 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 426 427 // None of the checks below are needed for functions that don't have 428 // simple names (e.g., C++ conversion functions). 429 if (!FnInfo) 430 return false; 431 432 // FIXME: This mechanism should be abstracted to be less fragile and 433 // more efficient. For example, just map function ids to custom 434 // handlers. 435 436 // Printf and scanf checking. 437 for (specific_attr_iterator<FormatAttr> 438 i = FDecl->specific_attr_begin<FormatAttr>(), 439 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) { 440 CheckFormatArguments(*i, TheCall); 441 } 442 443 for (specific_attr_iterator<NonNullAttr> 444 i = FDecl->specific_attr_begin<NonNullAttr>(), 445 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) { 446 CheckNonNullArguments(*i, TheCall->getArgs(), 447 TheCall->getCallee()->getLocStart()); 448 } 449 450 unsigned CMId = FDecl->getMemoryFunctionKind(); 451 if (CMId == 0) 452 return false; 453 454 // Handle memory setting and copying functions. 455 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 456 CheckStrlcpycatArguments(TheCall, FnInfo); 457 else if (CMId == Builtin::BIstrncat) 458 CheckStrncatArguments(TheCall, FnInfo); 459 else 460 CheckMemaccessArguments(TheCall, CMId, FnInfo); 461 462 return false; 463} 464 465bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 466 Expr **Args, unsigned NumArgs) { 467 for (specific_attr_iterator<FormatAttr> 468 i = Method->specific_attr_begin<FormatAttr>(), 469 e = Method->specific_attr_end<FormatAttr>(); i != e ; ++i) { 470 471 CheckFormatArguments(*i, Args, NumArgs, false, lbrac, 472 Method->getSourceRange()); 473 } 474 475 // diagnose nonnull arguments. 476 for (specific_attr_iterator<NonNullAttr> 477 i = Method->specific_attr_begin<NonNullAttr>(), 478 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) { 479 CheckNonNullArguments(*i, Args, lbrac); 480 } 481 482 return false; 483} 484 485bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) { 486 const VarDecl *V = dyn_cast<VarDecl>(NDecl); 487 if (!V) 488 return false; 489 490 QualType Ty = V->getType(); 491 if (!Ty->isBlockPointerType()) 492 return false; 493 494 // format string checking. 495 for (specific_attr_iterator<FormatAttr> 496 i = NDecl->specific_attr_begin<FormatAttr>(), 497 e = NDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) { 498 CheckFormatArguments(*i, TheCall); 499 } 500 501 return false; 502} 503 504ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 505 AtomicExpr::AtomicOp Op) { 506 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 507 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 508 509 // All these operations take one of the following forms: 510 enum { 511 // C __c11_atomic_init(A *, C) 512 Init, 513 // C __c11_atomic_load(A *, int) 514 Load, 515 // void __atomic_load(A *, CP, int) 516 Copy, 517 // C __c11_atomic_add(A *, M, int) 518 Arithmetic, 519 // C __atomic_exchange_n(A *, CP, int) 520 Xchg, 521 // void __atomic_exchange(A *, C *, CP, int) 522 GNUXchg, 523 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 524 C11CmpXchg, 525 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 526 GNUCmpXchg 527 } Form = Init; 528 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 }; 529 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 }; 530 // where: 531 // C is an appropriate type, 532 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 533 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 534 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 535 // the int parameters are for orderings. 536 537 assert(AtomicExpr::AO__c11_atomic_init == 0 && 538 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load 539 && "need to update code for modified C11 atomics"); 540 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init && 541 Op <= AtomicExpr::AO__c11_atomic_fetch_xor; 542 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 543 Op == AtomicExpr::AO__atomic_store_n || 544 Op == AtomicExpr::AO__atomic_exchange_n || 545 Op == AtomicExpr::AO__atomic_compare_exchange_n; 546 bool IsAddSub = false; 547 548 switch (Op) { 549 case AtomicExpr::AO__c11_atomic_init: 550 Form = Init; 551 break; 552 553 case AtomicExpr::AO__c11_atomic_load: 554 case AtomicExpr::AO__atomic_load_n: 555 Form = Load; 556 break; 557 558 case AtomicExpr::AO__c11_atomic_store: 559 case AtomicExpr::AO__atomic_load: 560 case AtomicExpr::AO__atomic_store: 561 case AtomicExpr::AO__atomic_store_n: 562 Form = Copy; 563 break; 564 565 case AtomicExpr::AO__c11_atomic_fetch_add: 566 case AtomicExpr::AO__c11_atomic_fetch_sub: 567 case AtomicExpr::AO__atomic_fetch_add: 568 case AtomicExpr::AO__atomic_fetch_sub: 569 case AtomicExpr::AO__atomic_add_fetch: 570 case AtomicExpr::AO__atomic_sub_fetch: 571 IsAddSub = true; 572 // Fall through. 573 case AtomicExpr::AO__c11_atomic_fetch_and: 574 case AtomicExpr::AO__c11_atomic_fetch_or: 575 case AtomicExpr::AO__c11_atomic_fetch_xor: 576 case AtomicExpr::AO__atomic_fetch_and: 577 case AtomicExpr::AO__atomic_fetch_or: 578 case AtomicExpr::AO__atomic_fetch_xor: 579 case AtomicExpr::AO__atomic_fetch_nand: 580 case AtomicExpr::AO__atomic_and_fetch: 581 case AtomicExpr::AO__atomic_or_fetch: 582 case AtomicExpr::AO__atomic_xor_fetch: 583 case AtomicExpr::AO__atomic_nand_fetch: 584 Form = Arithmetic; 585 break; 586 587 case AtomicExpr::AO__c11_atomic_exchange: 588 case AtomicExpr::AO__atomic_exchange_n: 589 Form = Xchg; 590 break; 591 592 case AtomicExpr::AO__atomic_exchange: 593 Form = GNUXchg; 594 break; 595 596 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 597 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 598 Form = C11CmpXchg; 599 break; 600 601 case AtomicExpr::AO__atomic_compare_exchange: 602 case AtomicExpr::AO__atomic_compare_exchange_n: 603 Form = GNUCmpXchg; 604 break; 605 } 606 607 // Check we have the right number of arguments. 608 if (TheCall->getNumArgs() < NumArgs[Form]) { 609 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 610 << 0 << NumArgs[Form] << TheCall->getNumArgs() 611 << TheCall->getCallee()->getSourceRange(); 612 return ExprError(); 613 } else if (TheCall->getNumArgs() > NumArgs[Form]) { 614 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(), 615 diag::err_typecheck_call_too_many_args) 616 << 0 << NumArgs[Form] << TheCall->getNumArgs() 617 << TheCall->getCallee()->getSourceRange(); 618 return ExprError(); 619 } 620 621 // Inspect the first argument of the atomic operation. 622 Expr *Ptr = TheCall->getArg(0); 623 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get(); 624 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 625 if (!pointerType) { 626 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 627 << Ptr->getType() << Ptr->getSourceRange(); 628 return ExprError(); 629 } 630 631 // For a __c11 builtin, this should be a pointer to an _Atomic type. 632 QualType AtomTy = pointerType->getPointeeType(); // 'A' 633 QualType ValType = AtomTy; // 'C' 634 if (IsC11) { 635 if (!AtomTy->isAtomicType()) { 636 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 637 << Ptr->getType() << Ptr->getSourceRange(); 638 return ExprError(); 639 } 640 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 641 } 642 643 // For an arithmetic operation, the implied arithmetic must be well-formed. 644 if (Form == Arithmetic) { 645 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 646 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 647 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 648 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 649 return ExprError(); 650 } 651 if (!IsAddSub && !ValType->isIntegerType()) { 652 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 653 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 654 return ExprError(); 655 } 656 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 657 // For __atomic_*_n operations, the value type must be a scalar integral or 658 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 659 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 660 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 661 return ExprError(); 662 } 663 664 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) { 665 // For GNU atomics, require a trivially-copyable type. This is not part of 666 // the GNU atomics specification, but we enforce it for sanity. 667 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 668 << Ptr->getType() << Ptr->getSourceRange(); 669 return ExprError(); 670 } 671 672 // FIXME: For any builtin other than a load, the ValType must not be 673 // const-qualified. 674 675 switch (ValType.getObjCLifetime()) { 676 case Qualifiers::OCL_None: 677 case Qualifiers::OCL_ExplicitNone: 678 // okay 679 break; 680 681 case Qualifiers::OCL_Weak: 682 case Qualifiers::OCL_Strong: 683 case Qualifiers::OCL_Autoreleasing: 684 // FIXME: Can this happen? By this point, ValType should be known 685 // to be trivially copyable. 686 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 687 << ValType << Ptr->getSourceRange(); 688 return ExprError(); 689 } 690 691 QualType ResultType = ValType; 692 if (Form == Copy || Form == GNUXchg || Form == Init) 693 ResultType = Context.VoidTy; 694 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 695 ResultType = Context.BoolTy; 696 697 // The type of a parameter passed 'by value'. In the GNU atomics, such 698 // arguments are actually passed as pointers. 699 QualType ByValType = ValType; // 'CP' 700 if (!IsC11 && !IsN) 701 ByValType = Ptr->getType(); 702 703 // The first argument --- the pointer --- has a fixed type; we 704 // deduce the types of the rest of the arguments accordingly. Walk 705 // the remaining arguments, converting them to the deduced value type. 706 for (unsigned i = 1; i != NumArgs[Form]; ++i) { 707 QualType Ty; 708 if (i < NumVals[Form] + 1) { 709 switch (i) { 710 case 1: 711 // The second argument is the non-atomic operand. For arithmetic, this 712 // is always passed by value, and for a compare_exchange it is always 713 // passed by address. For the rest, GNU uses by-address and C11 uses 714 // by-value. 715 assert(Form != Load); 716 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 717 Ty = ValType; 718 else if (Form == Copy || Form == Xchg) 719 Ty = ByValType; 720 else if (Form == Arithmetic) 721 Ty = Context.getPointerDiffType(); 722 else 723 Ty = Context.getPointerType(ValType.getUnqualifiedType()); 724 break; 725 case 2: 726 // The third argument to compare_exchange / GNU exchange is a 727 // (pointer to a) desired value. 728 Ty = ByValType; 729 break; 730 case 3: 731 // The fourth argument to GNU compare_exchange is a 'weak' flag. 732 Ty = Context.BoolTy; 733 break; 734 } 735 } else { 736 // The order(s) are always converted to int. 737 Ty = Context.IntTy; 738 } 739 740 InitializedEntity Entity = 741 InitializedEntity::InitializeParameter(Context, Ty, false); 742 ExprResult Arg = TheCall->getArg(i); 743 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 744 if (Arg.isInvalid()) 745 return true; 746 TheCall->setArg(i, Arg.get()); 747 } 748 749 // Permute the arguments into a 'consistent' order. 750 SmallVector<Expr*, 5> SubExprs; 751 SubExprs.push_back(Ptr); 752 switch (Form) { 753 case Init: 754 // Note, AtomicExpr::getVal1() has a special case for this atomic. 755 SubExprs.push_back(TheCall->getArg(1)); // Val1 756 break; 757 case Load: 758 SubExprs.push_back(TheCall->getArg(1)); // Order 759 break; 760 case Copy: 761 case Arithmetic: 762 case Xchg: 763 SubExprs.push_back(TheCall->getArg(2)); // Order 764 SubExprs.push_back(TheCall->getArg(1)); // Val1 765 break; 766 case GNUXchg: 767 // Note, AtomicExpr::getVal2() has a special case for this atomic. 768 SubExprs.push_back(TheCall->getArg(3)); // Order 769 SubExprs.push_back(TheCall->getArg(1)); // Val1 770 SubExprs.push_back(TheCall->getArg(2)); // Val2 771 break; 772 case C11CmpXchg: 773 SubExprs.push_back(TheCall->getArg(3)); // Order 774 SubExprs.push_back(TheCall->getArg(1)); // Val1 775 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 776 SubExprs.push_back(TheCall->getArg(2)); // Val2 777 break; 778 case GNUCmpXchg: 779 SubExprs.push_back(TheCall->getArg(4)); // Order 780 SubExprs.push_back(TheCall->getArg(1)); // Val1 781 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 782 SubExprs.push_back(TheCall->getArg(2)); // Val2 783 SubExprs.push_back(TheCall->getArg(3)); // Weak 784 break; 785 } 786 787 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 788 SubExprs.data(), SubExprs.size(), 789 ResultType, Op, 790 TheCall->getRParenLoc())); 791} 792 793 794/// checkBuiltinArgument - Given a call to a builtin function, perform 795/// normal type-checking on the given argument, updating the call in 796/// place. This is useful when a builtin function requires custom 797/// type-checking for some of its arguments but not necessarily all of 798/// them. 799/// 800/// Returns true on error. 801static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 802 FunctionDecl *Fn = E->getDirectCallee(); 803 assert(Fn && "builtin call without direct callee!"); 804 805 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 806 InitializedEntity Entity = 807 InitializedEntity::InitializeParameter(S.Context, Param); 808 809 ExprResult Arg = E->getArg(0); 810 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 811 if (Arg.isInvalid()) 812 return true; 813 814 E->setArg(ArgIndex, Arg.take()); 815 return false; 816} 817 818/// SemaBuiltinAtomicOverloaded - We have a call to a function like 819/// __sync_fetch_and_add, which is an overloaded function based on the pointer 820/// type of its first argument. The main ActOnCallExpr routines have already 821/// promoted the types of arguments because all of these calls are prototyped as 822/// void(...). 823/// 824/// This function goes through and does final semantic checking for these 825/// builtins, 826ExprResult 827Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 828 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 829 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 830 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 831 832 // Ensure that we have at least one argument to do type inference from. 833 if (TheCall->getNumArgs() < 1) { 834 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 835 << 0 << 1 << TheCall->getNumArgs() 836 << TheCall->getCallee()->getSourceRange(); 837 return ExprError(); 838 } 839 840 // Inspect the first argument of the atomic builtin. This should always be 841 // a pointer type, whose element is an integral scalar or pointer type. 842 // Because it is a pointer type, we don't have to worry about any implicit 843 // casts here. 844 // FIXME: We don't allow floating point scalars as input. 845 Expr *FirstArg = TheCall->getArg(0); 846 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 847 if (FirstArgResult.isInvalid()) 848 return ExprError(); 849 FirstArg = FirstArgResult.take(); 850 TheCall->setArg(0, FirstArg); 851 852 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 853 if (!pointerType) { 854 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 855 << FirstArg->getType() << FirstArg->getSourceRange(); 856 return ExprError(); 857 } 858 859 QualType ValType = pointerType->getPointeeType(); 860 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 861 !ValType->isBlockPointerType()) { 862 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 863 << FirstArg->getType() << FirstArg->getSourceRange(); 864 return ExprError(); 865 } 866 867 switch (ValType.getObjCLifetime()) { 868 case Qualifiers::OCL_None: 869 case Qualifiers::OCL_ExplicitNone: 870 // okay 871 break; 872 873 case Qualifiers::OCL_Weak: 874 case Qualifiers::OCL_Strong: 875 case Qualifiers::OCL_Autoreleasing: 876 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 877 << ValType << FirstArg->getSourceRange(); 878 return ExprError(); 879 } 880 881 // Strip any qualifiers off ValType. 882 ValType = ValType.getUnqualifiedType(); 883 884 // The majority of builtins return a value, but a few have special return 885 // types, so allow them to override appropriately below. 886 QualType ResultType = ValType; 887 888 // We need to figure out which concrete builtin this maps onto. For example, 889 // __sync_fetch_and_add with a 2 byte object turns into 890 // __sync_fetch_and_add_2. 891#define BUILTIN_ROW(x) \ 892 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 893 Builtin::BI##x##_8, Builtin::BI##x##_16 } 894 895 static const unsigned BuiltinIndices[][5] = { 896 BUILTIN_ROW(__sync_fetch_and_add), 897 BUILTIN_ROW(__sync_fetch_and_sub), 898 BUILTIN_ROW(__sync_fetch_and_or), 899 BUILTIN_ROW(__sync_fetch_and_and), 900 BUILTIN_ROW(__sync_fetch_and_xor), 901 902 BUILTIN_ROW(__sync_add_and_fetch), 903 BUILTIN_ROW(__sync_sub_and_fetch), 904 BUILTIN_ROW(__sync_and_and_fetch), 905 BUILTIN_ROW(__sync_or_and_fetch), 906 BUILTIN_ROW(__sync_xor_and_fetch), 907 908 BUILTIN_ROW(__sync_val_compare_and_swap), 909 BUILTIN_ROW(__sync_bool_compare_and_swap), 910 BUILTIN_ROW(__sync_lock_test_and_set), 911 BUILTIN_ROW(__sync_lock_release), 912 BUILTIN_ROW(__sync_swap) 913 }; 914#undef BUILTIN_ROW 915 916 // Determine the index of the size. 917 unsigned SizeIndex; 918 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 919 case 1: SizeIndex = 0; break; 920 case 2: SizeIndex = 1; break; 921 case 4: SizeIndex = 2; break; 922 case 8: SizeIndex = 3; break; 923 case 16: SizeIndex = 4; break; 924 default: 925 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 926 << FirstArg->getType() << FirstArg->getSourceRange(); 927 return ExprError(); 928 } 929 930 // Each of these builtins has one pointer argument, followed by some number of 931 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 932 // that we ignore. Find out which row of BuiltinIndices to read from as well 933 // as the number of fixed args. 934 unsigned BuiltinID = FDecl->getBuiltinID(); 935 unsigned BuiltinIndex, NumFixed = 1; 936 switch (BuiltinID) { 937 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 938 case Builtin::BI__sync_fetch_and_add: 939 case Builtin::BI__sync_fetch_and_add_1: 940 case Builtin::BI__sync_fetch_and_add_2: 941 case Builtin::BI__sync_fetch_and_add_4: 942 case Builtin::BI__sync_fetch_and_add_8: 943 case Builtin::BI__sync_fetch_and_add_16: 944 BuiltinIndex = 0; 945 break; 946 947 case Builtin::BI__sync_fetch_and_sub: 948 case Builtin::BI__sync_fetch_and_sub_1: 949 case Builtin::BI__sync_fetch_and_sub_2: 950 case Builtin::BI__sync_fetch_and_sub_4: 951 case Builtin::BI__sync_fetch_and_sub_8: 952 case Builtin::BI__sync_fetch_and_sub_16: 953 BuiltinIndex = 1; 954 break; 955 956 case Builtin::BI__sync_fetch_and_or: 957 case Builtin::BI__sync_fetch_and_or_1: 958 case Builtin::BI__sync_fetch_and_or_2: 959 case Builtin::BI__sync_fetch_and_or_4: 960 case Builtin::BI__sync_fetch_and_or_8: 961 case Builtin::BI__sync_fetch_and_or_16: 962 BuiltinIndex = 2; 963 break; 964 965 case Builtin::BI__sync_fetch_and_and: 966 case Builtin::BI__sync_fetch_and_and_1: 967 case Builtin::BI__sync_fetch_and_and_2: 968 case Builtin::BI__sync_fetch_and_and_4: 969 case Builtin::BI__sync_fetch_and_and_8: 970 case Builtin::BI__sync_fetch_and_and_16: 971 BuiltinIndex = 3; 972 break; 973 974 case Builtin::BI__sync_fetch_and_xor: 975 case Builtin::BI__sync_fetch_and_xor_1: 976 case Builtin::BI__sync_fetch_and_xor_2: 977 case Builtin::BI__sync_fetch_and_xor_4: 978 case Builtin::BI__sync_fetch_and_xor_8: 979 case Builtin::BI__sync_fetch_and_xor_16: 980 BuiltinIndex = 4; 981 break; 982 983 case Builtin::BI__sync_add_and_fetch: 984 case Builtin::BI__sync_add_and_fetch_1: 985 case Builtin::BI__sync_add_and_fetch_2: 986 case Builtin::BI__sync_add_and_fetch_4: 987 case Builtin::BI__sync_add_and_fetch_8: 988 case Builtin::BI__sync_add_and_fetch_16: 989 BuiltinIndex = 5; 990 break; 991 992 case Builtin::BI__sync_sub_and_fetch: 993 case Builtin::BI__sync_sub_and_fetch_1: 994 case Builtin::BI__sync_sub_and_fetch_2: 995 case Builtin::BI__sync_sub_and_fetch_4: 996 case Builtin::BI__sync_sub_and_fetch_8: 997 case Builtin::BI__sync_sub_and_fetch_16: 998 BuiltinIndex = 6; 999 break; 1000 1001 case Builtin::BI__sync_and_and_fetch: 1002 case Builtin::BI__sync_and_and_fetch_1: 1003 case Builtin::BI__sync_and_and_fetch_2: 1004 case Builtin::BI__sync_and_and_fetch_4: 1005 case Builtin::BI__sync_and_and_fetch_8: 1006 case Builtin::BI__sync_and_and_fetch_16: 1007 BuiltinIndex = 7; 1008 break; 1009 1010 case Builtin::BI__sync_or_and_fetch: 1011 case Builtin::BI__sync_or_and_fetch_1: 1012 case Builtin::BI__sync_or_and_fetch_2: 1013 case Builtin::BI__sync_or_and_fetch_4: 1014 case Builtin::BI__sync_or_and_fetch_8: 1015 case Builtin::BI__sync_or_and_fetch_16: 1016 BuiltinIndex = 8; 1017 break; 1018 1019 case Builtin::BI__sync_xor_and_fetch: 1020 case Builtin::BI__sync_xor_and_fetch_1: 1021 case Builtin::BI__sync_xor_and_fetch_2: 1022 case Builtin::BI__sync_xor_and_fetch_4: 1023 case Builtin::BI__sync_xor_and_fetch_8: 1024 case Builtin::BI__sync_xor_and_fetch_16: 1025 BuiltinIndex = 9; 1026 break; 1027 1028 case Builtin::BI__sync_val_compare_and_swap: 1029 case Builtin::BI__sync_val_compare_and_swap_1: 1030 case Builtin::BI__sync_val_compare_and_swap_2: 1031 case Builtin::BI__sync_val_compare_and_swap_4: 1032 case Builtin::BI__sync_val_compare_and_swap_8: 1033 case Builtin::BI__sync_val_compare_and_swap_16: 1034 BuiltinIndex = 10; 1035 NumFixed = 2; 1036 break; 1037 1038 case Builtin::BI__sync_bool_compare_and_swap: 1039 case Builtin::BI__sync_bool_compare_and_swap_1: 1040 case Builtin::BI__sync_bool_compare_and_swap_2: 1041 case Builtin::BI__sync_bool_compare_and_swap_4: 1042 case Builtin::BI__sync_bool_compare_and_swap_8: 1043 case Builtin::BI__sync_bool_compare_and_swap_16: 1044 BuiltinIndex = 11; 1045 NumFixed = 2; 1046 ResultType = Context.BoolTy; 1047 break; 1048 1049 case Builtin::BI__sync_lock_test_and_set: 1050 case Builtin::BI__sync_lock_test_and_set_1: 1051 case Builtin::BI__sync_lock_test_and_set_2: 1052 case Builtin::BI__sync_lock_test_and_set_4: 1053 case Builtin::BI__sync_lock_test_and_set_8: 1054 case Builtin::BI__sync_lock_test_and_set_16: 1055 BuiltinIndex = 12; 1056 break; 1057 1058 case Builtin::BI__sync_lock_release: 1059 case Builtin::BI__sync_lock_release_1: 1060 case Builtin::BI__sync_lock_release_2: 1061 case Builtin::BI__sync_lock_release_4: 1062 case Builtin::BI__sync_lock_release_8: 1063 case Builtin::BI__sync_lock_release_16: 1064 BuiltinIndex = 13; 1065 NumFixed = 0; 1066 ResultType = Context.VoidTy; 1067 break; 1068 1069 case Builtin::BI__sync_swap: 1070 case Builtin::BI__sync_swap_1: 1071 case Builtin::BI__sync_swap_2: 1072 case Builtin::BI__sync_swap_4: 1073 case Builtin::BI__sync_swap_8: 1074 case Builtin::BI__sync_swap_16: 1075 BuiltinIndex = 14; 1076 break; 1077 } 1078 1079 // Now that we know how many fixed arguments we expect, first check that we 1080 // have at least that many. 1081 if (TheCall->getNumArgs() < 1+NumFixed) { 1082 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 1083 << 0 << 1+NumFixed << TheCall->getNumArgs() 1084 << TheCall->getCallee()->getSourceRange(); 1085 return ExprError(); 1086 } 1087 1088 // Get the decl for the concrete builtin from this, we can tell what the 1089 // concrete integer type we should convert to is. 1090 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 1091 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID); 1092 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName); 1093 FunctionDecl *NewBuiltinDecl = 1094 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID, 1095 TUScope, false, DRE->getLocStart())); 1096 1097 // The first argument --- the pointer --- has a fixed type; we 1098 // deduce the types of the rest of the arguments accordingly. Walk 1099 // the remaining arguments, converting them to the deduced value type. 1100 for (unsigned i = 0; i != NumFixed; ++i) { 1101 ExprResult Arg = TheCall->getArg(i+1); 1102 1103 // GCC does an implicit conversion to the pointer or integer ValType. This 1104 // can fail in some cases (1i -> int**), check for this error case now. 1105 // Initialize the argument. 1106 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 1107 ValType, /*consume*/ false); 1108 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 1109 if (Arg.isInvalid()) 1110 return ExprError(); 1111 1112 // Okay, we have something that *can* be converted to the right type. Check 1113 // to see if there is a potentially weird extension going on here. This can 1114 // happen when you do an atomic operation on something like an char* and 1115 // pass in 42. The 42 gets converted to char. This is even more strange 1116 // for things like 45.123 -> char, etc. 1117 // FIXME: Do this check. 1118 TheCall->setArg(i+1, Arg.take()); 1119 } 1120 1121 ASTContext& Context = this->getASTContext(); 1122 1123 // Create a new DeclRefExpr to refer to the new decl. 1124 DeclRefExpr* NewDRE = DeclRefExpr::Create( 1125 Context, 1126 DRE->getQualifierLoc(), 1127 SourceLocation(), 1128 NewBuiltinDecl, 1129 /*enclosing*/ false, 1130 DRE->getLocation(), 1131 NewBuiltinDecl->getType(), 1132 DRE->getValueKind()); 1133 1134 // Set the callee in the CallExpr. 1135 // FIXME: This leaks the original parens and implicit casts. 1136 ExprResult PromotedCall = UsualUnaryConversions(NewDRE); 1137 if (PromotedCall.isInvalid()) 1138 return ExprError(); 1139 TheCall->setCallee(PromotedCall.take()); 1140 1141 // Change the result type of the call to match the original value type. This 1142 // is arbitrary, but the codegen for these builtins ins design to handle it 1143 // gracefully. 1144 TheCall->setType(ResultType); 1145 1146 return move(TheCallResult); 1147} 1148 1149/// CheckObjCString - Checks that the argument to the builtin 1150/// CFString constructor is correct 1151/// Note: It might also make sense to do the UTF-16 conversion here (would 1152/// simplify the backend). 1153bool Sema::CheckObjCString(Expr *Arg) { 1154 Arg = Arg->IgnoreParenCasts(); 1155 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 1156 1157 if (!Literal || !Literal->isAscii()) { 1158 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 1159 << Arg->getSourceRange(); 1160 return true; 1161 } 1162 1163 if (Literal->containsNonAsciiOrNull()) { 1164 StringRef String = Literal->getString(); 1165 unsigned NumBytes = String.size(); 1166 SmallVector<UTF16, 128> ToBuf(NumBytes); 1167 const UTF8 *FromPtr = (UTF8 *)String.data(); 1168 UTF16 *ToPtr = &ToBuf[0]; 1169 1170 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1171 &ToPtr, ToPtr + NumBytes, 1172 strictConversion); 1173 // Check for conversion failure. 1174 if (Result != conversionOK) 1175 Diag(Arg->getLocStart(), 1176 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 1177 } 1178 return false; 1179} 1180 1181/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 1182/// Emit an error and return true on failure, return false on success. 1183bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 1184 Expr *Fn = TheCall->getCallee(); 1185 if (TheCall->getNumArgs() > 2) { 1186 Diag(TheCall->getArg(2)->getLocStart(), 1187 diag::err_typecheck_call_too_many_args) 1188 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1189 << Fn->getSourceRange() 1190 << SourceRange(TheCall->getArg(2)->getLocStart(), 1191 (*(TheCall->arg_end()-1))->getLocEnd()); 1192 return true; 1193 } 1194 1195 if (TheCall->getNumArgs() < 2) { 1196 return Diag(TheCall->getLocEnd(), 1197 diag::err_typecheck_call_too_few_args_at_least) 1198 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 1199 } 1200 1201 // Type-check the first argument normally. 1202 if (checkBuiltinArgument(*this, TheCall, 0)) 1203 return true; 1204 1205 // Determine whether the current function is variadic or not. 1206 BlockScopeInfo *CurBlock = getCurBlock(); 1207 bool isVariadic; 1208 if (CurBlock) 1209 isVariadic = CurBlock->TheDecl->isVariadic(); 1210 else if (FunctionDecl *FD = getCurFunctionDecl()) 1211 isVariadic = FD->isVariadic(); 1212 else 1213 isVariadic = getCurMethodDecl()->isVariadic(); 1214 1215 if (!isVariadic) { 1216 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 1217 return true; 1218 } 1219 1220 // Verify that the second argument to the builtin is the last argument of the 1221 // current function or method. 1222 bool SecondArgIsLastNamedArgument = false; 1223 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 1224 1225 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 1226 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 1227 // FIXME: This isn't correct for methods (results in bogus warning). 1228 // Get the last formal in the current function. 1229 const ParmVarDecl *LastArg; 1230 if (CurBlock) 1231 LastArg = *(CurBlock->TheDecl->param_end()-1); 1232 else if (FunctionDecl *FD = getCurFunctionDecl()) 1233 LastArg = *(FD->param_end()-1); 1234 else 1235 LastArg = *(getCurMethodDecl()->param_end()-1); 1236 SecondArgIsLastNamedArgument = PV == LastArg; 1237 } 1238 } 1239 1240 if (!SecondArgIsLastNamedArgument) 1241 Diag(TheCall->getArg(1)->getLocStart(), 1242 diag::warn_second_parameter_of_va_start_not_last_named_argument); 1243 return false; 1244} 1245 1246/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 1247/// friends. This is declared to take (...), so we have to check everything. 1248bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 1249 if (TheCall->getNumArgs() < 2) 1250 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1251 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 1252 if (TheCall->getNumArgs() > 2) 1253 return Diag(TheCall->getArg(2)->getLocStart(), 1254 diag::err_typecheck_call_too_many_args) 1255 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1256 << SourceRange(TheCall->getArg(2)->getLocStart(), 1257 (*(TheCall->arg_end()-1))->getLocEnd()); 1258 1259 ExprResult OrigArg0 = TheCall->getArg(0); 1260 ExprResult OrigArg1 = TheCall->getArg(1); 1261 1262 // Do standard promotions between the two arguments, returning their common 1263 // type. 1264 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 1265 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 1266 return true; 1267 1268 // Make sure any conversions are pushed back into the call; this is 1269 // type safe since unordered compare builtins are declared as "_Bool 1270 // foo(...)". 1271 TheCall->setArg(0, OrigArg0.get()); 1272 TheCall->setArg(1, OrigArg1.get()); 1273 1274 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 1275 return false; 1276 1277 // If the common type isn't a real floating type, then the arguments were 1278 // invalid for this operation. 1279 if (!Res->isRealFloatingType()) 1280 return Diag(OrigArg0.get()->getLocStart(), 1281 diag::err_typecheck_call_invalid_ordered_compare) 1282 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 1283 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 1284 1285 return false; 1286} 1287 1288/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 1289/// __builtin_isnan and friends. This is declared to take (...), so we have 1290/// to check everything. We expect the last argument to be a floating point 1291/// value. 1292bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 1293 if (TheCall->getNumArgs() < NumArgs) 1294 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1295 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 1296 if (TheCall->getNumArgs() > NumArgs) 1297 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 1298 diag::err_typecheck_call_too_many_args) 1299 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 1300 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 1301 (*(TheCall->arg_end()-1))->getLocEnd()); 1302 1303 Expr *OrigArg = TheCall->getArg(NumArgs-1); 1304 1305 if (OrigArg->isTypeDependent()) 1306 return false; 1307 1308 // This operation requires a non-_Complex floating-point number. 1309 if (!OrigArg->getType()->isRealFloatingType()) 1310 return Diag(OrigArg->getLocStart(), 1311 diag::err_typecheck_call_invalid_unary_fp) 1312 << OrigArg->getType() << OrigArg->getSourceRange(); 1313 1314 // If this is an implicit conversion from float -> double, remove it. 1315 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 1316 Expr *CastArg = Cast->getSubExpr(); 1317 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 1318 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 1319 "promotion from float to double is the only expected cast here"); 1320 Cast->setSubExpr(0); 1321 TheCall->setArg(NumArgs-1, CastArg); 1322 } 1323 } 1324 1325 return false; 1326} 1327 1328/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 1329// This is declared to take (...), so we have to check everything. 1330ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 1331 if (TheCall->getNumArgs() < 2) 1332 return ExprError(Diag(TheCall->getLocEnd(), 1333 diag::err_typecheck_call_too_few_args_at_least) 1334 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1335 << TheCall->getSourceRange()); 1336 1337 // Determine which of the following types of shufflevector we're checking: 1338 // 1) unary, vector mask: (lhs, mask) 1339 // 2) binary, vector mask: (lhs, rhs, mask) 1340 // 3) binary, scalar mask: (lhs, rhs, index, ..., index) 1341 QualType resType = TheCall->getArg(0)->getType(); 1342 unsigned numElements = 0; 1343 1344 if (!TheCall->getArg(0)->isTypeDependent() && 1345 !TheCall->getArg(1)->isTypeDependent()) { 1346 QualType LHSType = TheCall->getArg(0)->getType(); 1347 QualType RHSType = TheCall->getArg(1)->getType(); 1348 1349 if (!LHSType->isVectorType() || !RHSType->isVectorType()) { 1350 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector) 1351 << SourceRange(TheCall->getArg(0)->getLocStart(), 1352 TheCall->getArg(1)->getLocEnd()); 1353 return ExprError(); 1354 } 1355 1356 numElements = LHSType->getAs<VectorType>()->getNumElements(); 1357 unsigned numResElements = TheCall->getNumArgs() - 2; 1358 1359 // Check to see if we have a call with 2 vector arguments, the unary shuffle 1360 // with mask. If so, verify that RHS is an integer vector type with the 1361 // same number of elts as lhs. 1362 if (TheCall->getNumArgs() == 2) { 1363 if (!RHSType->hasIntegerRepresentation() || 1364 RHSType->getAs<VectorType>()->getNumElements() != numElements) 1365 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 1366 << SourceRange(TheCall->getArg(1)->getLocStart(), 1367 TheCall->getArg(1)->getLocEnd()); 1368 numResElements = numElements; 1369 } 1370 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 1371 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 1372 << SourceRange(TheCall->getArg(0)->getLocStart(), 1373 TheCall->getArg(1)->getLocEnd()); 1374 return ExprError(); 1375 } else if (numElements != numResElements) { 1376 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 1377 resType = Context.getVectorType(eltType, numResElements, 1378 VectorType::GenericVector); 1379 } 1380 } 1381 1382 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 1383 if (TheCall->getArg(i)->isTypeDependent() || 1384 TheCall->getArg(i)->isValueDependent()) 1385 continue; 1386 1387 llvm::APSInt Result(32); 1388 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 1389 return ExprError(Diag(TheCall->getLocStart(), 1390 diag::err_shufflevector_nonconstant_argument) 1391 << TheCall->getArg(i)->getSourceRange()); 1392 1393 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 1394 return ExprError(Diag(TheCall->getLocStart(), 1395 diag::err_shufflevector_argument_too_large) 1396 << TheCall->getArg(i)->getSourceRange()); 1397 } 1398 1399 SmallVector<Expr*, 32> exprs; 1400 1401 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 1402 exprs.push_back(TheCall->getArg(i)); 1403 TheCall->setArg(i, 0); 1404 } 1405 1406 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(), 1407 exprs.size(), resType, 1408 TheCall->getCallee()->getLocStart(), 1409 TheCall->getRParenLoc())); 1410} 1411 1412/// SemaBuiltinPrefetch - Handle __builtin_prefetch. 1413// This is declared to take (const void*, ...) and can take two 1414// optional constant int args. 1415bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 1416 unsigned NumArgs = TheCall->getNumArgs(); 1417 1418 if (NumArgs > 3) 1419 return Diag(TheCall->getLocEnd(), 1420 diag::err_typecheck_call_too_many_args_at_most) 1421 << 0 /*function call*/ << 3 << NumArgs 1422 << TheCall->getSourceRange(); 1423 1424 // Argument 0 is checked for us and the remaining arguments must be 1425 // constant integers. 1426 for (unsigned i = 1; i != NumArgs; ++i) { 1427 Expr *Arg = TheCall->getArg(i); 1428 1429 llvm::APSInt Result; 1430 if (SemaBuiltinConstantArg(TheCall, i, Result)) 1431 return true; 1432 1433 // FIXME: gcc issues a warning and rewrites these to 0. These 1434 // seems especially odd for the third argument since the default 1435 // is 3. 1436 if (i == 1) { 1437 if (Result.getLimitedValue() > 1) 1438 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1439 << "0" << "1" << Arg->getSourceRange(); 1440 } else { 1441 if (Result.getLimitedValue() > 3) 1442 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1443 << "0" << "3" << Arg->getSourceRange(); 1444 } 1445 } 1446 1447 return false; 1448} 1449 1450/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 1451/// TheCall is a constant expression. 1452bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 1453 llvm::APSInt &Result) { 1454 Expr *Arg = TheCall->getArg(ArgNum); 1455 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1456 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 1457 1458 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 1459 1460 if (!Arg->isIntegerConstantExpr(Result, Context)) 1461 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 1462 << FDecl->getDeclName() << Arg->getSourceRange(); 1463 1464 return false; 1465} 1466 1467/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, 1468/// int type). This simply type checks that type is one of the defined 1469/// constants (0-3). 1470// For compatibility check 0-3, llvm only handles 0 and 2. 1471bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { 1472 llvm::APSInt Result; 1473 1474 // Check constant-ness first. 1475 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 1476 return true; 1477 1478 Expr *Arg = TheCall->getArg(1); 1479 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { 1480 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1481 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 1482 } 1483 1484 return false; 1485} 1486 1487/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 1488/// This checks that val is a constant 1. 1489bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 1490 Expr *Arg = TheCall->getArg(1); 1491 llvm::APSInt Result; 1492 1493 // TODO: This is less than ideal. Overload this to take a value. 1494 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 1495 return true; 1496 1497 if (Result != 1) 1498 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 1499 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 1500 1501 return false; 1502} 1503 1504// Handle i > 1 ? "x" : "y", recursively. 1505bool Sema::SemaCheckStringLiteral(const Expr *E, Expr **Args, 1506 unsigned NumArgs, bool HasVAListArg, 1507 unsigned format_idx, unsigned firstDataArg, 1508 FormatStringType Type, bool inFunctionCall) { 1509 tryAgain: 1510 if (E->isTypeDependent() || E->isValueDependent()) 1511 return false; 1512 1513 E = E->IgnoreParenCasts(); 1514 1515 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 1516 // Technically -Wformat-nonliteral does not warn about this case. 1517 // The behavior of printf and friends in this case is implementation 1518 // dependent. Ideally if the format string cannot be null then 1519 // it should have a 'nonnull' attribute in the function prototype. 1520 return true; 1521 1522 switch (E->getStmtClass()) { 1523 case Stmt::BinaryConditionalOperatorClass: 1524 case Stmt::ConditionalOperatorClass: { 1525 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E); 1526 return SemaCheckStringLiteral(C->getTrueExpr(), Args, NumArgs, HasVAListArg, 1527 format_idx, firstDataArg, Type, 1528 inFunctionCall) 1529 && SemaCheckStringLiteral(C->getFalseExpr(), Args, NumArgs, HasVAListArg, 1530 format_idx, firstDataArg, Type, 1531 inFunctionCall); 1532 } 1533 1534 case Stmt::ImplicitCastExprClass: { 1535 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 1536 goto tryAgain; 1537 } 1538 1539 case Stmt::OpaqueValueExprClass: 1540 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 1541 E = src; 1542 goto tryAgain; 1543 } 1544 return false; 1545 1546 case Stmt::PredefinedExprClass: 1547 // While __func__, etc., are technically not string literals, they 1548 // cannot contain format specifiers and thus are not a security 1549 // liability. 1550 return true; 1551 1552 case Stmt::DeclRefExprClass: { 1553 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 1554 1555 // As an exception, do not flag errors for variables binding to 1556 // const string literals. 1557 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 1558 bool isConstant = false; 1559 QualType T = DR->getType(); 1560 1561 if (const ArrayType *AT = Context.getAsArrayType(T)) { 1562 isConstant = AT->getElementType().isConstant(Context); 1563 } else if (const PointerType *PT = T->getAs<PointerType>()) { 1564 isConstant = T.isConstant(Context) && 1565 PT->getPointeeType().isConstant(Context); 1566 } else if (T->isObjCObjectPointerType()) { 1567 // In ObjC, there is usually no "const ObjectPointer" type, 1568 // so don't check if the pointee type is constant. 1569 isConstant = T.isConstant(Context); 1570 } 1571 1572 if (isConstant) { 1573 if (const Expr *Init = VD->getAnyInitializer()) { 1574 // Look through initializers like const char c[] = { "foo" } 1575 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 1576 if (InitList->isStringLiteralInit()) 1577 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 1578 } 1579 return SemaCheckStringLiteral(Init, Args, NumArgs, 1580 HasVAListArg, format_idx, firstDataArg, 1581 Type, /*inFunctionCall*/false); 1582 } 1583 } 1584 1585 // For vprintf* functions (i.e., HasVAListArg==true), we add a 1586 // special check to see if the format string is a function parameter 1587 // of the function calling the printf function. If the function 1588 // has an attribute indicating it is a printf-like function, then we 1589 // should suppress warnings concerning non-literals being used in a call 1590 // to a vprintf function. For example: 1591 // 1592 // void 1593 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 1594 // va_list ap; 1595 // va_start(ap, fmt); 1596 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 1597 // ... 1598 // 1599 if (HasVAListArg) { 1600 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 1601 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 1602 int PVIndex = PV->getFunctionScopeIndex() + 1; 1603 for (specific_attr_iterator<FormatAttr> 1604 i = ND->specific_attr_begin<FormatAttr>(), 1605 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) { 1606 FormatAttr *PVFormat = *i; 1607 // adjust for implicit parameter 1608 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 1609 if (MD->isInstance()) 1610 ++PVIndex; 1611 // We also check if the formats are compatible. 1612 // We can't pass a 'scanf' string to a 'printf' function. 1613 if (PVIndex == PVFormat->getFormatIdx() && 1614 Type == GetFormatStringType(PVFormat)) 1615 return true; 1616 } 1617 } 1618 } 1619 } 1620 } 1621 1622 return false; 1623 } 1624 1625 case Stmt::CallExprClass: 1626 case Stmt::CXXMemberCallExprClass: { 1627 const CallExpr *CE = cast<CallExpr>(E); 1628 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 1629 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 1630 unsigned ArgIndex = FA->getFormatIdx(); 1631 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 1632 if (MD->isInstance()) 1633 --ArgIndex; 1634 const Expr *Arg = CE->getArg(ArgIndex - 1); 1635 1636 return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg, 1637 format_idx, firstDataArg, Type, 1638 inFunctionCall); 1639 } 1640 } 1641 1642 return false; 1643 } 1644 case Stmt::ObjCStringLiteralClass: 1645 case Stmt::StringLiteralClass: { 1646 const StringLiteral *StrE = NULL; 1647 1648 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 1649 StrE = ObjCFExpr->getString(); 1650 else 1651 StrE = cast<StringLiteral>(E); 1652 1653 if (StrE) { 1654 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx, 1655 firstDataArg, Type, inFunctionCall); 1656 return true; 1657 } 1658 1659 return false; 1660 } 1661 1662 default: 1663 return false; 1664 } 1665} 1666 1667void 1668Sema::CheckNonNullArguments(const NonNullAttr *NonNull, 1669 const Expr * const *ExprArgs, 1670 SourceLocation CallSiteLoc) { 1671 for (NonNullAttr::args_iterator i = NonNull->args_begin(), 1672 e = NonNull->args_end(); 1673 i != e; ++i) { 1674 const Expr *ArgExpr = ExprArgs[*i]; 1675 if (ArgExpr->isNullPointerConstant(Context, 1676 Expr::NPC_ValueDependentIsNotNull)) 1677 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 1678 } 1679} 1680 1681Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 1682 return llvm::StringSwitch<FormatStringType>(Format->getType()) 1683 .Case("scanf", FST_Scanf) 1684 .Cases("printf", "printf0", FST_Printf) 1685 .Cases("NSString", "CFString", FST_NSString) 1686 .Case("strftime", FST_Strftime) 1687 .Case("strfmon", FST_Strfmon) 1688 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 1689 .Default(FST_Unknown); 1690} 1691 1692/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar 1693/// functions) for correct use of format strings. 1694void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) { 1695 bool IsCXXMember = false; 1696 // The way the format attribute works in GCC, the implicit this argument 1697 // of member functions is counted. However, it doesn't appear in our own 1698 // lists, so decrement format_idx in that case. 1699 IsCXXMember = isa<CXXMemberCallExpr>(TheCall); 1700 CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(), 1701 IsCXXMember, TheCall->getRParenLoc(), 1702 TheCall->getCallee()->getSourceRange()); 1703} 1704 1705void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args, 1706 unsigned NumArgs, bool IsCXXMember, 1707 SourceLocation Loc, SourceRange Range) { 1708 bool HasVAListArg = Format->getFirstArg() == 0; 1709 unsigned format_idx = Format->getFormatIdx() - 1; 1710 unsigned firstDataArg = HasVAListArg ? 0 : Format->getFirstArg() - 1; 1711 if (IsCXXMember) { 1712 if (format_idx == 0) 1713 return; 1714 --format_idx; 1715 if(firstDataArg != 0) 1716 --firstDataArg; 1717 } 1718 CheckFormatArguments(Args, NumArgs, HasVAListArg, format_idx, 1719 firstDataArg, GetFormatStringType(Format), Loc, Range); 1720} 1721 1722void Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs, 1723 bool HasVAListArg, unsigned format_idx, 1724 unsigned firstDataArg, FormatStringType Type, 1725 SourceLocation Loc, SourceRange Range) { 1726 // CHECK: printf/scanf-like function is called with no format string. 1727 if (format_idx >= NumArgs) { 1728 Diag(Loc, diag::warn_missing_format_string) << Range; 1729 return; 1730 } 1731 1732 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 1733 1734 // CHECK: format string is not a string literal. 1735 // 1736 // Dynamically generated format strings are difficult to 1737 // automatically vet at compile time. Requiring that format strings 1738 // are string literals: (1) permits the checking of format strings by 1739 // the compiler and thereby (2) can practically remove the source of 1740 // many format string exploits. 1741 1742 // Format string can be either ObjC string (e.g. @"%d") or 1743 // C string (e.g. "%d") 1744 // ObjC string uses the same format specifiers as C string, so we can use 1745 // the same format string checking logic for both ObjC and C strings. 1746 if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg, 1747 format_idx, firstDataArg, Type)) 1748 return; // Literal format string found, check done! 1749 1750 // Strftime is particular as it always uses a single 'time' argument, 1751 // so it is safe to pass a non-literal string. 1752 if (Type == FST_Strftime) 1753 return; 1754 1755 // Do not emit diag when the string param is a macro expansion and the 1756 // format is either NSString or CFString. This is a hack to prevent 1757 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 1758 // which are usually used in place of NS and CF string literals. 1759 if (Type == FST_NSString && 1760 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart())) 1761 return; 1762 1763 // If there are no arguments specified, warn with -Wformat-security, otherwise 1764 // warn only with -Wformat-nonliteral. 1765 if (NumArgs == format_idx+1) 1766 Diag(Args[format_idx]->getLocStart(), 1767 diag::warn_format_nonliteral_noargs) 1768 << OrigFormatExpr->getSourceRange(); 1769 else 1770 Diag(Args[format_idx]->getLocStart(), 1771 diag::warn_format_nonliteral) 1772 << OrigFormatExpr->getSourceRange(); 1773} 1774 1775namespace { 1776class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 1777protected: 1778 Sema &S; 1779 const StringLiteral *FExpr; 1780 const Expr *OrigFormatExpr; 1781 const unsigned FirstDataArg; 1782 const unsigned NumDataArgs; 1783 const bool IsObjCLiteral; 1784 const char *Beg; // Start of format string. 1785 const bool HasVAListArg; 1786 const Expr * const *Args; 1787 const unsigned NumArgs; 1788 unsigned FormatIdx; 1789 llvm::BitVector CoveredArgs; 1790 bool usesPositionalArgs; 1791 bool atFirstArg; 1792 bool inFunctionCall; 1793public: 1794 CheckFormatHandler(Sema &s, const StringLiteral *fexpr, 1795 const Expr *origFormatExpr, unsigned firstDataArg, 1796 unsigned numDataArgs, bool isObjCLiteral, 1797 const char *beg, bool hasVAListArg, 1798 Expr **args, unsigned numArgs, 1799 unsigned formatIdx, bool inFunctionCall) 1800 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 1801 FirstDataArg(firstDataArg), 1802 NumDataArgs(numDataArgs), 1803 IsObjCLiteral(isObjCLiteral), Beg(beg), 1804 HasVAListArg(hasVAListArg), 1805 Args(args), NumArgs(numArgs), FormatIdx(formatIdx), 1806 usesPositionalArgs(false), atFirstArg(true), 1807 inFunctionCall(inFunctionCall) { 1808 CoveredArgs.resize(numDataArgs); 1809 CoveredArgs.reset(); 1810 } 1811 1812 void DoneProcessing(); 1813 1814 void HandleIncompleteSpecifier(const char *startSpecifier, 1815 unsigned specifierLen); 1816 1817 void HandleNonStandardLengthModifier( 1818 const analyze_format_string::LengthModifier &LM, 1819 const char *startSpecifier, unsigned specifierLen); 1820 1821 void HandleNonStandardConversionSpecifier( 1822 const analyze_format_string::ConversionSpecifier &CS, 1823 const char *startSpecifier, unsigned specifierLen); 1824 1825 void HandleNonStandardConversionSpecification( 1826 const analyze_format_string::LengthModifier &LM, 1827 const analyze_format_string::ConversionSpecifier &CS, 1828 const char *startSpecifier, unsigned specifierLen); 1829 1830 virtual void HandlePosition(const char *startPos, unsigned posLen); 1831 1832 virtual void HandleInvalidPosition(const char *startSpecifier, 1833 unsigned specifierLen, 1834 analyze_format_string::PositionContext p); 1835 1836 virtual void HandleZeroPosition(const char *startPos, unsigned posLen); 1837 1838 void HandleNullChar(const char *nullCharacter); 1839 1840 template <typename Range> 1841 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall, 1842 const Expr *ArgumentExpr, 1843 PartialDiagnostic PDiag, 1844 SourceLocation StringLoc, 1845 bool IsStringLocation, Range StringRange, 1846 FixItHint Fixit = FixItHint()); 1847 1848protected: 1849 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 1850 const char *startSpec, 1851 unsigned specifierLen, 1852 const char *csStart, unsigned csLen); 1853 1854 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 1855 const char *startSpec, 1856 unsigned specifierLen); 1857 1858 SourceRange getFormatStringRange(); 1859 CharSourceRange getSpecifierRange(const char *startSpecifier, 1860 unsigned specifierLen); 1861 SourceLocation getLocationOfByte(const char *x); 1862 1863 const Expr *getDataArg(unsigned i) const; 1864 1865 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 1866 const analyze_format_string::ConversionSpecifier &CS, 1867 const char *startSpecifier, unsigned specifierLen, 1868 unsigned argIndex); 1869 1870 template <typename Range> 1871 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 1872 bool IsStringLocation, Range StringRange, 1873 FixItHint Fixit = FixItHint()); 1874 1875 void CheckPositionalAndNonpositionalArgs( 1876 const analyze_format_string::FormatSpecifier *FS); 1877}; 1878} 1879 1880SourceRange CheckFormatHandler::getFormatStringRange() { 1881 return OrigFormatExpr->getSourceRange(); 1882} 1883 1884CharSourceRange CheckFormatHandler:: 1885getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 1886 SourceLocation Start = getLocationOfByte(startSpecifier); 1887 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 1888 1889 // Advance the end SourceLocation by one due to half-open ranges. 1890 End = End.getLocWithOffset(1); 1891 1892 return CharSourceRange::getCharRange(Start, End); 1893} 1894 1895SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 1896 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 1897} 1898 1899void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 1900 unsigned specifierLen){ 1901 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 1902 getLocationOfByte(startSpecifier), 1903 /*IsStringLocation*/true, 1904 getSpecifierRange(startSpecifier, specifierLen)); 1905} 1906 1907void CheckFormatHandler::HandleNonStandardLengthModifier( 1908 const analyze_format_string::LengthModifier &LM, 1909 const char *startSpecifier, unsigned specifierLen) { 1910 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toString() 1911 << 0, 1912 getLocationOfByte(LM.getStart()), 1913 /*IsStringLocation*/true, 1914 getSpecifierRange(startSpecifier, specifierLen)); 1915} 1916 1917void CheckFormatHandler::HandleNonStandardConversionSpecifier( 1918 const analyze_format_string::ConversionSpecifier &CS, 1919 const char *startSpecifier, unsigned specifierLen) { 1920 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString() 1921 << 1, 1922 getLocationOfByte(CS.getStart()), 1923 /*IsStringLocation*/true, 1924 getSpecifierRange(startSpecifier, specifierLen)); 1925} 1926 1927void CheckFormatHandler::HandleNonStandardConversionSpecification( 1928 const analyze_format_string::LengthModifier &LM, 1929 const analyze_format_string::ConversionSpecifier &CS, 1930 const char *startSpecifier, unsigned specifierLen) { 1931 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_conversion_spec) 1932 << LM.toString() << CS.toString(), 1933 getLocationOfByte(LM.getStart()), 1934 /*IsStringLocation*/true, 1935 getSpecifierRange(startSpecifier, specifierLen)); 1936} 1937 1938void CheckFormatHandler::HandlePosition(const char *startPos, 1939 unsigned posLen) { 1940 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 1941 getLocationOfByte(startPos), 1942 /*IsStringLocation*/true, 1943 getSpecifierRange(startPos, posLen)); 1944} 1945 1946void 1947CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 1948 analyze_format_string::PositionContext p) { 1949 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 1950 << (unsigned) p, 1951 getLocationOfByte(startPos), /*IsStringLocation*/true, 1952 getSpecifierRange(startPos, posLen)); 1953} 1954 1955void CheckFormatHandler::HandleZeroPosition(const char *startPos, 1956 unsigned posLen) { 1957 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 1958 getLocationOfByte(startPos), 1959 /*IsStringLocation*/true, 1960 getSpecifierRange(startPos, posLen)); 1961} 1962 1963void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 1964 if (!IsObjCLiteral) { 1965 // The presence of a null character is likely an error. 1966 EmitFormatDiagnostic( 1967 S.PDiag(diag::warn_printf_format_string_contains_null_char), 1968 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 1969 getFormatStringRange()); 1970 } 1971} 1972 1973const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 1974 return Args[FirstDataArg + i]; 1975} 1976 1977void CheckFormatHandler::DoneProcessing() { 1978 // Does the number of data arguments exceed the number of 1979 // format conversions in the format string? 1980 if (!HasVAListArg) { 1981 // Find any arguments that weren't covered. 1982 CoveredArgs.flip(); 1983 signed notCoveredArg = CoveredArgs.find_first(); 1984 if (notCoveredArg >= 0) { 1985 assert((unsigned)notCoveredArg < NumDataArgs); 1986 SourceLocation Loc = getDataArg((unsigned) notCoveredArg)->getLocStart(); 1987 if (!S.getSourceManager().isInSystemMacro(Loc)) { 1988 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used), 1989 Loc, 1990 /*IsStringLocation*/false, getFormatStringRange()); 1991 } 1992 } 1993 } 1994} 1995 1996bool 1997CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 1998 SourceLocation Loc, 1999 const char *startSpec, 2000 unsigned specifierLen, 2001 const char *csStart, 2002 unsigned csLen) { 2003 2004 bool keepGoing = true; 2005 if (argIndex < NumDataArgs) { 2006 // Consider the argument coverered, even though the specifier doesn't 2007 // make sense. 2008 CoveredArgs.set(argIndex); 2009 } 2010 else { 2011 // If argIndex exceeds the number of data arguments we 2012 // don't issue a warning because that is just a cascade of warnings (and 2013 // they may have intended '%%' anyway). We don't want to continue processing 2014 // the format string after this point, however, as we will like just get 2015 // gibberish when trying to match arguments. 2016 keepGoing = false; 2017 } 2018 2019 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion) 2020 << StringRef(csStart, csLen), 2021 Loc, /*IsStringLocation*/true, 2022 getSpecifierRange(startSpec, specifierLen)); 2023 2024 return keepGoing; 2025} 2026 2027void 2028CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 2029 const char *startSpec, 2030 unsigned specifierLen) { 2031 EmitFormatDiagnostic( 2032 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 2033 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 2034} 2035 2036bool 2037CheckFormatHandler::CheckNumArgs( 2038 const analyze_format_string::FormatSpecifier &FS, 2039 const analyze_format_string::ConversionSpecifier &CS, 2040 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 2041 2042 if (argIndex >= NumDataArgs) { 2043 PartialDiagnostic PDiag = FS.usesPositionalArg() 2044 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 2045 << (argIndex+1) << NumDataArgs) 2046 : S.PDiag(diag::warn_printf_insufficient_data_args); 2047 EmitFormatDiagnostic( 2048 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 2049 getSpecifierRange(startSpecifier, specifierLen)); 2050 return false; 2051 } 2052 return true; 2053} 2054 2055template<typename Range> 2056void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 2057 SourceLocation Loc, 2058 bool IsStringLocation, 2059 Range StringRange, 2060 FixItHint FixIt) { 2061 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 2062 Loc, IsStringLocation, StringRange, FixIt); 2063} 2064 2065/// \brief If the format string is not within the funcion call, emit a note 2066/// so that the function call and string are in diagnostic messages. 2067/// 2068/// \param inFunctionCall if true, the format string is within the function 2069/// call and only one diagnostic message will be produced. Otherwise, an 2070/// extra note will be emitted pointing to location of the format string. 2071/// 2072/// \param ArgumentExpr the expression that is passed as the format string 2073/// argument in the function call. Used for getting locations when two 2074/// diagnostics are emitted. 2075/// 2076/// \param PDiag the callee should already have provided any strings for the 2077/// diagnostic message. This function only adds locations and fixits 2078/// to diagnostics. 2079/// 2080/// \param Loc primary location for diagnostic. If two diagnostics are 2081/// required, one will be at Loc and a new SourceLocation will be created for 2082/// the other one. 2083/// 2084/// \param IsStringLocation if true, Loc points to the format string should be 2085/// used for the note. Otherwise, Loc points to the argument list and will 2086/// be used with PDiag. 2087/// 2088/// \param StringRange some or all of the string to highlight. This is 2089/// templated so it can accept either a CharSourceRange or a SourceRange. 2090/// 2091/// \param Fixit optional fix it hint for the format string. 2092template<typename Range> 2093void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall, 2094 const Expr *ArgumentExpr, 2095 PartialDiagnostic PDiag, 2096 SourceLocation Loc, 2097 bool IsStringLocation, 2098 Range StringRange, 2099 FixItHint FixIt) { 2100 if (InFunctionCall) 2101 S.Diag(Loc, PDiag) << StringRange << FixIt; 2102 else { 2103 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 2104 << ArgumentExpr->getSourceRange(); 2105 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 2106 diag::note_format_string_defined) 2107 << StringRange << FixIt; 2108 } 2109} 2110 2111//===--- CHECK: Printf format string checking ------------------------------===// 2112 2113namespace { 2114class CheckPrintfHandler : public CheckFormatHandler { 2115public: 2116 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 2117 const Expr *origFormatExpr, unsigned firstDataArg, 2118 unsigned numDataArgs, bool isObjCLiteral, 2119 const char *beg, bool hasVAListArg, 2120 Expr **Args, unsigned NumArgs, 2121 unsigned formatIdx, bool inFunctionCall) 2122 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 2123 numDataArgs, isObjCLiteral, beg, hasVAListArg, 2124 Args, NumArgs, formatIdx, inFunctionCall) {} 2125 2126 2127 bool HandleInvalidPrintfConversionSpecifier( 2128 const analyze_printf::PrintfSpecifier &FS, 2129 const char *startSpecifier, 2130 unsigned specifierLen); 2131 2132 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 2133 const char *startSpecifier, 2134 unsigned specifierLen); 2135 2136 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 2137 const char *startSpecifier, unsigned specifierLen); 2138 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 2139 const analyze_printf::OptionalAmount &Amt, 2140 unsigned type, 2141 const char *startSpecifier, unsigned specifierLen); 2142 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 2143 const analyze_printf::OptionalFlag &flag, 2144 const char *startSpecifier, unsigned specifierLen); 2145 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 2146 const analyze_printf::OptionalFlag &ignoredFlag, 2147 const analyze_printf::OptionalFlag &flag, 2148 const char *startSpecifier, unsigned specifierLen); 2149}; 2150} 2151 2152bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 2153 const analyze_printf::PrintfSpecifier &FS, 2154 const char *startSpecifier, 2155 unsigned specifierLen) { 2156 const analyze_printf::PrintfConversionSpecifier &CS = 2157 FS.getConversionSpecifier(); 2158 2159 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 2160 getLocationOfByte(CS.getStart()), 2161 startSpecifier, specifierLen, 2162 CS.getStart(), CS.getLength()); 2163} 2164 2165bool CheckPrintfHandler::HandleAmount( 2166 const analyze_format_string::OptionalAmount &Amt, 2167 unsigned k, const char *startSpecifier, 2168 unsigned specifierLen) { 2169 2170 if (Amt.hasDataArgument()) { 2171 if (!HasVAListArg) { 2172 unsigned argIndex = Amt.getArgIndex(); 2173 if (argIndex >= NumDataArgs) { 2174 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 2175 << k, 2176 getLocationOfByte(Amt.getStart()), 2177 /*IsStringLocation*/true, 2178 getSpecifierRange(startSpecifier, specifierLen)); 2179 // Don't do any more checking. We will just emit 2180 // spurious errors. 2181 return false; 2182 } 2183 2184 // Type check the data argument. It should be an 'int'. 2185 // Although not in conformance with C99, we also allow the argument to be 2186 // an 'unsigned int' as that is a reasonably safe case. GCC also 2187 // doesn't emit a warning for that case. 2188 CoveredArgs.set(argIndex); 2189 const Expr *Arg = getDataArg(argIndex); 2190 QualType T = Arg->getType(); 2191 2192 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context); 2193 assert(ATR.isValid()); 2194 2195 if (!ATR.matchesType(S.Context, T)) { 2196 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 2197 << k << ATR.getRepresentativeTypeName(S.Context) 2198 << T << Arg->getSourceRange(), 2199 getLocationOfByte(Amt.getStart()), 2200 /*IsStringLocation*/true, 2201 getSpecifierRange(startSpecifier, specifierLen)); 2202 // Don't do any more checking. We will just emit 2203 // spurious errors. 2204 return false; 2205 } 2206 } 2207 } 2208 return true; 2209} 2210 2211void CheckPrintfHandler::HandleInvalidAmount( 2212 const analyze_printf::PrintfSpecifier &FS, 2213 const analyze_printf::OptionalAmount &Amt, 2214 unsigned type, 2215 const char *startSpecifier, 2216 unsigned specifierLen) { 2217 const analyze_printf::PrintfConversionSpecifier &CS = 2218 FS.getConversionSpecifier(); 2219 2220 FixItHint fixit = 2221 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 2222 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 2223 Amt.getConstantLength())) 2224 : FixItHint(); 2225 2226 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 2227 << type << CS.toString(), 2228 getLocationOfByte(Amt.getStart()), 2229 /*IsStringLocation*/true, 2230 getSpecifierRange(startSpecifier, specifierLen), 2231 fixit); 2232} 2233 2234void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 2235 const analyze_printf::OptionalFlag &flag, 2236 const char *startSpecifier, 2237 unsigned specifierLen) { 2238 // Warn about pointless flag with a fixit removal. 2239 const analyze_printf::PrintfConversionSpecifier &CS = 2240 FS.getConversionSpecifier(); 2241 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 2242 << flag.toString() << CS.toString(), 2243 getLocationOfByte(flag.getPosition()), 2244 /*IsStringLocation*/true, 2245 getSpecifierRange(startSpecifier, specifierLen), 2246 FixItHint::CreateRemoval( 2247 getSpecifierRange(flag.getPosition(), 1))); 2248} 2249 2250void CheckPrintfHandler::HandleIgnoredFlag( 2251 const analyze_printf::PrintfSpecifier &FS, 2252 const analyze_printf::OptionalFlag &ignoredFlag, 2253 const analyze_printf::OptionalFlag &flag, 2254 const char *startSpecifier, 2255 unsigned specifierLen) { 2256 // Warn about ignored flag with a fixit removal. 2257 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 2258 << ignoredFlag.toString() << flag.toString(), 2259 getLocationOfByte(ignoredFlag.getPosition()), 2260 /*IsStringLocation*/true, 2261 getSpecifierRange(startSpecifier, specifierLen), 2262 FixItHint::CreateRemoval( 2263 getSpecifierRange(ignoredFlag.getPosition(), 1))); 2264} 2265 2266bool 2267CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 2268 &FS, 2269 const char *startSpecifier, 2270 unsigned specifierLen) { 2271 2272 using namespace analyze_format_string; 2273 using namespace analyze_printf; 2274 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 2275 2276 if (FS.consumesDataArgument()) { 2277 if (atFirstArg) { 2278 atFirstArg = false; 2279 usesPositionalArgs = FS.usesPositionalArg(); 2280 } 2281 else if (usesPositionalArgs != FS.usesPositionalArg()) { 2282 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 2283 startSpecifier, specifierLen); 2284 return false; 2285 } 2286 } 2287 2288 // First check if the field width, precision, and conversion specifier 2289 // have matching data arguments. 2290 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 2291 startSpecifier, specifierLen)) { 2292 return false; 2293 } 2294 2295 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 2296 startSpecifier, specifierLen)) { 2297 return false; 2298 } 2299 2300 if (!CS.consumesDataArgument()) { 2301 // FIXME: Technically specifying a precision or field width here 2302 // makes no sense. Worth issuing a warning at some point. 2303 return true; 2304 } 2305 2306 // Consume the argument. 2307 unsigned argIndex = FS.getArgIndex(); 2308 if (argIndex < NumDataArgs) { 2309 // The check to see if the argIndex is valid will come later. 2310 // We set the bit here because we may exit early from this 2311 // function if we encounter some other error. 2312 CoveredArgs.set(argIndex); 2313 } 2314 2315 // Check for using an Objective-C specific conversion specifier 2316 // in a non-ObjC literal. 2317 if (!IsObjCLiteral && CS.isObjCArg()) { 2318 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 2319 specifierLen); 2320 } 2321 2322 // Check for invalid use of field width 2323 if (!FS.hasValidFieldWidth()) { 2324 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 2325 startSpecifier, specifierLen); 2326 } 2327 2328 // Check for invalid use of precision 2329 if (!FS.hasValidPrecision()) { 2330 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 2331 startSpecifier, specifierLen); 2332 } 2333 2334 // Check each flag does not conflict with any other component. 2335 if (!FS.hasValidThousandsGroupingPrefix()) 2336 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 2337 if (!FS.hasValidLeadingZeros()) 2338 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 2339 if (!FS.hasValidPlusPrefix()) 2340 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 2341 if (!FS.hasValidSpacePrefix()) 2342 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 2343 if (!FS.hasValidAlternativeForm()) 2344 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 2345 if (!FS.hasValidLeftJustified()) 2346 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 2347 2348 // Check that flags are not ignored by another flag 2349 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 2350 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 2351 startSpecifier, specifierLen); 2352 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 2353 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 2354 startSpecifier, specifierLen); 2355 2356 // Check the length modifier is valid with the given conversion specifier. 2357 const LengthModifier &LM = FS.getLengthModifier(); 2358 if (!FS.hasValidLengthModifier()) 2359 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length) 2360 << LM.toString() << CS.toString(), 2361 getLocationOfByte(LM.getStart()), 2362 /*IsStringLocation*/true, 2363 getSpecifierRange(startSpecifier, specifierLen), 2364 FixItHint::CreateRemoval( 2365 getSpecifierRange(LM.getStart(), 2366 LM.getLength()))); 2367 if (!FS.hasStandardLengthModifier()) 2368 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen); 2369 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 2370 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 2371 if (!FS.hasStandardLengthConversionCombination()) 2372 HandleNonStandardConversionSpecification(LM, CS, startSpecifier, 2373 specifierLen); 2374 2375 // Are we using '%n'? 2376 if (CS.getKind() == ConversionSpecifier::nArg) { 2377 // Issue a warning about this being a possible security issue. 2378 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back), 2379 getLocationOfByte(CS.getStart()), 2380 /*IsStringLocation*/true, 2381 getSpecifierRange(startSpecifier, specifierLen)); 2382 // Continue checking the other format specifiers. 2383 return true; 2384 } 2385 2386 // The remaining checks depend on the data arguments. 2387 if (HasVAListArg) 2388 return true; 2389 2390 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 2391 return false; 2392 2393 // Now type check the data expression that matches the 2394 // format specifier. 2395 const Expr *Ex = getDataArg(argIndex); 2396 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context, 2397 IsObjCLiteral); 2398 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) { 2399 // Check if we didn't match because of an implicit cast from a 'char' 2400 // or 'short' to an 'int'. This is done because printf is a varargs 2401 // function. 2402 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex)) 2403 if (ICE->getType() == S.Context.IntTy || 2404 ICE->getType() == S.Context.UnsignedIntTy) { 2405 // All further checking is done on the subexpression. 2406 Ex = ICE->getSubExpr(); 2407 if (ATR.matchesType(S.Context, Ex->getType())) 2408 return true; 2409 } 2410 2411 // We may be able to offer a FixItHint if it is a supported type. 2412 PrintfSpecifier fixedFS = FS; 2413 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(), 2414 S.Context, IsObjCLiteral); 2415 2416 if (success) { 2417 // Get the fix string from the fixed format specifier 2418 SmallString<128> buf; 2419 llvm::raw_svector_ostream os(buf); 2420 fixedFS.toString(os); 2421 2422 EmitFormatDiagnostic( 2423 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2424 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2425 << Ex->getSourceRange(), 2426 getLocationOfByte(CS.getStart()), 2427 /*IsStringLocation*/true, 2428 getSpecifierRange(startSpecifier, specifierLen), 2429 FixItHint::CreateReplacement( 2430 getSpecifierRange(startSpecifier, specifierLen), 2431 os.str())); 2432 } 2433 else { 2434 EmitFormatDiagnostic( 2435 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2436 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2437 << getSpecifierRange(startSpecifier, specifierLen) 2438 << Ex->getSourceRange(), 2439 getLocationOfByte(CS.getStart()), 2440 true, 2441 getSpecifierRange(startSpecifier, specifierLen)); 2442 } 2443 } 2444 2445 return true; 2446} 2447 2448//===--- CHECK: Scanf format string checking ------------------------------===// 2449 2450namespace { 2451class CheckScanfHandler : public CheckFormatHandler { 2452public: 2453 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 2454 const Expr *origFormatExpr, unsigned firstDataArg, 2455 unsigned numDataArgs, bool isObjCLiteral, 2456 const char *beg, bool hasVAListArg, 2457 Expr **Args, unsigned NumArgs, 2458 unsigned formatIdx, bool inFunctionCall) 2459 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 2460 numDataArgs, isObjCLiteral, beg, hasVAListArg, 2461 Args, NumArgs, formatIdx, inFunctionCall) {} 2462 2463 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 2464 const char *startSpecifier, 2465 unsigned specifierLen); 2466 2467 bool HandleInvalidScanfConversionSpecifier( 2468 const analyze_scanf::ScanfSpecifier &FS, 2469 const char *startSpecifier, 2470 unsigned specifierLen); 2471 2472 void HandleIncompleteScanList(const char *start, const char *end); 2473}; 2474} 2475 2476void CheckScanfHandler::HandleIncompleteScanList(const char *start, 2477 const char *end) { 2478 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 2479 getLocationOfByte(end), /*IsStringLocation*/true, 2480 getSpecifierRange(start, end - start)); 2481} 2482 2483bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 2484 const analyze_scanf::ScanfSpecifier &FS, 2485 const char *startSpecifier, 2486 unsigned specifierLen) { 2487 2488 const analyze_scanf::ScanfConversionSpecifier &CS = 2489 FS.getConversionSpecifier(); 2490 2491 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 2492 getLocationOfByte(CS.getStart()), 2493 startSpecifier, specifierLen, 2494 CS.getStart(), CS.getLength()); 2495} 2496 2497bool CheckScanfHandler::HandleScanfSpecifier( 2498 const analyze_scanf::ScanfSpecifier &FS, 2499 const char *startSpecifier, 2500 unsigned specifierLen) { 2501 2502 using namespace analyze_scanf; 2503 using namespace analyze_format_string; 2504 2505 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 2506 2507 // Handle case where '%' and '*' don't consume an argument. These shouldn't 2508 // be used to decide if we are using positional arguments consistently. 2509 if (FS.consumesDataArgument()) { 2510 if (atFirstArg) { 2511 atFirstArg = false; 2512 usesPositionalArgs = FS.usesPositionalArg(); 2513 } 2514 else if (usesPositionalArgs != FS.usesPositionalArg()) { 2515 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 2516 startSpecifier, specifierLen); 2517 return false; 2518 } 2519 } 2520 2521 // Check if the field with is non-zero. 2522 const OptionalAmount &Amt = FS.getFieldWidth(); 2523 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 2524 if (Amt.getConstantAmount() == 0) { 2525 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 2526 Amt.getConstantLength()); 2527 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 2528 getLocationOfByte(Amt.getStart()), 2529 /*IsStringLocation*/true, R, 2530 FixItHint::CreateRemoval(R)); 2531 } 2532 } 2533 2534 if (!FS.consumesDataArgument()) { 2535 // FIXME: Technically specifying a precision or field width here 2536 // makes no sense. Worth issuing a warning at some point. 2537 return true; 2538 } 2539 2540 // Consume the argument. 2541 unsigned argIndex = FS.getArgIndex(); 2542 if (argIndex < NumDataArgs) { 2543 // The check to see if the argIndex is valid will come later. 2544 // We set the bit here because we may exit early from this 2545 // function if we encounter some other error. 2546 CoveredArgs.set(argIndex); 2547 } 2548 2549 // Check the length modifier is valid with the given conversion specifier. 2550 const LengthModifier &LM = FS.getLengthModifier(); 2551 if (!FS.hasValidLengthModifier()) { 2552 const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength()); 2553 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length) 2554 << LM.toString() << CS.toString() 2555 << getSpecifierRange(startSpecifier, specifierLen), 2556 getLocationOfByte(LM.getStart()), 2557 /*IsStringLocation*/true, R, 2558 FixItHint::CreateRemoval(R)); 2559 } 2560 2561 if (!FS.hasStandardLengthModifier()) 2562 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen); 2563 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 2564 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 2565 if (!FS.hasStandardLengthConversionCombination()) 2566 HandleNonStandardConversionSpecification(LM, CS, startSpecifier, 2567 specifierLen); 2568 2569 // The remaining checks depend on the data arguments. 2570 if (HasVAListArg) 2571 return true; 2572 2573 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 2574 return false; 2575 2576 // Check that the argument type matches the format specifier. 2577 const Expr *Ex = getDataArg(argIndex); 2578 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context); 2579 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) { 2580 ScanfSpecifier fixedFS = FS; 2581 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(), 2582 S.Context); 2583 2584 if (success) { 2585 // Get the fix string from the fixed format specifier. 2586 SmallString<128> buf; 2587 llvm::raw_svector_ostream os(buf); 2588 fixedFS.toString(os); 2589 2590 EmitFormatDiagnostic( 2591 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2592 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2593 << Ex->getSourceRange(), 2594 getLocationOfByte(CS.getStart()), 2595 /*IsStringLocation*/true, 2596 getSpecifierRange(startSpecifier, specifierLen), 2597 FixItHint::CreateReplacement( 2598 getSpecifierRange(startSpecifier, specifierLen), 2599 os.str())); 2600 } else { 2601 EmitFormatDiagnostic( 2602 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2603 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2604 << Ex->getSourceRange(), 2605 getLocationOfByte(CS.getStart()), 2606 /*IsStringLocation*/true, 2607 getSpecifierRange(startSpecifier, specifierLen)); 2608 } 2609 } 2610 2611 return true; 2612} 2613 2614void Sema::CheckFormatString(const StringLiteral *FExpr, 2615 const Expr *OrigFormatExpr, 2616 Expr **Args, unsigned NumArgs, 2617 bool HasVAListArg, unsigned format_idx, 2618 unsigned firstDataArg, FormatStringType Type, 2619 bool inFunctionCall) { 2620 2621 // CHECK: is the format string a wide literal? 2622 if (!FExpr->isAscii()) { 2623 CheckFormatHandler::EmitFormatDiagnostic( 2624 *this, inFunctionCall, Args[format_idx], 2625 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 2626 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 2627 return; 2628 } 2629 2630 // Str - The format string. NOTE: this is NOT null-terminated! 2631 StringRef StrRef = FExpr->getString(); 2632 const char *Str = StrRef.data(); 2633 unsigned StrLen = StrRef.size(); 2634 const unsigned numDataArgs = NumArgs - firstDataArg; 2635 2636 // CHECK: empty format string? 2637 if (StrLen == 0 && numDataArgs > 0) { 2638 CheckFormatHandler::EmitFormatDiagnostic( 2639 *this, inFunctionCall, Args[format_idx], 2640 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 2641 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 2642 return; 2643 } 2644 2645 if (Type == FST_Printf || Type == FST_NSString) { 2646 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 2647 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr), 2648 Str, HasVAListArg, Args, NumArgs, format_idx, 2649 inFunctionCall); 2650 2651 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 2652 getLangOpts())) 2653 H.DoneProcessing(); 2654 } else if (Type == FST_Scanf) { 2655 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 2656 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr), 2657 Str, HasVAListArg, Args, NumArgs, format_idx, 2658 inFunctionCall); 2659 2660 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 2661 getLangOpts())) 2662 H.DoneProcessing(); 2663 } // TODO: handle other formats 2664} 2665 2666//===--- CHECK: Standard memory functions ---------------------------------===// 2667 2668/// \brief Determine whether the given type is a dynamic class type (e.g., 2669/// whether it has a vtable). 2670static bool isDynamicClassType(QualType T) { 2671 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 2672 if (CXXRecordDecl *Definition = Record->getDefinition()) 2673 if (Definition->isDynamicClass()) 2674 return true; 2675 2676 return false; 2677} 2678 2679/// \brief If E is a sizeof expression, returns its argument expression, 2680/// otherwise returns NULL. 2681static const Expr *getSizeOfExprArg(const Expr* E) { 2682 if (const UnaryExprOrTypeTraitExpr *SizeOf = 2683 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 2684 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 2685 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 2686 2687 return 0; 2688} 2689 2690/// \brief If E is a sizeof expression, returns its argument type. 2691static QualType getSizeOfArgType(const Expr* E) { 2692 if (const UnaryExprOrTypeTraitExpr *SizeOf = 2693 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 2694 if (SizeOf->getKind() == clang::UETT_SizeOf) 2695 return SizeOf->getTypeOfArgument(); 2696 2697 return QualType(); 2698} 2699 2700/// \brief Check for dangerous or invalid arguments to memset(). 2701/// 2702/// This issues warnings on known problematic, dangerous or unspecified 2703/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 2704/// function calls. 2705/// 2706/// \param Call The call expression to diagnose. 2707void Sema::CheckMemaccessArguments(const CallExpr *Call, 2708 unsigned BId, 2709 IdentifierInfo *FnName) { 2710 assert(BId != 0); 2711 2712 // It is possible to have a non-standard definition of memset. Validate 2713 // we have enough arguments, and if not, abort further checking. 2714 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3); 2715 if (Call->getNumArgs() < ExpectedNumArgs) 2716 return; 2717 2718 unsigned LastArg = (BId == Builtin::BImemset || 2719 BId == Builtin::BIstrndup ? 1 : 2); 2720 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2); 2721 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 2722 2723 // We have special checking when the length is a sizeof expression. 2724 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 2725 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 2726 llvm::FoldingSetNodeID SizeOfArgID; 2727 2728 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 2729 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 2730 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 2731 2732 QualType DestTy = Dest->getType(); 2733 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 2734 QualType PointeeTy = DestPtrTy->getPointeeType(); 2735 2736 // Never warn about void type pointers. This can be used to suppress 2737 // false positives. 2738 if (PointeeTy->isVoidType()) 2739 continue; 2740 2741 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 2742 // actually comparing the expressions for equality. Because computing the 2743 // expression IDs can be expensive, we only do this if the diagnostic is 2744 // enabled. 2745 if (SizeOfArg && 2746 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess, 2747 SizeOfArg->getExprLoc())) { 2748 // We only compute IDs for expressions if the warning is enabled, and 2749 // cache the sizeof arg's ID. 2750 if (SizeOfArgID == llvm::FoldingSetNodeID()) 2751 SizeOfArg->Profile(SizeOfArgID, Context, true); 2752 llvm::FoldingSetNodeID DestID; 2753 Dest->Profile(DestID, Context, true); 2754 if (DestID == SizeOfArgID) { 2755 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 2756 // over sizeof(src) as well. 2757 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 2758 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 2759 if (UnaryOp->getOpcode() == UO_AddrOf) 2760 ActionIdx = 1; // If its an address-of operator, just remove it. 2761 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth()) 2762 ActionIdx = 2; // If the pointee's size is sizeof(char), 2763 // suggest an explicit length. 2764 unsigned DestSrcSelect = 2765 (BId == Builtin::BIstrndup ? 1 : ArgIdx); 2766 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest, 2767 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 2768 << FnName << DestSrcSelect << ActionIdx 2769 << Dest->getSourceRange() 2770 << SizeOfArg->getSourceRange()); 2771 break; 2772 } 2773 } 2774 2775 // Also check for cases where the sizeof argument is the exact same 2776 // type as the memory argument, and where it points to a user-defined 2777 // record type. 2778 if (SizeOfArgTy != QualType()) { 2779 if (PointeeTy->isRecordType() && 2780 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 2781 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 2782 PDiag(diag::warn_sizeof_pointer_type_memaccess) 2783 << FnName << SizeOfArgTy << ArgIdx 2784 << PointeeTy << Dest->getSourceRange() 2785 << LenExpr->getSourceRange()); 2786 break; 2787 } 2788 } 2789 2790 // Always complain about dynamic classes. 2791 if (isDynamicClassType(PointeeTy)) { 2792 2793 unsigned OperationType = 0; 2794 // "overwritten" if we're warning about the destination for any call 2795 // but memcmp; otherwise a verb appropriate to the call. 2796 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 2797 if (BId == Builtin::BImemcpy) 2798 OperationType = 1; 2799 else if(BId == Builtin::BImemmove) 2800 OperationType = 2; 2801 else if (BId == Builtin::BImemcmp) 2802 OperationType = 3; 2803 } 2804 2805 DiagRuntimeBehavior( 2806 Dest->getExprLoc(), Dest, 2807 PDiag(diag::warn_dyn_class_memaccess) 2808 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 2809 << FnName << PointeeTy 2810 << OperationType 2811 << Call->getCallee()->getSourceRange()); 2812 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 2813 BId != Builtin::BImemset) 2814 DiagRuntimeBehavior( 2815 Dest->getExprLoc(), Dest, 2816 PDiag(diag::warn_arc_object_memaccess) 2817 << ArgIdx << FnName << PointeeTy 2818 << Call->getCallee()->getSourceRange()); 2819 else 2820 continue; 2821 2822 DiagRuntimeBehavior( 2823 Dest->getExprLoc(), Dest, 2824 PDiag(diag::note_bad_memaccess_silence) 2825 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 2826 break; 2827 } 2828 } 2829} 2830 2831// A little helper routine: ignore addition and subtraction of integer literals. 2832// This intentionally does not ignore all integer constant expressions because 2833// we don't want to remove sizeof(). 2834static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 2835 Ex = Ex->IgnoreParenCasts(); 2836 2837 for (;;) { 2838 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 2839 if (!BO || !BO->isAdditiveOp()) 2840 break; 2841 2842 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 2843 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 2844 2845 if (isa<IntegerLiteral>(RHS)) 2846 Ex = LHS; 2847 else if (isa<IntegerLiteral>(LHS)) 2848 Ex = RHS; 2849 else 2850 break; 2851 } 2852 2853 return Ex; 2854} 2855 2856// Warn if the user has made the 'size' argument to strlcpy or strlcat 2857// be the size of the source, instead of the destination. 2858void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 2859 IdentifierInfo *FnName) { 2860 2861 // Don't crash if the user has the wrong number of arguments 2862 if (Call->getNumArgs() != 3) 2863 return; 2864 2865 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 2866 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 2867 const Expr *CompareWithSrc = NULL; 2868 2869 // Look for 'strlcpy(dst, x, sizeof(x))' 2870 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 2871 CompareWithSrc = Ex; 2872 else { 2873 // Look for 'strlcpy(dst, x, strlen(x))' 2874 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 2875 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen 2876 && SizeCall->getNumArgs() == 1) 2877 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 2878 } 2879 } 2880 2881 if (!CompareWithSrc) 2882 return; 2883 2884 // Determine if the argument to sizeof/strlen is equal to the source 2885 // argument. In principle there's all kinds of things you could do 2886 // here, for instance creating an == expression and evaluating it with 2887 // EvaluateAsBooleanCondition, but this uses a more direct technique: 2888 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 2889 if (!SrcArgDRE) 2890 return; 2891 2892 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 2893 if (!CompareWithSrcDRE || 2894 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 2895 return; 2896 2897 const Expr *OriginalSizeArg = Call->getArg(2); 2898 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 2899 << OriginalSizeArg->getSourceRange() << FnName; 2900 2901 // Output a FIXIT hint if the destination is an array (rather than a 2902 // pointer to an array). This could be enhanced to handle some 2903 // pointers if we know the actual size, like if DstArg is 'array+2' 2904 // we could say 'sizeof(array)-2'. 2905 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 2906 QualType DstArgTy = DstArg->getType(); 2907 2908 // Only handle constant-sized or VLAs, but not flexible members. 2909 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) { 2910 // Only issue the FIXIT for arrays of size > 1. 2911 if (CAT->getSize().getSExtValue() <= 1) 2912 return; 2913 } else if (!DstArgTy->isVariableArrayType()) { 2914 return; 2915 } 2916 2917 SmallString<128> sizeString; 2918 llvm::raw_svector_ostream OS(sizeString); 2919 OS << "sizeof("; 2920 DstArg->printPretty(OS, Context, 0, getPrintingPolicy()); 2921 OS << ")"; 2922 2923 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 2924 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 2925 OS.str()); 2926} 2927 2928/// Check if two expressions refer to the same declaration. 2929static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 2930 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 2931 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 2932 return D1->getDecl() == D2->getDecl(); 2933 return false; 2934} 2935 2936static const Expr *getStrlenExprArg(const Expr *E) { 2937 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 2938 const FunctionDecl *FD = CE->getDirectCallee(); 2939 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 2940 return 0; 2941 return CE->getArg(0)->IgnoreParenCasts(); 2942 } 2943 return 0; 2944} 2945 2946// Warn on anti-patterns as the 'size' argument to strncat. 2947// The correct size argument should look like following: 2948// strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 2949void Sema::CheckStrncatArguments(const CallExpr *CE, 2950 IdentifierInfo *FnName) { 2951 // Don't crash if the user has the wrong number of arguments. 2952 if (CE->getNumArgs() < 3) 2953 return; 2954 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 2955 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 2956 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 2957 2958 // Identify common expressions, which are wrongly used as the size argument 2959 // to strncat and may lead to buffer overflows. 2960 unsigned PatternType = 0; 2961 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 2962 // - sizeof(dst) 2963 if (referToTheSameDecl(SizeOfArg, DstArg)) 2964 PatternType = 1; 2965 // - sizeof(src) 2966 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 2967 PatternType = 2; 2968 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 2969 if (BE->getOpcode() == BO_Sub) { 2970 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 2971 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 2972 // - sizeof(dst) - strlen(dst) 2973 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 2974 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 2975 PatternType = 1; 2976 // - sizeof(src) - (anything) 2977 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 2978 PatternType = 2; 2979 } 2980 } 2981 2982 if (PatternType == 0) 2983 return; 2984 2985 // Generate the diagnostic. 2986 SourceLocation SL = LenArg->getLocStart(); 2987 SourceRange SR = LenArg->getSourceRange(); 2988 SourceManager &SM = PP.getSourceManager(); 2989 2990 // If the function is defined as a builtin macro, do not show macro expansion. 2991 if (SM.isMacroArgExpansion(SL)) { 2992 SL = SM.getSpellingLoc(SL); 2993 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 2994 SM.getSpellingLoc(SR.getEnd())); 2995 } 2996 2997 if (PatternType == 1) 2998 Diag(SL, diag::warn_strncat_large_size) << SR; 2999 else 3000 Diag(SL, diag::warn_strncat_src_size) << SR; 3001 3002 // Output a FIXIT hint if the destination is an array (rather than a 3003 // pointer to an array). This could be enhanced to handle some 3004 // pointers if we know the actual size, like if DstArg is 'array+2' 3005 // we could say 'sizeof(array)-2'. 3006 QualType DstArgTy = DstArg->getType(); 3007 3008 // Only handle constant-sized or VLAs, but not flexible members. 3009 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) { 3010 // Only issue the FIXIT for arrays of size > 1. 3011 if (CAT->getSize().getSExtValue() <= 1) 3012 return; 3013 } else if (!DstArgTy->isVariableArrayType()) { 3014 return; 3015 } 3016 3017 SmallString<128> sizeString; 3018 llvm::raw_svector_ostream OS(sizeString); 3019 OS << "sizeof("; 3020 DstArg->printPretty(OS, Context, 0, getPrintingPolicy()); 3021 OS << ") - "; 3022 OS << "strlen("; 3023 DstArg->printPretty(OS, Context, 0, getPrintingPolicy()); 3024 OS << ") - 1"; 3025 3026 Diag(SL, diag::note_strncat_wrong_size) 3027 << FixItHint::CreateReplacement(SR, OS.str()); 3028} 3029 3030//===--- CHECK: Return Address of Stack Variable --------------------------===// 3031 3032static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 3033 Decl *ParentDecl); 3034static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars, 3035 Decl *ParentDecl); 3036 3037/// CheckReturnStackAddr - Check if a return statement returns the address 3038/// of a stack variable. 3039void 3040Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 3041 SourceLocation ReturnLoc) { 3042 3043 Expr *stackE = 0; 3044 SmallVector<DeclRefExpr *, 8> refVars; 3045 3046 // Perform checking for returned stack addresses, local blocks, 3047 // label addresses or references to temporaries. 3048 if (lhsType->isPointerType() || 3049 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 3050 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0); 3051 } else if (lhsType->isReferenceType()) { 3052 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0); 3053 } 3054 3055 if (stackE == 0) 3056 return; // Nothing suspicious was found. 3057 3058 SourceLocation diagLoc; 3059 SourceRange diagRange; 3060 if (refVars.empty()) { 3061 diagLoc = stackE->getLocStart(); 3062 diagRange = stackE->getSourceRange(); 3063 } else { 3064 // We followed through a reference variable. 'stackE' contains the 3065 // problematic expression but we will warn at the return statement pointing 3066 // at the reference variable. We will later display the "trail" of 3067 // reference variables using notes. 3068 diagLoc = refVars[0]->getLocStart(); 3069 diagRange = refVars[0]->getSourceRange(); 3070 } 3071 3072 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var. 3073 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref 3074 : diag::warn_ret_stack_addr) 3075 << DR->getDecl()->getDeclName() << diagRange; 3076 } else if (isa<BlockExpr>(stackE)) { // local block. 3077 Diag(diagLoc, diag::err_ret_local_block) << diagRange; 3078 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 3079 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 3080 } else { // local temporary. 3081 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref 3082 : diag::warn_ret_local_temp_addr) 3083 << diagRange; 3084 } 3085 3086 // Display the "trail" of reference variables that we followed until we 3087 // found the problematic expression using notes. 3088 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 3089 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 3090 // If this var binds to another reference var, show the range of the next 3091 // var, otherwise the var binds to the problematic expression, in which case 3092 // show the range of the expression. 3093 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange() 3094 : stackE->getSourceRange(); 3095 Diag(VD->getLocation(), diag::note_ref_var_local_bind) 3096 << VD->getDeclName() << range; 3097 } 3098} 3099 3100/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 3101/// check if the expression in a return statement evaluates to an address 3102/// to a location on the stack, a local block, an address of a label, or a 3103/// reference to local temporary. The recursion is used to traverse the 3104/// AST of the return expression, with recursion backtracking when we 3105/// encounter a subexpression that (1) clearly does not lead to one of the 3106/// above problematic expressions (2) is something we cannot determine leads to 3107/// a problematic expression based on such local checking. 3108/// 3109/// Both EvalAddr and EvalVal follow through reference variables to evaluate 3110/// the expression that they point to. Such variables are added to the 3111/// 'refVars' vector so that we know what the reference variable "trail" was. 3112/// 3113/// EvalAddr processes expressions that are pointers that are used as 3114/// references (and not L-values). EvalVal handles all other values. 3115/// At the base case of the recursion is a check for the above problematic 3116/// expressions. 3117/// 3118/// This implementation handles: 3119/// 3120/// * pointer-to-pointer casts 3121/// * implicit conversions from array references to pointers 3122/// * taking the address of fields 3123/// * arbitrary interplay between "&" and "*" operators 3124/// * pointer arithmetic from an address of a stack variable 3125/// * taking the address of an array element where the array is on the stack 3126static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 3127 Decl *ParentDecl) { 3128 if (E->isTypeDependent()) 3129 return NULL; 3130 3131 // We should only be called for evaluating pointer expressions. 3132 assert((E->getType()->isAnyPointerType() || 3133 E->getType()->isBlockPointerType() || 3134 E->getType()->isObjCQualifiedIdType()) && 3135 "EvalAddr only works on pointers"); 3136 3137 E = E->IgnoreParens(); 3138 3139 // Our "symbolic interpreter" is just a dispatch off the currently 3140 // viewed AST node. We then recursively traverse the AST by calling 3141 // EvalAddr and EvalVal appropriately. 3142 switch (E->getStmtClass()) { 3143 case Stmt::DeclRefExprClass: { 3144 DeclRefExpr *DR = cast<DeclRefExpr>(E); 3145 3146 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 3147 // If this is a reference variable, follow through to the expression that 3148 // it points to. 3149 if (V->hasLocalStorage() && 3150 V->getType()->isReferenceType() && V->hasInit()) { 3151 // Add the reference variable to the "trail". 3152 refVars.push_back(DR); 3153 return EvalAddr(V->getInit(), refVars, ParentDecl); 3154 } 3155 3156 return NULL; 3157 } 3158 3159 case Stmt::UnaryOperatorClass: { 3160 // The only unary operator that make sense to handle here 3161 // is AddrOf. All others don't make sense as pointers. 3162 UnaryOperator *U = cast<UnaryOperator>(E); 3163 3164 if (U->getOpcode() == UO_AddrOf) 3165 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 3166 else 3167 return NULL; 3168 } 3169 3170 case Stmt::BinaryOperatorClass: { 3171 // Handle pointer arithmetic. All other binary operators are not valid 3172 // in this context. 3173 BinaryOperator *B = cast<BinaryOperator>(E); 3174 BinaryOperatorKind op = B->getOpcode(); 3175 3176 if (op != BO_Add && op != BO_Sub) 3177 return NULL; 3178 3179 Expr *Base = B->getLHS(); 3180 3181 // Determine which argument is the real pointer base. It could be 3182 // the RHS argument instead of the LHS. 3183 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 3184 3185 assert (Base->getType()->isPointerType()); 3186 return EvalAddr(Base, refVars, ParentDecl); 3187 } 3188 3189 // For conditional operators we need to see if either the LHS or RHS are 3190 // valid DeclRefExpr*s. If one of them is valid, we return it. 3191 case Stmt::ConditionalOperatorClass: { 3192 ConditionalOperator *C = cast<ConditionalOperator>(E); 3193 3194 // Handle the GNU extension for missing LHS. 3195 if (Expr *lhsExpr = C->getLHS()) { 3196 // In C++, we can have a throw-expression, which has 'void' type. 3197 if (!lhsExpr->getType()->isVoidType()) 3198 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl)) 3199 return LHS; 3200 } 3201 3202 // In C++, we can have a throw-expression, which has 'void' type. 3203 if (C->getRHS()->getType()->isVoidType()) 3204 return NULL; 3205 3206 return EvalAddr(C->getRHS(), refVars, ParentDecl); 3207 } 3208 3209 case Stmt::BlockExprClass: 3210 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 3211 return E; // local block. 3212 return NULL; 3213 3214 case Stmt::AddrLabelExprClass: 3215 return E; // address of label. 3216 3217 case Stmt::ExprWithCleanupsClass: 3218 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 3219 ParentDecl); 3220 3221 // For casts, we need to handle conversions from arrays to 3222 // pointer values, and pointer-to-pointer conversions. 3223 case Stmt::ImplicitCastExprClass: 3224 case Stmt::CStyleCastExprClass: 3225 case Stmt::CXXFunctionalCastExprClass: 3226 case Stmt::ObjCBridgedCastExprClass: 3227 case Stmt::CXXStaticCastExprClass: 3228 case Stmt::CXXDynamicCastExprClass: 3229 case Stmt::CXXConstCastExprClass: 3230 case Stmt::CXXReinterpretCastExprClass: { 3231 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 3232 switch (cast<CastExpr>(E)->getCastKind()) { 3233 case CK_BitCast: 3234 case CK_LValueToRValue: 3235 case CK_NoOp: 3236 case CK_BaseToDerived: 3237 case CK_DerivedToBase: 3238 case CK_UncheckedDerivedToBase: 3239 case CK_Dynamic: 3240 case CK_CPointerToObjCPointerCast: 3241 case CK_BlockPointerToObjCPointerCast: 3242 case CK_AnyPointerToBlockPointerCast: 3243 return EvalAddr(SubExpr, refVars, ParentDecl); 3244 3245 case CK_ArrayToPointerDecay: 3246 return EvalVal(SubExpr, refVars, ParentDecl); 3247 3248 default: 3249 return 0; 3250 } 3251 } 3252 3253 case Stmt::MaterializeTemporaryExprClass: 3254 if (Expr *Result = EvalAddr( 3255 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 3256 refVars, ParentDecl)) 3257 return Result; 3258 3259 return E; 3260 3261 // Everything else: we simply don't reason about them. 3262 default: 3263 return NULL; 3264 } 3265} 3266 3267 3268/// EvalVal - This function is complements EvalAddr in the mutual recursion. 3269/// See the comments for EvalAddr for more details. 3270static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 3271 Decl *ParentDecl) { 3272do { 3273 // We should only be called for evaluating non-pointer expressions, or 3274 // expressions with a pointer type that are not used as references but instead 3275 // are l-values (e.g., DeclRefExpr with a pointer type). 3276 3277 // Our "symbolic interpreter" is just a dispatch off the currently 3278 // viewed AST node. We then recursively traverse the AST by calling 3279 // EvalAddr and EvalVal appropriately. 3280 3281 E = E->IgnoreParens(); 3282 switch (E->getStmtClass()) { 3283 case Stmt::ImplicitCastExprClass: { 3284 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 3285 if (IE->getValueKind() == VK_LValue) { 3286 E = IE->getSubExpr(); 3287 continue; 3288 } 3289 return NULL; 3290 } 3291 3292 case Stmt::ExprWithCleanupsClass: 3293 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl); 3294 3295 case Stmt::DeclRefExprClass: { 3296 // When we hit a DeclRefExpr we are looking at code that refers to a 3297 // variable's name. If it's not a reference variable we check if it has 3298 // local storage within the function, and if so, return the expression. 3299 DeclRefExpr *DR = cast<DeclRefExpr>(E); 3300 3301 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 3302 // Check if it refers to itself, e.g. "int& i = i;". 3303 if (V == ParentDecl) 3304 return DR; 3305 3306 if (V->hasLocalStorage()) { 3307 if (!V->getType()->isReferenceType()) 3308 return DR; 3309 3310 // Reference variable, follow through to the expression that 3311 // it points to. 3312 if (V->hasInit()) { 3313 // Add the reference variable to the "trail". 3314 refVars.push_back(DR); 3315 return EvalVal(V->getInit(), refVars, V); 3316 } 3317 } 3318 } 3319 3320 return NULL; 3321 } 3322 3323 case Stmt::UnaryOperatorClass: { 3324 // The only unary operator that make sense to handle here 3325 // is Deref. All others don't resolve to a "name." This includes 3326 // handling all sorts of rvalues passed to a unary operator. 3327 UnaryOperator *U = cast<UnaryOperator>(E); 3328 3329 if (U->getOpcode() == UO_Deref) 3330 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 3331 3332 return NULL; 3333 } 3334 3335 case Stmt::ArraySubscriptExprClass: { 3336 // Array subscripts are potential references to data on the stack. We 3337 // retrieve the DeclRefExpr* for the array variable if it indeed 3338 // has local storage. 3339 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl); 3340 } 3341 3342 case Stmt::ConditionalOperatorClass: { 3343 // For conditional operators we need to see if either the LHS or RHS are 3344 // non-NULL Expr's. If one is non-NULL, we return it. 3345 ConditionalOperator *C = cast<ConditionalOperator>(E); 3346 3347 // Handle the GNU extension for missing LHS. 3348 if (Expr *lhsExpr = C->getLHS()) 3349 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl)) 3350 return LHS; 3351 3352 return EvalVal(C->getRHS(), refVars, ParentDecl); 3353 } 3354 3355 // Accesses to members are potential references to data on the stack. 3356 case Stmt::MemberExprClass: { 3357 MemberExpr *M = cast<MemberExpr>(E); 3358 3359 // Check for indirect access. We only want direct field accesses. 3360 if (M->isArrow()) 3361 return NULL; 3362 3363 // Check whether the member type is itself a reference, in which case 3364 // we're not going to refer to the member, but to what the member refers to. 3365 if (M->getMemberDecl()->getType()->isReferenceType()) 3366 return NULL; 3367 3368 return EvalVal(M->getBase(), refVars, ParentDecl); 3369 } 3370 3371 case Stmt::MaterializeTemporaryExprClass: 3372 if (Expr *Result = EvalVal( 3373 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 3374 refVars, ParentDecl)) 3375 return Result; 3376 3377 return E; 3378 3379 default: 3380 // Check that we don't return or take the address of a reference to a 3381 // temporary. This is only useful in C++. 3382 if (!E->isTypeDependent() && E->isRValue()) 3383 return E; 3384 3385 // Everything else: we simply don't reason about them. 3386 return NULL; 3387 } 3388} while (true); 3389} 3390 3391//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 3392 3393/// Check for comparisons of floating point operands using != and ==. 3394/// Issue a warning if these are no self-comparisons, as they are not likely 3395/// to do what the programmer intended. 3396void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 3397 bool EmitWarning = true; 3398 3399 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 3400 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 3401 3402 // Special case: check for x == x (which is OK). 3403 // Do not emit warnings for such cases. 3404 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 3405 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 3406 if (DRL->getDecl() == DRR->getDecl()) 3407 EmitWarning = false; 3408 3409 3410 // Special case: check for comparisons against literals that can be exactly 3411 // represented by APFloat. In such cases, do not emit a warning. This 3412 // is a heuristic: often comparison against such literals are used to 3413 // detect if a value in a variable has not changed. This clearly can 3414 // lead to false negatives. 3415 if (EmitWarning) { 3416 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 3417 if (FLL->isExact()) 3418 EmitWarning = false; 3419 } else 3420 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){ 3421 if (FLR->isExact()) 3422 EmitWarning = false; 3423 } 3424 } 3425 3426 // Check for comparisons with builtin types. 3427 if (EmitWarning) 3428 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 3429 if (CL->isBuiltinCall()) 3430 EmitWarning = false; 3431 3432 if (EmitWarning) 3433 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 3434 if (CR->isBuiltinCall()) 3435 EmitWarning = false; 3436 3437 // Emit the diagnostic. 3438 if (EmitWarning) 3439 Diag(Loc, diag::warn_floatingpoint_eq) 3440 << LHS->getSourceRange() << RHS->getSourceRange(); 3441} 3442 3443//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 3444//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 3445 3446namespace { 3447 3448/// Structure recording the 'active' range of an integer-valued 3449/// expression. 3450struct IntRange { 3451 /// The number of bits active in the int. 3452 unsigned Width; 3453 3454 /// True if the int is known not to have negative values. 3455 bool NonNegative; 3456 3457 IntRange(unsigned Width, bool NonNegative) 3458 : Width(Width), NonNegative(NonNegative) 3459 {} 3460 3461 /// Returns the range of the bool type. 3462 static IntRange forBoolType() { 3463 return IntRange(1, true); 3464 } 3465 3466 /// Returns the range of an opaque value of the given integral type. 3467 static IntRange forValueOfType(ASTContext &C, QualType T) { 3468 return forValueOfCanonicalType(C, 3469 T->getCanonicalTypeInternal().getTypePtr()); 3470 } 3471 3472 /// Returns the range of an opaque value of a canonical integral type. 3473 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 3474 assert(T->isCanonicalUnqualified()); 3475 3476 if (const VectorType *VT = dyn_cast<VectorType>(T)) 3477 T = VT->getElementType().getTypePtr(); 3478 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 3479 T = CT->getElementType().getTypePtr(); 3480 3481 // For enum types, use the known bit width of the enumerators. 3482 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 3483 EnumDecl *Enum = ET->getDecl(); 3484 if (!Enum->isCompleteDefinition()) 3485 return IntRange(C.getIntWidth(QualType(T, 0)), false); 3486 3487 unsigned NumPositive = Enum->getNumPositiveBits(); 3488 unsigned NumNegative = Enum->getNumNegativeBits(); 3489 3490 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0); 3491 } 3492 3493 const BuiltinType *BT = cast<BuiltinType>(T); 3494 assert(BT->isInteger()); 3495 3496 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 3497 } 3498 3499 /// Returns the "target" range of a canonical integral type, i.e. 3500 /// the range of values expressible in the type. 3501 /// 3502 /// This matches forValueOfCanonicalType except that enums have the 3503 /// full range of their type, not the range of their enumerators. 3504 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 3505 assert(T->isCanonicalUnqualified()); 3506 3507 if (const VectorType *VT = dyn_cast<VectorType>(T)) 3508 T = VT->getElementType().getTypePtr(); 3509 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 3510 T = CT->getElementType().getTypePtr(); 3511 if (const EnumType *ET = dyn_cast<EnumType>(T)) 3512 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 3513 3514 const BuiltinType *BT = cast<BuiltinType>(T); 3515 assert(BT->isInteger()); 3516 3517 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 3518 } 3519 3520 /// Returns the supremum of two ranges: i.e. their conservative merge. 3521 static IntRange join(IntRange L, IntRange R) { 3522 return IntRange(std::max(L.Width, R.Width), 3523 L.NonNegative && R.NonNegative); 3524 } 3525 3526 /// Returns the infinum of two ranges: i.e. their aggressive merge. 3527 static IntRange meet(IntRange L, IntRange R) { 3528 return IntRange(std::min(L.Width, R.Width), 3529 L.NonNegative || R.NonNegative); 3530 } 3531}; 3532 3533static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 3534 unsigned MaxWidth) { 3535 if (value.isSigned() && value.isNegative()) 3536 return IntRange(value.getMinSignedBits(), false); 3537 3538 if (value.getBitWidth() > MaxWidth) 3539 value = value.trunc(MaxWidth); 3540 3541 // isNonNegative() just checks the sign bit without considering 3542 // signedness. 3543 return IntRange(value.getActiveBits(), true); 3544} 3545 3546static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 3547 unsigned MaxWidth) { 3548 if (result.isInt()) 3549 return GetValueRange(C, result.getInt(), MaxWidth); 3550 3551 if (result.isVector()) { 3552 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 3553 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 3554 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 3555 R = IntRange::join(R, El); 3556 } 3557 return R; 3558 } 3559 3560 if (result.isComplexInt()) { 3561 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 3562 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 3563 return IntRange::join(R, I); 3564 } 3565 3566 // This can happen with lossless casts to intptr_t of "based" lvalues. 3567 // Assume it might use arbitrary bits. 3568 // FIXME: The only reason we need to pass the type in here is to get 3569 // the sign right on this one case. It would be nice if APValue 3570 // preserved this. 3571 assert(result.isLValue() || result.isAddrLabelDiff()); 3572 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 3573} 3574 3575/// Pseudo-evaluate the given integer expression, estimating the 3576/// range of values it might take. 3577/// 3578/// \param MaxWidth - the width to which the value will be truncated 3579static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { 3580 E = E->IgnoreParens(); 3581 3582 // Try a full evaluation first. 3583 Expr::EvalResult result; 3584 if (E->EvaluateAsRValue(result, C)) 3585 return GetValueRange(C, result.Val, E->getType(), MaxWidth); 3586 3587 // I think we only want to look through implicit casts here; if the 3588 // user has an explicit widening cast, we should treat the value as 3589 // being of the new, wider type. 3590 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 3591 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 3592 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 3593 3594 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType()); 3595 3596 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast); 3597 3598 // Assume that non-integer casts can span the full range of the type. 3599 if (!isIntegerCast) 3600 return OutputTypeRange; 3601 3602 IntRange SubRange 3603 = GetExprRange(C, CE->getSubExpr(), 3604 std::min(MaxWidth, OutputTypeRange.Width)); 3605 3606 // Bail out if the subexpr's range is as wide as the cast type. 3607 if (SubRange.Width >= OutputTypeRange.Width) 3608 return OutputTypeRange; 3609 3610 // Otherwise, we take the smaller width, and we're non-negative if 3611 // either the output type or the subexpr is. 3612 return IntRange(SubRange.Width, 3613 SubRange.NonNegative || OutputTypeRange.NonNegative); 3614 } 3615 3616 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3617 // If we can fold the condition, just take that operand. 3618 bool CondResult; 3619 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 3620 return GetExprRange(C, CondResult ? CO->getTrueExpr() 3621 : CO->getFalseExpr(), 3622 MaxWidth); 3623 3624 // Otherwise, conservatively merge. 3625 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 3626 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 3627 return IntRange::join(L, R); 3628 } 3629 3630 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3631 switch (BO->getOpcode()) { 3632 3633 // Boolean-valued operations are single-bit and positive. 3634 case BO_LAnd: 3635 case BO_LOr: 3636 case BO_LT: 3637 case BO_GT: 3638 case BO_LE: 3639 case BO_GE: 3640 case BO_EQ: 3641 case BO_NE: 3642 return IntRange::forBoolType(); 3643 3644 // The type of the assignments is the type of the LHS, so the RHS 3645 // is not necessarily the same type. 3646 case BO_MulAssign: 3647 case BO_DivAssign: 3648 case BO_RemAssign: 3649 case BO_AddAssign: 3650 case BO_SubAssign: 3651 case BO_XorAssign: 3652 case BO_OrAssign: 3653 // TODO: bitfields? 3654 return IntRange::forValueOfType(C, E->getType()); 3655 3656 // Simple assignments just pass through the RHS, which will have 3657 // been coerced to the LHS type. 3658 case BO_Assign: 3659 // TODO: bitfields? 3660 return GetExprRange(C, BO->getRHS(), MaxWidth); 3661 3662 // Operations with opaque sources are black-listed. 3663 case BO_PtrMemD: 3664 case BO_PtrMemI: 3665 return IntRange::forValueOfType(C, E->getType()); 3666 3667 // Bitwise-and uses the *infinum* of the two source ranges. 3668 case BO_And: 3669 case BO_AndAssign: 3670 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 3671 GetExprRange(C, BO->getRHS(), MaxWidth)); 3672 3673 // Left shift gets black-listed based on a judgement call. 3674 case BO_Shl: 3675 // ...except that we want to treat '1 << (blah)' as logically 3676 // positive. It's an important idiom. 3677 if (IntegerLiteral *I 3678 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 3679 if (I->getValue() == 1) { 3680 IntRange R = IntRange::forValueOfType(C, E->getType()); 3681 return IntRange(R.Width, /*NonNegative*/ true); 3682 } 3683 } 3684 // fallthrough 3685 3686 case BO_ShlAssign: 3687 return IntRange::forValueOfType(C, E->getType()); 3688 3689 // Right shift by a constant can narrow its left argument. 3690 case BO_Shr: 3691 case BO_ShrAssign: { 3692 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 3693 3694 // If the shift amount is a positive constant, drop the width by 3695 // that much. 3696 llvm::APSInt shift; 3697 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 3698 shift.isNonNegative()) { 3699 unsigned zext = shift.getZExtValue(); 3700 if (zext >= L.Width) 3701 L.Width = (L.NonNegative ? 0 : 1); 3702 else 3703 L.Width -= zext; 3704 } 3705 3706 return L; 3707 } 3708 3709 // Comma acts as its right operand. 3710 case BO_Comma: 3711 return GetExprRange(C, BO->getRHS(), MaxWidth); 3712 3713 // Black-list pointer subtractions. 3714 case BO_Sub: 3715 if (BO->getLHS()->getType()->isPointerType()) 3716 return IntRange::forValueOfType(C, E->getType()); 3717 break; 3718 3719 // The width of a division result is mostly determined by the size 3720 // of the LHS. 3721 case BO_Div: { 3722 // Don't 'pre-truncate' the operands. 3723 unsigned opWidth = C.getIntWidth(E->getType()); 3724 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 3725 3726 // If the divisor is constant, use that. 3727 llvm::APSInt divisor; 3728 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 3729 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 3730 if (log2 >= L.Width) 3731 L.Width = (L.NonNegative ? 0 : 1); 3732 else 3733 L.Width = std::min(L.Width - log2, MaxWidth); 3734 return L; 3735 } 3736 3737 // Otherwise, just use the LHS's width. 3738 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 3739 return IntRange(L.Width, L.NonNegative && R.NonNegative); 3740 } 3741 3742 // The result of a remainder can't be larger than the result of 3743 // either side. 3744 case BO_Rem: { 3745 // Don't 'pre-truncate' the operands. 3746 unsigned opWidth = C.getIntWidth(E->getType()); 3747 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 3748 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 3749 3750 IntRange meet = IntRange::meet(L, R); 3751 meet.Width = std::min(meet.Width, MaxWidth); 3752 return meet; 3753 } 3754 3755 // The default behavior is okay for these. 3756 case BO_Mul: 3757 case BO_Add: 3758 case BO_Xor: 3759 case BO_Or: 3760 break; 3761 } 3762 3763 // The default case is to treat the operation as if it were closed 3764 // on the narrowest type that encompasses both operands. 3765 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 3766 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 3767 return IntRange::join(L, R); 3768 } 3769 3770 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 3771 switch (UO->getOpcode()) { 3772 // Boolean-valued operations are white-listed. 3773 case UO_LNot: 3774 return IntRange::forBoolType(); 3775 3776 // Operations with opaque sources are black-listed. 3777 case UO_Deref: 3778 case UO_AddrOf: // should be impossible 3779 return IntRange::forValueOfType(C, E->getType()); 3780 3781 default: 3782 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 3783 } 3784 } 3785 3786 if (dyn_cast<OffsetOfExpr>(E)) { 3787 IntRange::forValueOfType(C, E->getType()); 3788 } 3789 3790 if (FieldDecl *BitField = E->getBitField()) 3791 return IntRange(BitField->getBitWidthValue(C), 3792 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 3793 3794 return IntRange::forValueOfType(C, E->getType()); 3795} 3796 3797static IntRange GetExprRange(ASTContext &C, Expr *E) { 3798 return GetExprRange(C, E, C.getIntWidth(E->getType())); 3799} 3800 3801/// Checks whether the given value, which currently has the given 3802/// source semantics, has the same value when coerced through the 3803/// target semantics. 3804static bool IsSameFloatAfterCast(const llvm::APFloat &value, 3805 const llvm::fltSemantics &Src, 3806 const llvm::fltSemantics &Tgt) { 3807 llvm::APFloat truncated = value; 3808 3809 bool ignored; 3810 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 3811 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 3812 3813 return truncated.bitwiseIsEqual(value); 3814} 3815 3816/// Checks whether the given value, which currently has the given 3817/// source semantics, has the same value when coerced through the 3818/// target semantics. 3819/// 3820/// The value might be a vector of floats (or a complex number). 3821static bool IsSameFloatAfterCast(const APValue &value, 3822 const llvm::fltSemantics &Src, 3823 const llvm::fltSemantics &Tgt) { 3824 if (value.isFloat()) 3825 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 3826 3827 if (value.isVector()) { 3828 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 3829 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 3830 return false; 3831 return true; 3832 } 3833 3834 assert(value.isComplexFloat()); 3835 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 3836 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 3837} 3838 3839static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 3840 3841static bool IsZero(Sema &S, Expr *E) { 3842 // Suppress cases where we are comparing against an enum constant. 3843 if (const DeclRefExpr *DR = 3844 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 3845 if (isa<EnumConstantDecl>(DR->getDecl())) 3846 return false; 3847 3848 // Suppress cases where the '0' value is expanded from a macro. 3849 if (E->getLocStart().isMacroID()) 3850 return false; 3851 3852 llvm::APSInt Value; 3853 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 3854} 3855 3856static bool HasEnumType(Expr *E) { 3857 // Strip off implicit integral promotions. 3858 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 3859 if (ICE->getCastKind() != CK_IntegralCast && 3860 ICE->getCastKind() != CK_NoOp) 3861 break; 3862 E = ICE->getSubExpr(); 3863 } 3864 3865 return E->getType()->isEnumeralType(); 3866} 3867 3868static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 3869 BinaryOperatorKind op = E->getOpcode(); 3870 if (E->isValueDependent()) 3871 return; 3872 3873 if (op == BO_LT && IsZero(S, E->getRHS())) { 3874 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 3875 << "< 0" << "false" << HasEnumType(E->getLHS()) 3876 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3877 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 3878 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 3879 << ">= 0" << "true" << HasEnumType(E->getLHS()) 3880 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3881 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 3882 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 3883 << "0 >" << "false" << HasEnumType(E->getRHS()) 3884 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3885 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 3886 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 3887 << "0 <=" << "true" << HasEnumType(E->getRHS()) 3888 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3889 } 3890} 3891 3892/// Analyze the operands of the given comparison. Implements the 3893/// fallback case from AnalyzeComparison. 3894static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 3895 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 3896 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 3897} 3898 3899/// \brief Implements -Wsign-compare. 3900/// 3901/// \param E the binary operator to check for warnings 3902static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 3903 // The type the comparison is being performed in. 3904 QualType T = E->getLHS()->getType(); 3905 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()) 3906 && "comparison with mismatched types"); 3907 3908 // We don't do anything special if this isn't an unsigned integral 3909 // comparison: we're only interested in integral comparisons, and 3910 // signed comparisons only happen in cases we don't care to warn about. 3911 // 3912 // We also don't care about value-dependent expressions or expressions 3913 // whose result is a constant. 3914 if (!T->hasUnsignedIntegerRepresentation() 3915 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context)) 3916 return AnalyzeImpConvsInComparison(S, E); 3917 3918 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 3919 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 3920 3921 // Check to see if one of the (unmodified) operands is of different 3922 // signedness. 3923 Expr *signedOperand, *unsignedOperand; 3924 if (LHS->getType()->hasSignedIntegerRepresentation()) { 3925 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 3926 "unsigned comparison between two signed integer expressions?"); 3927 signedOperand = LHS; 3928 unsignedOperand = RHS; 3929 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 3930 signedOperand = RHS; 3931 unsignedOperand = LHS; 3932 } else { 3933 CheckTrivialUnsignedComparison(S, E); 3934 return AnalyzeImpConvsInComparison(S, E); 3935 } 3936 3937 // Otherwise, calculate the effective range of the signed operand. 3938 IntRange signedRange = GetExprRange(S.Context, signedOperand); 3939 3940 // Go ahead and analyze implicit conversions in the operands. Note 3941 // that we skip the implicit conversions on both sides. 3942 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 3943 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 3944 3945 // If the signed range is non-negative, -Wsign-compare won't fire, 3946 // but we should still check for comparisons which are always true 3947 // or false. 3948 if (signedRange.NonNegative) 3949 return CheckTrivialUnsignedComparison(S, E); 3950 3951 // For (in)equality comparisons, if the unsigned operand is a 3952 // constant which cannot collide with a overflowed signed operand, 3953 // then reinterpreting the signed operand as unsigned will not 3954 // change the result of the comparison. 3955 if (E->isEqualityOp()) { 3956 unsigned comparisonWidth = S.Context.getIntWidth(T); 3957 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 3958 3959 // We should never be unable to prove that the unsigned operand is 3960 // non-negative. 3961 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 3962 3963 if (unsignedRange.Width < comparisonWidth) 3964 return; 3965 } 3966 3967 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 3968 S.PDiag(diag::warn_mixed_sign_comparison) 3969 << LHS->getType() << RHS->getType() 3970 << LHS->getSourceRange() << RHS->getSourceRange()); 3971} 3972 3973/// Analyzes an attempt to assign the given value to a bitfield. 3974/// 3975/// Returns true if there was something fishy about the attempt. 3976static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 3977 SourceLocation InitLoc) { 3978 assert(Bitfield->isBitField()); 3979 if (Bitfield->isInvalidDecl()) 3980 return false; 3981 3982 // White-list bool bitfields. 3983 if (Bitfield->getType()->isBooleanType()) 3984 return false; 3985 3986 // Ignore value- or type-dependent expressions. 3987 if (Bitfield->getBitWidth()->isValueDependent() || 3988 Bitfield->getBitWidth()->isTypeDependent() || 3989 Init->isValueDependent() || 3990 Init->isTypeDependent()) 3991 return false; 3992 3993 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 3994 3995 llvm::APSInt Value; 3996 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 3997 return false; 3998 3999 unsigned OriginalWidth = Value.getBitWidth(); 4000 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 4001 4002 if (OriginalWidth <= FieldWidth) 4003 return false; 4004 4005 // Compute the value which the bitfield will contain. 4006 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 4007 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType()); 4008 4009 // Check whether the stored value is equal to the original value. 4010 TruncatedValue = TruncatedValue.extend(OriginalWidth); 4011 if (Value == TruncatedValue) 4012 return false; 4013 4014 // Special-case bitfields of width 1: booleans are naturally 0/1, and 4015 // therefore don't strictly fit into a signed bitfield of width 1. 4016 if (FieldWidth == 1 && Value == 1) 4017 return false; 4018 4019 std::string PrettyValue = Value.toString(10); 4020 std::string PrettyTrunc = TruncatedValue.toString(10); 4021 4022 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 4023 << PrettyValue << PrettyTrunc << OriginalInit->getType() 4024 << Init->getSourceRange(); 4025 4026 return true; 4027} 4028 4029/// Analyze the given simple or compound assignment for warning-worthy 4030/// operations. 4031static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 4032 // Just recurse on the LHS. 4033 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 4034 4035 // We want to recurse on the RHS as normal unless we're assigning to 4036 // a bitfield. 4037 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) { 4038 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 4039 E->getOperatorLoc())) { 4040 // Recurse, ignoring any implicit conversions on the RHS. 4041 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 4042 E->getOperatorLoc()); 4043 } 4044 } 4045 4046 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 4047} 4048 4049/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 4050static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 4051 SourceLocation CContext, unsigned diag, 4052 bool pruneControlFlow = false) { 4053 if (pruneControlFlow) { 4054 S.DiagRuntimeBehavior(E->getExprLoc(), E, 4055 S.PDiag(diag) 4056 << SourceType << T << E->getSourceRange() 4057 << SourceRange(CContext)); 4058 return; 4059 } 4060 S.Diag(E->getExprLoc(), diag) 4061 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 4062} 4063 4064/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 4065static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 4066 SourceLocation CContext, unsigned diag, 4067 bool pruneControlFlow = false) { 4068 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 4069} 4070 4071/// Diagnose an implicit cast from a literal expression. Does not warn when the 4072/// cast wouldn't lose information. 4073void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T, 4074 SourceLocation CContext) { 4075 // Try to convert the literal exactly to an integer. If we can, don't warn. 4076 bool isExact = false; 4077 const llvm::APFloat &Value = FL->getValue(); 4078 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 4079 T->hasUnsignedIntegerRepresentation()); 4080 if (Value.convertToInteger(IntegerValue, 4081 llvm::APFloat::rmTowardZero, &isExact) 4082 == llvm::APFloat::opOK && isExact) 4083 return; 4084 4085 SmallString<16> PrettySourceValue; 4086 Value.toString(PrettySourceValue); 4087 std::string PrettyTargetValue; 4088 if (T->isSpecificBuiltinType(BuiltinType::Bool)) 4089 PrettyTargetValue = IntegerValue == 0 ? "false" : "true"; 4090 else 4091 PrettyTargetValue = IntegerValue.toString(10); 4092 4093 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer) 4094 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue 4095 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext); 4096} 4097 4098std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 4099 if (!Range.Width) return "0"; 4100 4101 llvm::APSInt ValueInRange = Value; 4102 ValueInRange.setIsSigned(!Range.NonNegative); 4103 ValueInRange = ValueInRange.trunc(Range.Width); 4104 return ValueInRange.toString(10); 4105} 4106 4107void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 4108 SourceLocation CC, bool *ICContext = 0) { 4109 if (E->isTypeDependent() || E->isValueDependent()) return; 4110 4111 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 4112 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 4113 if (Source == Target) return; 4114 if (Target->isDependentType()) return; 4115 4116 // If the conversion context location is invalid don't complain. We also 4117 // don't want to emit a warning if the issue occurs from the expansion of 4118 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 4119 // delay this check as long as possible. Once we detect we are in that 4120 // scenario, we just return. 4121 if (CC.isInvalid()) 4122 return; 4123 4124 // Diagnose implicit casts to bool. 4125 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 4126 if (isa<StringLiteral>(E)) 4127 // Warn on string literal to bool. Checks for string literals in logical 4128 // expressions, for instances, assert(0 && "error here"), is prevented 4129 // by a check in AnalyzeImplicitConversions(). 4130 return DiagnoseImpCast(S, E, T, CC, 4131 diag::warn_impcast_string_literal_to_bool); 4132 if (Source->isFunctionType()) { 4133 // Warn on function to bool. Checks free functions and static member 4134 // functions. Weakly imported functions are excluded from the check, 4135 // since it's common to test their value to check whether the linker 4136 // found a definition for them. 4137 ValueDecl *D = 0; 4138 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) { 4139 D = R->getDecl(); 4140 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 4141 D = M->getMemberDecl(); 4142 } 4143 4144 if (D && !D->isWeak()) { 4145 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) { 4146 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool) 4147 << F << E->getSourceRange() << SourceRange(CC); 4148 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence) 4149 << FixItHint::CreateInsertion(E->getExprLoc(), "&"); 4150 QualType ReturnType; 4151 UnresolvedSet<4> NonTemplateOverloads; 4152 S.isExprCallable(*E, ReturnType, NonTemplateOverloads); 4153 if (!ReturnType.isNull() 4154 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 4155 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call) 4156 << FixItHint::CreateInsertion( 4157 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()"); 4158 return; 4159 } 4160 } 4161 } 4162 } 4163 4164 // Strip vector types. 4165 if (isa<VectorType>(Source)) { 4166 if (!isa<VectorType>(Target)) { 4167 if (S.SourceMgr.isInSystemMacro(CC)) 4168 return; 4169 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 4170 } 4171 4172 // If the vector cast is cast between two vectors of the same size, it is 4173 // a bitcast, not a conversion. 4174 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 4175 return; 4176 4177 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 4178 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 4179 } 4180 4181 // Strip complex types. 4182 if (isa<ComplexType>(Source)) { 4183 if (!isa<ComplexType>(Target)) { 4184 if (S.SourceMgr.isInSystemMacro(CC)) 4185 return; 4186 4187 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 4188 } 4189 4190 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 4191 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 4192 } 4193 4194 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 4195 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 4196 4197 // If the source is floating point... 4198 if (SourceBT && SourceBT->isFloatingPoint()) { 4199 // ...and the target is floating point... 4200 if (TargetBT && TargetBT->isFloatingPoint()) { 4201 // ...then warn if we're dropping FP rank. 4202 4203 // Builtin FP kinds are ordered by increasing FP rank. 4204 if (SourceBT->getKind() > TargetBT->getKind()) { 4205 // Don't warn about float constants that are precisely 4206 // representable in the target type. 4207 Expr::EvalResult result; 4208 if (E->EvaluateAsRValue(result, S.Context)) { 4209 // Value might be a float, a float vector, or a float complex. 4210 if (IsSameFloatAfterCast(result.Val, 4211 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 4212 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 4213 return; 4214 } 4215 4216 if (S.SourceMgr.isInSystemMacro(CC)) 4217 return; 4218 4219 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 4220 } 4221 return; 4222 } 4223 4224 // If the target is integral, always warn. 4225 if (TargetBT && TargetBT->isInteger()) { 4226 if (S.SourceMgr.isInSystemMacro(CC)) 4227 return; 4228 4229 Expr *InnerE = E->IgnoreParenImpCasts(); 4230 // We also want to warn on, e.g., "int i = -1.234" 4231 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 4232 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 4233 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 4234 4235 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) { 4236 DiagnoseFloatingLiteralImpCast(S, FL, T, CC); 4237 } else { 4238 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer); 4239 } 4240 } 4241 4242 return; 4243 } 4244 4245 if (!Source->isIntegerType() || !Target->isIntegerType()) 4246 return; 4247 4248 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) 4249 == Expr::NPCK_GNUNull) && Target->isIntegerType()) { 4250 SourceLocation Loc = E->getSourceRange().getBegin(); 4251 if (Loc.isMacroID()) 4252 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 4253 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 4254 << T << clang::SourceRange(CC) 4255 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T)); 4256 return; 4257 } 4258 4259 // TODO: remove this early return once the false positives for constant->bool 4260 // in templates, macros, etc, are reduced or removed. 4261 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 4262 return; 4263 4264 IntRange SourceRange = GetExprRange(S.Context, E); 4265 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 4266 4267 if (SourceRange.Width > TargetRange.Width) { 4268 // If the source is a constant, use a default-on diagnostic. 4269 // TODO: this should happen for bitfield stores, too. 4270 llvm::APSInt Value(32); 4271 if (E->isIntegerConstantExpr(Value, S.Context)) { 4272 if (S.SourceMgr.isInSystemMacro(CC)) 4273 return; 4274 4275 std::string PrettySourceValue = Value.toString(10); 4276 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 4277 4278 S.DiagRuntimeBehavior(E->getExprLoc(), E, 4279 S.PDiag(diag::warn_impcast_integer_precision_constant) 4280 << PrettySourceValue << PrettyTargetValue 4281 << E->getType() << T << E->getSourceRange() 4282 << clang::SourceRange(CC)); 4283 return; 4284 } 4285 4286 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 4287 if (S.SourceMgr.isInSystemMacro(CC)) 4288 return; 4289 4290 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 4291 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 4292 /* pruneControlFlow */ true); 4293 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 4294 } 4295 4296 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 4297 (!TargetRange.NonNegative && SourceRange.NonNegative && 4298 SourceRange.Width == TargetRange.Width)) { 4299 4300 if (S.SourceMgr.isInSystemMacro(CC)) 4301 return; 4302 4303 unsigned DiagID = diag::warn_impcast_integer_sign; 4304 4305 // Traditionally, gcc has warned about this under -Wsign-compare. 4306 // We also want to warn about it in -Wconversion. 4307 // So if -Wconversion is off, use a completely identical diagnostic 4308 // in the sign-compare group. 4309 // The conditional-checking code will 4310 if (ICContext) { 4311 DiagID = diag::warn_impcast_integer_sign_conditional; 4312 *ICContext = true; 4313 } 4314 4315 return DiagnoseImpCast(S, E, T, CC, DiagID); 4316 } 4317 4318 // Diagnose conversions between different enumeration types. 4319 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 4320 // type, to give us better diagnostics. 4321 QualType SourceType = E->getType(); 4322 if (!S.getLangOpts().CPlusPlus) { 4323 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 4324 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 4325 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 4326 SourceType = S.Context.getTypeDeclType(Enum); 4327 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 4328 } 4329 } 4330 4331 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 4332 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 4333 if ((SourceEnum->getDecl()->getIdentifier() || 4334 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) && 4335 (TargetEnum->getDecl()->getIdentifier() || 4336 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) && 4337 SourceEnum != TargetEnum) { 4338 if (S.SourceMgr.isInSystemMacro(CC)) 4339 return; 4340 4341 return DiagnoseImpCast(S, E, SourceType, T, CC, 4342 diag::warn_impcast_different_enum_types); 4343 } 4344 4345 return; 4346} 4347 4348void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T); 4349 4350void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 4351 SourceLocation CC, bool &ICContext) { 4352 E = E->IgnoreParenImpCasts(); 4353 4354 if (isa<ConditionalOperator>(E)) 4355 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T); 4356 4357 AnalyzeImplicitConversions(S, E, CC); 4358 if (E->getType() != T) 4359 return CheckImplicitConversion(S, E, T, CC, &ICContext); 4360 return; 4361} 4362 4363void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) { 4364 SourceLocation CC = E->getQuestionLoc(); 4365 4366 AnalyzeImplicitConversions(S, E->getCond(), CC); 4367 4368 bool Suspicious = false; 4369 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 4370 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 4371 4372 // If -Wconversion would have warned about either of the candidates 4373 // for a signedness conversion to the context type... 4374 if (!Suspicious) return; 4375 4376 // ...but it's currently ignored... 4377 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional, 4378 CC)) 4379 return; 4380 4381 // ...then check whether it would have warned about either of the 4382 // candidates for a signedness conversion to the condition type. 4383 if (E->getType() == T) return; 4384 4385 Suspicious = false; 4386 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 4387 E->getType(), CC, &Suspicious); 4388 if (!Suspicious) 4389 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 4390 E->getType(), CC, &Suspicious); 4391} 4392 4393/// AnalyzeImplicitConversions - Find and report any interesting 4394/// implicit conversions in the given expression. There are a couple 4395/// of competing diagnostics here, -Wconversion and -Wsign-compare. 4396void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 4397 QualType T = OrigE->getType(); 4398 Expr *E = OrigE->IgnoreParenImpCasts(); 4399 4400 if (E->isTypeDependent() || E->isValueDependent()) 4401 return; 4402 4403 // For conditional operators, we analyze the arguments as if they 4404 // were being fed directly into the output. 4405 if (isa<ConditionalOperator>(E)) { 4406 ConditionalOperator *CO = cast<ConditionalOperator>(E); 4407 CheckConditionalOperator(S, CO, T); 4408 return; 4409 } 4410 4411 // Go ahead and check any implicit conversions we might have skipped. 4412 // The non-canonical typecheck is just an optimization; 4413 // CheckImplicitConversion will filter out dead implicit conversions. 4414 if (E->getType() != T) 4415 CheckImplicitConversion(S, E, T, CC); 4416 4417 // Now continue drilling into this expression. 4418 4419 // Skip past explicit casts. 4420 if (isa<ExplicitCastExpr>(E)) { 4421 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 4422 return AnalyzeImplicitConversions(S, E, CC); 4423 } 4424 4425 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 4426 // Do a somewhat different check with comparison operators. 4427 if (BO->isComparisonOp()) 4428 return AnalyzeComparison(S, BO); 4429 4430 // And with simple assignments. 4431 if (BO->getOpcode() == BO_Assign) 4432 return AnalyzeAssignment(S, BO); 4433 } 4434 4435 // These break the otherwise-useful invariant below. Fortunately, 4436 // we don't really need to recurse into them, because any internal 4437 // expressions should have been analyzed already when they were 4438 // built into statements. 4439 if (isa<StmtExpr>(E)) return; 4440 4441 // Don't descend into unevaluated contexts. 4442 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 4443 4444 // Now just recurse over the expression's children. 4445 CC = E->getExprLoc(); 4446 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 4447 bool IsLogicalOperator = BO && BO->isLogicalOp(); 4448 for (Stmt::child_range I = E->children(); I; ++I) { 4449 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I); 4450 if (!ChildExpr) 4451 continue; 4452 4453 if (IsLogicalOperator && 4454 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 4455 // Ignore checking string literals that are in logical operators. 4456 continue; 4457 AnalyzeImplicitConversions(S, ChildExpr, CC); 4458 } 4459} 4460 4461} // end anonymous namespace 4462 4463/// Diagnoses "dangerous" implicit conversions within the given 4464/// expression (which is a full expression). Implements -Wconversion 4465/// and -Wsign-compare. 4466/// 4467/// \param CC the "context" location of the implicit conversion, i.e. 4468/// the most location of the syntactic entity requiring the implicit 4469/// conversion 4470void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 4471 // Don't diagnose in unevaluated contexts. 4472 if (ExprEvalContexts.back().Context == Sema::Unevaluated) 4473 return; 4474 4475 // Don't diagnose for value- or type-dependent expressions. 4476 if (E->isTypeDependent() || E->isValueDependent()) 4477 return; 4478 4479 // Check for array bounds violations in cases where the check isn't triggered 4480 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 4481 // ArraySubscriptExpr is on the RHS of a variable initialization. 4482 CheckArrayAccess(E); 4483 4484 // This is not the right CC for (e.g.) a variable initialization. 4485 AnalyzeImplicitConversions(*this, E, CC); 4486} 4487 4488void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 4489 FieldDecl *BitField, 4490 Expr *Init) { 4491 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 4492} 4493 4494/// CheckParmsForFunctionDef - Check that the parameters of the given 4495/// function are appropriate for the definition of a function. This 4496/// takes care of any checks that cannot be performed on the 4497/// declaration itself, e.g., that the types of each of the function 4498/// parameters are complete. 4499bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd, 4500 bool CheckParameterNames) { 4501 bool HasInvalidParm = false; 4502 for (; P != PEnd; ++P) { 4503 ParmVarDecl *Param = *P; 4504 4505 // C99 6.7.5.3p4: the parameters in a parameter type list in a 4506 // function declarator that is part of a function definition of 4507 // that function shall not have incomplete type. 4508 // 4509 // This is also C++ [dcl.fct]p6. 4510 if (!Param->isInvalidDecl() && 4511 RequireCompleteType(Param->getLocation(), Param->getType(), 4512 diag::err_typecheck_decl_incomplete_type)) { 4513 Param->setInvalidDecl(); 4514 HasInvalidParm = true; 4515 } 4516 4517 // C99 6.9.1p5: If the declarator includes a parameter type list, the 4518 // declaration of each parameter shall include an identifier. 4519 if (CheckParameterNames && 4520 Param->getIdentifier() == 0 && 4521 !Param->isImplicit() && 4522 !getLangOpts().CPlusPlus) 4523 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 4524 4525 // C99 6.7.5.3p12: 4526 // If the function declarator is not part of a definition of that 4527 // function, parameters may have incomplete type and may use the [*] 4528 // notation in their sequences of declarator specifiers to specify 4529 // variable length array types. 4530 QualType PType = Param->getOriginalType(); 4531 if (const ArrayType *AT = Context.getAsArrayType(PType)) { 4532 if (AT->getSizeModifier() == ArrayType::Star) { 4533 // FIXME: This diagnosic should point the the '[*]' if source-location 4534 // information is added for it. 4535 Diag(Param->getLocation(), diag::err_array_star_in_function_definition); 4536 } 4537 } 4538 } 4539 4540 return HasInvalidParm; 4541} 4542 4543/// CheckCastAlign - Implements -Wcast-align, which warns when a 4544/// pointer cast increases the alignment requirements. 4545void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 4546 // This is actually a lot of work to potentially be doing on every 4547 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 4548 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align, 4549 TRange.getBegin()) 4550 == DiagnosticsEngine::Ignored) 4551 return; 4552 4553 // Ignore dependent types. 4554 if (T->isDependentType() || Op->getType()->isDependentType()) 4555 return; 4556 4557 // Require that the destination be a pointer type. 4558 const PointerType *DestPtr = T->getAs<PointerType>(); 4559 if (!DestPtr) return; 4560 4561 // If the destination has alignment 1, we're done. 4562 QualType DestPointee = DestPtr->getPointeeType(); 4563 if (DestPointee->isIncompleteType()) return; 4564 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 4565 if (DestAlign.isOne()) return; 4566 4567 // Require that the source be a pointer type. 4568 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 4569 if (!SrcPtr) return; 4570 QualType SrcPointee = SrcPtr->getPointeeType(); 4571 4572 // Whitelist casts from cv void*. We already implicitly 4573 // whitelisted casts to cv void*, since they have alignment 1. 4574 // Also whitelist casts involving incomplete types, which implicitly 4575 // includes 'void'. 4576 if (SrcPointee->isIncompleteType()) return; 4577 4578 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 4579 if (SrcAlign >= DestAlign) return; 4580 4581 Diag(TRange.getBegin(), diag::warn_cast_align) 4582 << Op->getType() << T 4583 << static_cast<unsigned>(SrcAlign.getQuantity()) 4584 << static_cast<unsigned>(DestAlign.getQuantity()) 4585 << TRange << Op->getSourceRange(); 4586} 4587 4588static const Type* getElementType(const Expr *BaseExpr) { 4589 const Type* EltType = BaseExpr->getType().getTypePtr(); 4590 if (EltType->isAnyPointerType()) 4591 return EltType->getPointeeType().getTypePtr(); 4592 else if (EltType->isArrayType()) 4593 return EltType->getBaseElementTypeUnsafe(); 4594 return EltType; 4595} 4596 4597/// \brief Check whether this array fits the idiom of a size-one tail padded 4598/// array member of a struct. 4599/// 4600/// We avoid emitting out-of-bounds access warnings for such arrays as they are 4601/// commonly used to emulate flexible arrays in C89 code. 4602static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size, 4603 const NamedDecl *ND) { 4604 if (Size != 1 || !ND) return false; 4605 4606 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 4607 if (!FD) return false; 4608 4609 // Don't consider sizes resulting from macro expansions or template argument 4610 // substitution to form C89 tail-padded arrays. 4611 4612 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 4613 while (TInfo) { 4614 TypeLoc TL = TInfo->getTypeLoc(); 4615 // Look through typedefs. 4616 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL); 4617 if (TTL) { 4618 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl(); 4619 TInfo = TDL->getTypeSourceInfo(); 4620 continue; 4621 } 4622 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL); 4623 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 4624 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 4625 return false; 4626 break; 4627 } 4628 4629 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 4630 if (!RD) return false; 4631 if (RD->isUnion()) return false; 4632 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 4633 if (!CRD->isStandardLayout()) return false; 4634 } 4635 4636 // See if this is the last field decl in the record. 4637 const Decl *D = FD; 4638 while ((D = D->getNextDeclInContext())) 4639 if (isa<FieldDecl>(D)) 4640 return false; 4641 return true; 4642} 4643 4644void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 4645 const ArraySubscriptExpr *ASE, 4646 bool AllowOnePastEnd, bool IndexNegated) { 4647 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 4648 if (IndexExpr->isValueDependent()) 4649 return; 4650 4651 const Type *EffectiveType = getElementType(BaseExpr); 4652 BaseExpr = BaseExpr->IgnoreParenCasts(); 4653 const ConstantArrayType *ArrayTy = 4654 Context.getAsConstantArrayType(BaseExpr->getType()); 4655 if (!ArrayTy) 4656 return; 4657 4658 llvm::APSInt index; 4659 if (!IndexExpr->EvaluateAsInt(index, Context)) 4660 return; 4661 if (IndexNegated) 4662 index = -index; 4663 4664 const NamedDecl *ND = NULL; 4665 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 4666 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 4667 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 4668 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 4669 4670 if (index.isUnsigned() || !index.isNegative()) { 4671 llvm::APInt size = ArrayTy->getSize(); 4672 if (!size.isStrictlyPositive()) 4673 return; 4674 4675 const Type* BaseType = getElementType(BaseExpr); 4676 if (BaseType != EffectiveType) { 4677 // Make sure we're comparing apples to apples when comparing index to size 4678 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 4679 uint64_t array_typesize = Context.getTypeSize(BaseType); 4680 // Handle ptrarith_typesize being zero, such as when casting to void* 4681 if (!ptrarith_typesize) ptrarith_typesize = 1; 4682 if (ptrarith_typesize != array_typesize) { 4683 // There's a cast to a different size type involved 4684 uint64_t ratio = array_typesize / ptrarith_typesize; 4685 // TODO: Be smarter about handling cases where array_typesize is not a 4686 // multiple of ptrarith_typesize 4687 if (ptrarith_typesize * ratio == array_typesize) 4688 size *= llvm::APInt(size.getBitWidth(), ratio); 4689 } 4690 } 4691 4692 if (size.getBitWidth() > index.getBitWidth()) 4693 index = index.zext(size.getBitWidth()); 4694 else if (size.getBitWidth() < index.getBitWidth()) 4695 size = size.zext(index.getBitWidth()); 4696 4697 // For array subscripting the index must be less than size, but for pointer 4698 // arithmetic also allow the index (offset) to be equal to size since 4699 // computing the next address after the end of the array is legal and 4700 // commonly done e.g. in C++ iterators and range-based for loops. 4701 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 4702 return; 4703 4704 // Also don't warn for arrays of size 1 which are members of some 4705 // structure. These are often used to approximate flexible arrays in C89 4706 // code. 4707 if (IsTailPaddedMemberArray(*this, size, ND)) 4708 return; 4709 4710 // Suppress the warning if the subscript expression (as identified by the 4711 // ']' location) and the index expression are both from macro expansions 4712 // within a system header. 4713 if (ASE) { 4714 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 4715 ASE->getRBracketLoc()); 4716 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 4717 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 4718 IndexExpr->getLocStart()); 4719 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc)) 4720 return; 4721 } 4722 } 4723 4724 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 4725 if (ASE) 4726 DiagID = diag::warn_array_index_exceeds_bounds; 4727 4728 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 4729 PDiag(DiagID) << index.toString(10, true) 4730 << size.toString(10, true) 4731 << (unsigned)size.getLimitedValue(~0U) 4732 << IndexExpr->getSourceRange()); 4733 } else { 4734 unsigned DiagID = diag::warn_array_index_precedes_bounds; 4735 if (!ASE) { 4736 DiagID = diag::warn_ptr_arith_precedes_bounds; 4737 if (index.isNegative()) index = -index; 4738 } 4739 4740 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 4741 PDiag(DiagID) << index.toString(10, true) 4742 << IndexExpr->getSourceRange()); 4743 } 4744 4745 if (!ND) { 4746 // Try harder to find a NamedDecl to point at in the note. 4747 while (const ArraySubscriptExpr *ASE = 4748 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 4749 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 4750 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 4751 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 4752 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 4753 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 4754 } 4755 4756 if (ND) 4757 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 4758 PDiag(diag::note_array_index_out_of_bounds) 4759 << ND->getDeclName()); 4760} 4761 4762void Sema::CheckArrayAccess(const Expr *expr) { 4763 int AllowOnePastEnd = 0; 4764 while (expr) { 4765 expr = expr->IgnoreParenImpCasts(); 4766 switch (expr->getStmtClass()) { 4767 case Stmt::ArraySubscriptExprClass: { 4768 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 4769 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 4770 AllowOnePastEnd > 0); 4771 return; 4772 } 4773 case Stmt::UnaryOperatorClass: { 4774 // Only unwrap the * and & unary operators 4775 const UnaryOperator *UO = cast<UnaryOperator>(expr); 4776 expr = UO->getSubExpr(); 4777 switch (UO->getOpcode()) { 4778 case UO_AddrOf: 4779 AllowOnePastEnd++; 4780 break; 4781 case UO_Deref: 4782 AllowOnePastEnd--; 4783 break; 4784 default: 4785 return; 4786 } 4787 break; 4788 } 4789 case Stmt::ConditionalOperatorClass: { 4790 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 4791 if (const Expr *lhs = cond->getLHS()) 4792 CheckArrayAccess(lhs); 4793 if (const Expr *rhs = cond->getRHS()) 4794 CheckArrayAccess(rhs); 4795 return; 4796 } 4797 default: 4798 return; 4799 } 4800 } 4801} 4802 4803//===--- CHECK: Objective-C retain cycles ----------------------------------// 4804 4805namespace { 4806 struct RetainCycleOwner { 4807 RetainCycleOwner() : Variable(0), Indirect(false) {} 4808 VarDecl *Variable; 4809 SourceRange Range; 4810 SourceLocation Loc; 4811 bool Indirect; 4812 4813 void setLocsFrom(Expr *e) { 4814 Loc = e->getExprLoc(); 4815 Range = e->getSourceRange(); 4816 } 4817 }; 4818} 4819 4820/// Consider whether capturing the given variable can possibly lead to 4821/// a retain cycle. 4822static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 4823 // In ARC, it's captured strongly iff the variable has __strong 4824 // lifetime. In MRR, it's captured strongly if the variable is 4825 // __block and has an appropriate type. 4826 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 4827 return false; 4828 4829 owner.Variable = var; 4830 owner.setLocsFrom(ref); 4831 return true; 4832} 4833 4834static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 4835 while (true) { 4836 e = e->IgnoreParens(); 4837 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 4838 switch (cast->getCastKind()) { 4839 case CK_BitCast: 4840 case CK_LValueBitCast: 4841 case CK_LValueToRValue: 4842 case CK_ARCReclaimReturnedObject: 4843 e = cast->getSubExpr(); 4844 continue; 4845 4846 default: 4847 return false; 4848 } 4849 } 4850 4851 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 4852 ObjCIvarDecl *ivar = ref->getDecl(); 4853 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 4854 return false; 4855 4856 // Try to find a retain cycle in the base. 4857 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 4858 return false; 4859 4860 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 4861 owner.Indirect = true; 4862 return true; 4863 } 4864 4865 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 4866 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 4867 if (!var) return false; 4868 return considerVariable(var, ref, owner); 4869 } 4870 4871 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 4872 if (member->isArrow()) return false; 4873 4874 // Don't count this as an indirect ownership. 4875 e = member->getBase(); 4876 continue; 4877 } 4878 4879 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 4880 // Only pay attention to pseudo-objects on property references. 4881 ObjCPropertyRefExpr *pre 4882 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 4883 ->IgnoreParens()); 4884 if (!pre) return false; 4885 if (pre->isImplicitProperty()) return false; 4886 ObjCPropertyDecl *property = pre->getExplicitProperty(); 4887 if (!property->isRetaining() && 4888 !(property->getPropertyIvarDecl() && 4889 property->getPropertyIvarDecl()->getType() 4890 .getObjCLifetime() == Qualifiers::OCL_Strong)) 4891 return false; 4892 4893 owner.Indirect = true; 4894 if (pre->isSuperReceiver()) { 4895 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 4896 if (!owner.Variable) 4897 return false; 4898 owner.Loc = pre->getLocation(); 4899 owner.Range = pre->getSourceRange(); 4900 return true; 4901 } 4902 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 4903 ->getSourceExpr()); 4904 continue; 4905 } 4906 4907 // Array ivars? 4908 4909 return false; 4910 } 4911} 4912 4913namespace { 4914 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 4915 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 4916 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 4917 Variable(variable), Capturer(0) {} 4918 4919 VarDecl *Variable; 4920 Expr *Capturer; 4921 4922 void VisitDeclRefExpr(DeclRefExpr *ref) { 4923 if (ref->getDecl() == Variable && !Capturer) 4924 Capturer = ref; 4925 } 4926 4927 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 4928 if (Capturer) return; 4929 Visit(ref->getBase()); 4930 if (Capturer && ref->isFreeIvar()) 4931 Capturer = ref; 4932 } 4933 4934 void VisitBlockExpr(BlockExpr *block) { 4935 // Look inside nested blocks 4936 if (block->getBlockDecl()->capturesVariable(Variable)) 4937 Visit(block->getBlockDecl()->getBody()); 4938 } 4939 }; 4940} 4941 4942/// Check whether the given argument is a block which captures a 4943/// variable. 4944static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 4945 assert(owner.Variable && owner.Loc.isValid()); 4946 4947 e = e->IgnoreParenCasts(); 4948 BlockExpr *block = dyn_cast<BlockExpr>(e); 4949 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 4950 return 0; 4951 4952 FindCaptureVisitor visitor(S.Context, owner.Variable); 4953 visitor.Visit(block->getBlockDecl()->getBody()); 4954 return visitor.Capturer; 4955} 4956 4957static void diagnoseRetainCycle(Sema &S, Expr *capturer, 4958 RetainCycleOwner &owner) { 4959 assert(capturer); 4960 assert(owner.Variable && owner.Loc.isValid()); 4961 4962 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 4963 << owner.Variable << capturer->getSourceRange(); 4964 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 4965 << owner.Indirect << owner.Range; 4966} 4967 4968/// Check for a keyword selector that starts with the word 'add' or 4969/// 'set'. 4970static bool isSetterLikeSelector(Selector sel) { 4971 if (sel.isUnarySelector()) return false; 4972 4973 StringRef str = sel.getNameForSlot(0); 4974 while (!str.empty() && str.front() == '_') str = str.substr(1); 4975 if (str.startswith("set")) 4976 str = str.substr(3); 4977 else if (str.startswith("add")) { 4978 // Specially whitelist 'addOperationWithBlock:'. 4979 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 4980 return false; 4981 str = str.substr(3); 4982 } 4983 else 4984 return false; 4985 4986 if (str.empty()) return true; 4987 return !islower(str.front()); 4988} 4989 4990/// Check a message send to see if it's likely to cause a retain cycle. 4991void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 4992 // Only check instance methods whose selector looks like a setter. 4993 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 4994 return; 4995 4996 // Try to find a variable that the receiver is strongly owned by. 4997 RetainCycleOwner owner; 4998 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 4999 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 5000 return; 5001 } else { 5002 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 5003 owner.Variable = getCurMethodDecl()->getSelfDecl(); 5004 owner.Loc = msg->getSuperLoc(); 5005 owner.Range = msg->getSuperLoc(); 5006 } 5007 5008 // Check whether the receiver is captured by any of the arguments. 5009 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 5010 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 5011 return diagnoseRetainCycle(*this, capturer, owner); 5012} 5013 5014/// Check a property assign to see if it's likely to cause a retain cycle. 5015void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 5016 RetainCycleOwner owner; 5017 if (!findRetainCycleOwner(*this, receiver, owner)) 5018 return; 5019 5020 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 5021 diagnoseRetainCycle(*this, capturer, owner); 5022} 5023 5024bool Sema::checkUnsafeAssigns(SourceLocation Loc, 5025 QualType LHS, Expr *RHS) { 5026 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 5027 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 5028 return false; 5029 // strip off any implicit cast added to get to the one arc-specific 5030 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 5031 if (cast->getCastKind() == CK_ARCConsumeObject) { 5032 Diag(Loc, diag::warn_arc_retained_assign) 5033 << (LT == Qualifiers::OCL_ExplicitNone) 5034 << RHS->getSourceRange(); 5035 return true; 5036 } 5037 RHS = cast->getSubExpr(); 5038 } 5039 return false; 5040} 5041 5042void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 5043 Expr *LHS, Expr *RHS) { 5044 QualType LHSType; 5045 // PropertyRef on LHS type need be directly obtained from 5046 // its declaration as it has a PsuedoType. 5047 ObjCPropertyRefExpr *PRE 5048 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 5049 if (PRE && !PRE->isImplicitProperty()) { 5050 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 5051 if (PD) 5052 LHSType = PD->getType(); 5053 } 5054 5055 if (LHSType.isNull()) 5056 LHSType = LHS->getType(); 5057 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 5058 return; 5059 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 5060 // FIXME. Check for other life times. 5061 if (LT != Qualifiers::OCL_None) 5062 return; 5063 5064 if (PRE) { 5065 if (PRE->isImplicitProperty()) 5066 return; 5067 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 5068 if (!PD) 5069 return; 5070 5071 unsigned Attributes = PD->getPropertyAttributes(); 5072 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 5073 // when 'assign' attribute was not explicitly specified 5074 // by user, ignore it and rely on property type itself 5075 // for lifetime info. 5076 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 5077 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 5078 LHSType->isObjCRetainableType()) 5079 return; 5080 5081 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 5082 if (cast->getCastKind() == CK_ARCConsumeObject) { 5083 Diag(Loc, diag::warn_arc_retained_property_assign) 5084 << RHS->getSourceRange(); 5085 return; 5086 } 5087 RHS = cast->getSubExpr(); 5088 } 5089 } 5090 } 5091} 5092 5093//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 5094 5095namespace { 5096bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 5097 SourceLocation StmtLoc, 5098 const NullStmt *Body) { 5099 // Do not warn if the body is a macro that expands to nothing, e.g: 5100 // 5101 // #define CALL(x) 5102 // if (condition) 5103 // CALL(0); 5104 // 5105 if (Body->hasLeadingEmptyMacro()) 5106 return false; 5107 5108 // Get line numbers of statement and body. 5109 bool StmtLineInvalid; 5110 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc, 5111 &StmtLineInvalid); 5112 if (StmtLineInvalid) 5113 return false; 5114 5115 bool BodyLineInvalid; 5116 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 5117 &BodyLineInvalid); 5118 if (BodyLineInvalid) 5119 return false; 5120 5121 // Warn if null statement and body are on the same line. 5122 if (StmtLine != BodyLine) 5123 return false; 5124 5125 return true; 5126} 5127} // Unnamed namespace 5128 5129void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 5130 const Stmt *Body, 5131 unsigned DiagID) { 5132 // Since this is a syntactic check, don't emit diagnostic for template 5133 // instantiations, this just adds noise. 5134 if (CurrentInstantiationScope) 5135 return; 5136 5137 // The body should be a null statement. 5138 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 5139 if (!NBody) 5140 return; 5141 5142 // Do the usual checks. 5143 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 5144 return; 5145 5146 Diag(NBody->getSemiLoc(), DiagID); 5147 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 5148} 5149 5150void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 5151 const Stmt *PossibleBody) { 5152 assert(!CurrentInstantiationScope); // Ensured by caller 5153 5154 SourceLocation StmtLoc; 5155 const Stmt *Body; 5156 unsigned DiagID; 5157 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 5158 StmtLoc = FS->getRParenLoc(); 5159 Body = FS->getBody(); 5160 DiagID = diag::warn_empty_for_body; 5161 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 5162 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 5163 Body = WS->getBody(); 5164 DiagID = diag::warn_empty_while_body; 5165 } else 5166 return; // Neither `for' nor `while'. 5167 5168 // The body should be a null statement. 5169 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 5170 if (!NBody) 5171 return; 5172 5173 // Skip expensive checks if diagnostic is disabled. 5174 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) == 5175 DiagnosticsEngine::Ignored) 5176 return; 5177 5178 // Do the usual checks. 5179 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 5180 return; 5181 5182 // `for(...);' and `while(...);' are popular idioms, so in order to keep 5183 // noise level low, emit diagnostics only if for/while is followed by a 5184 // CompoundStmt, e.g.: 5185 // for (int i = 0; i < n; i++); 5186 // { 5187 // a(i); 5188 // } 5189 // or if for/while is followed by a statement with more indentation 5190 // than for/while itself: 5191 // for (int i = 0; i < n; i++); 5192 // a(i); 5193 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 5194 if (!ProbableTypo) { 5195 bool BodyColInvalid; 5196 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 5197 PossibleBody->getLocStart(), 5198 &BodyColInvalid); 5199 if (BodyColInvalid) 5200 return; 5201 5202 bool StmtColInvalid; 5203 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 5204 S->getLocStart(), 5205 &StmtColInvalid); 5206 if (StmtColInvalid) 5207 return; 5208 5209 if (BodyCol > StmtCol) 5210 ProbableTypo = true; 5211 } 5212 5213 if (ProbableTypo) { 5214 Diag(NBody->getSemiLoc(), DiagID); 5215 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 5216 } 5217} 5218