SemaChecking.cpp revision df9ef1bc8c3780307ab2ed81bf5e31c23310b936
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 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 1640 unsigned BuiltinID = FD->getBuiltinID(); 1641 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 1642 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 1643 const Expr *Arg = CE->getArg(0); 1644 return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg, 1645 format_idx, firstDataArg, Type, 1646 inFunctionCall); 1647 } 1648 } 1649 } 1650 1651 return false; 1652 } 1653 case Stmt::ObjCStringLiteralClass: 1654 case Stmt::StringLiteralClass: { 1655 const StringLiteral *StrE = NULL; 1656 1657 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 1658 StrE = ObjCFExpr->getString(); 1659 else 1660 StrE = cast<StringLiteral>(E); 1661 1662 if (StrE) { 1663 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx, 1664 firstDataArg, Type, inFunctionCall); 1665 return true; 1666 } 1667 1668 return false; 1669 } 1670 1671 default: 1672 return false; 1673 } 1674} 1675 1676void 1677Sema::CheckNonNullArguments(const NonNullAttr *NonNull, 1678 const Expr * const *ExprArgs, 1679 SourceLocation CallSiteLoc) { 1680 for (NonNullAttr::args_iterator i = NonNull->args_begin(), 1681 e = NonNull->args_end(); 1682 i != e; ++i) { 1683 const Expr *ArgExpr = ExprArgs[*i]; 1684 if (ArgExpr->isNullPointerConstant(Context, 1685 Expr::NPC_ValueDependentIsNotNull)) 1686 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 1687 } 1688} 1689 1690Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 1691 return llvm::StringSwitch<FormatStringType>(Format->getType()) 1692 .Case("scanf", FST_Scanf) 1693 .Cases("printf", "printf0", FST_Printf) 1694 .Cases("NSString", "CFString", FST_NSString) 1695 .Case("strftime", FST_Strftime) 1696 .Case("strfmon", FST_Strfmon) 1697 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 1698 .Default(FST_Unknown); 1699} 1700 1701/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar 1702/// functions) for correct use of format strings. 1703void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) { 1704 bool IsCXXMember = false; 1705 // The way the format attribute works in GCC, the implicit this argument 1706 // of member functions is counted. However, it doesn't appear in our own 1707 // lists, so decrement format_idx in that case. 1708 IsCXXMember = isa<CXXMemberCallExpr>(TheCall); 1709 CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(), 1710 IsCXXMember, TheCall->getRParenLoc(), 1711 TheCall->getCallee()->getSourceRange()); 1712} 1713 1714void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args, 1715 unsigned NumArgs, bool IsCXXMember, 1716 SourceLocation Loc, SourceRange Range) { 1717 bool HasVAListArg = Format->getFirstArg() == 0; 1718 unsigned format_idx = Format->getFormatIdx() - 1; 1719 unsigned firstDataArg = HasVAListArg ? 0 : Format->getFirstArg() - 1; 1720 if (IsCXXMember) { 1721 if (format_idx == 0) 1722 return; 1723 --format_idx; 1724 if(firstDataArg != 0) 1725 --firstDataArg; 1726 } 1727 CheckFormatArguments(Args, NumArgs, HasVAListArg, format_idx, 1728 firstDataArg, GetFormatStringType(Format), Loc, Range); 1729} 1730 1731void Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs, 1732 bool HasVAListArg, unsigned format_idx, 1733 unsigned firstDataArg, FormatStringType Type, 1734 SourceLocation Loc, SourceRange Range) { 1735 // CHECK: printf/scanf-like function is called with no format string. 1736 if (format_idx >= NumArgs) { 1737 Diag(Loc, diag::warn_missing_format_string) << Range; 1738 return; 1739 } 1740 1741 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 1742 1743 // CHECK: format string is not a string literal. 1744 // 1745 // Dynamically generated format strings are difficult to 1746 // automatically vet at compile time. Requiring that format strings 1747 // are string literals: (1) permits the checking of format strings by 1748 // the compiler and thereby (2) can practically remove the source of 1749 // many format string exploits. 1750 1751 // Format string can be either ObjC string (e.g. @"%d") or 1752 // C string (e.g. "%d") 1753 // ObjC string uses the same format specifiers as C string, so we can use 1754 // the same format string checking logic for both ObjC and C strings. 1755 if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg, 1756 format_idx, firstDataArg, Type)) 1757 return; // Literal format string found, check done! 1758 1759 // Strftime is particular as it always uses a single 'time' argument, 1760 // so it is safe to pass a non-literal string. 1761 if (Type == FST_Strftime) 1762 return; 1763 1764 // Do not emit diag when the string param is a macro expansion and the 1765 // format is either NSString or CFString. This is a hack to prevent 1766 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 1767 // which are usually used in place of NS and CF string literals. 1768 if (Type == FST_NSString && 1769 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart())) 1770 return; 1771 1772 // If there are no arguments specified, warn with -Wformat-security, otherwise 1773 // warn only with -Wformat-nonliteral. 1774 if (NumArgs == format_idx+1) 1775 Diag(Args[format_idx]->getLocStart(), 1776 diag::warn_format_nonliteral_noargs) 1777 << OrigFormatExpr->getSourceRange(); 1778 else 1779 Diag(Args[format_idx]->getLocStart(), 1780 diag::warn_format_nonliteral) 1781 << OrigFormatExpr->getSourceRange(); 1782} 1783 1784namespace { 1785class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 1786protected: 1787 Sema &S; 1788 const StringLiteral *FExpr; 1789 const Expr *OrigFormatExpr; 1790 const unsigned FirstDataArg; 1791 const unsigned NumDataArgs; 1792 const char *Beg; // Start of format string. 1793 const bool HasVAListArg; 1794 const Expr * const *Args; 1795 const unsigned NumArgs; 1796 unsigned FormatIdx; 1797 llvm::BitVector CoveredArgs; 1798 bool usesPositionalArgs; 1799 bool atFirstArg; 1800 bool inFunctionCall; 1801public: 1802 CheckFormatHandler(Sema &s, const StringLiteral *fexpr, 1803 const Expr *origFormatExpr, unsigned firstDataArg, 1804 unsigned numDataArgs, const char *beg, bool hasVAListArg, 1805 Expr **args, unsigned numArgs, 1806 unsigned formatIdx, bool inFunctionCall) 1807 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 1808 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), 1809 Beg(beg), HasVAListArg(hasVAListArg), 1810 Args(args), NumArgs(numArgs), FormatIdx(formatIdx), 1811 usesPositionalArgs(false), atFirstArg(true), 1812 inFunctionCall(inFunctionCall) { 1813 CoveredArgs.resize(numDataArgs); 1814 CoveredArgs.reset(); 1815 } 1816 1817 void DoneProcessing(); 1818 1819 void HandleIncompleteSpecifier(const char *startSpecifier, 1820 unsigned specifierLen); 1821 1822 void HandleNonStandardLengthModifier( 1823 const analyze_format_string::LengthModifier &LM, 1824 const char *startSpecifier, unsigned specifierLen); 1825 1826 void HandleNonStandardConversionSpecifier( 1827 const analyze_format_string::ConversionSpecifier &CS, 1828 const char *startSpecifier, unsigned specifierLen); 1829 1830 void HandleNonStandardConversionSpecification( 1831 const analyze_format_string::LengthModifier &LM, 1832 const analyze_format_string::ConversionSpecifier &CS, 1833 const char *startSpecifier, unsigned specifierLen); 1834 1835 virtual void HandlePosition(const char *startPos, unsigned posLen); 1836 1837 virtual void HandleInvalidPosition(const char *startSpecifier, 1838 unsigned specifierLen, 1839 analyze_format_string::PositionContext p); 1840 1841 virtual void HandleZeroPosition(const char *startPos, unsigned posLen); 1842 1843 void HandleNullChar(const char *nullCharacter); 1844 1845 template <typename Range> 1846 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall, 1847 const Expr *ArgumentExpr, 1848 PartialDiagnostic PDiag, 1849 SourceLocation StringLoc, 1850 bool IsStringLocation, Range StringRange, 1851 FixItHint Fixit = FixItHint()); 1852 1853protected: 1854 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 1855 const char *startSpec, 1856 unsigned specifierLen, 1857 const char *csStart, unsigned csLen); 1858 1859 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 1860 const char *startSpec, 1861 unsigned specifierLen); 1862 1863 SourceRange getFormatStringRange(); 1864 CharSourceRange getSpecifierRange(const char *startSpecifier, 1865 unsigned specifierLen); 1866 SourceLocation getLocationOfByte(const char *x); 1867 1868 const Expr *getDataArg(unsigned i) const; 1869 1870 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 1871 const analyze_format_string::ConversionSpecifier &CS, 1872 const char *startSpecifier, unsigned specifierLen, 1873 unsigned argIndex); 1874 1875 template <typename Range> 1876 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 1877 bool IsStringLocation, Range StringRange, 1878 FixItHint Fixit = FixItHint()); 1879 1880 void CheckPositionalAndNonpositionalArgs( 1881 const analyze_format_string::FormatSpecifier *FS); 1882}; 1883} 1884 1885SourceRange CheckFormatHandler::getFormatStringRange() { 1886 return OrigFormatExpr->getSourceRange(); 1887} 1888 1889CharSourceRange CheckFormatHandler:: 1890getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 1891 SourceLocation Start = getLocationOfByte(startSpecifier); 1892 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 1893 1894 // Advance the end SourceLocation by one due to half-open ranges. 1895 End = End.getLocWithOffset(1); 1896 1897 return CharSourceRange::getCharRange(Start, End); 1898} 1899 1900SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 1901 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 1902} 1903 1904void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 1905 unsigned specifierLen){ 1906 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 1907 getLocationOfByte(startSpecifier), 1908 /*IsStringLocation*/true, 1909 getSpecifierRange(startSpecifier, specifierLen)); 1910} 1911 1912void CheckFormatHandler::HandleNonStandardLengthModifier( 1913 const analyze_format_string::LengthModifier &LM, 1914 const char *startSpecifier, unsigned specifierLen) { 1915 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toString() 1916 << 0, 1917 getLocationOfByte(LM.getStart()), 1918 /*IsStringLocation*/true, 1919 getSpecifierRange(startSpecifier, specifierLen)); 1920} 1921 1922void CheckFormatHandler::HandleNonStandardConversionSpecifier( 1923 const analyze_format_string::ConversionSpecifier &CS, 1924 const char *startSpecifier, unsigned specifierLen) { 1925 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString() 1926 << 1, 1927 getLocationOfByte(CS.getStart()), 1928 /*IsStringLocation*/true, 1929 getSpecifierRange(startSpecifier, specifierLen)); 1930} 1931 1932void CheckFormatHandler::HandleNonStandardConversionSpecification( 1933 const analyze_format_string::LengthModifier &LM, 1934 const analyze_format_string::ConversionSpecifier &CS, 1935 const char *startSpecifier, unsigned specifierLen) { 1936 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_conversion_spec) 1937 << LM.toString() << CS.toString(), 1938 getLocationOfByte(LM.getStart()), 1939 /*IsStringLocation*/true, 1940 getSpecifierRange(startSpecifier, specifierLen)); 1941} 1942 1943void CheckFormatHandler::HandlePosition(const char *startPos, 1944 unsigned posLen) { 1945 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 1946 getLocationOfByte(startPos), 1947 /*IsStringLocation*/true, 1948 getSpecifierRange(startPos, posLen)); 1949} 1950 1951void 1952CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 1953 analyze_format_string::PositionContext p) { 1954 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 1955 << (unsigned) p, 1956 getLocationOfByte(startPos), /*IsStringLocation*/true, 1957 getSpecifierRange(startPos, posLen)); 1958} 1959 1960void CheckFormatHandler::HandleZeroPosition(const char *startPos, 1961 unsigned posLen) { 1962 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 1963 getLocationOfByte(startPos), 1964 /*IsStringLocation*/true, 1965 getSpecifierRange(startPos, posLen)); 1966} 1967 1968void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 1969 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 1970 // The presence of a null character is likely an error. 1971 EmitFormatDiagnostic( 1972 S.PDiag(diag::warn_printf_format_string_contains_null_char), 1973 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 1974 getFormatStringRange()); 1975 } 1976} 1977 1978const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 1979 return Args[FirstDataArg + i]; 1980} 1981 1982void CheckFormatHandler::DoneProcessing() { 1983 // Does the number of data arguments exceed the number of 1984 // format conversions in the format string? 1985 if (!HasVAListArg) { 1986 // Find any arguments that weren't covered. 1987 CoveredArgs.flip(); 1988 signed notCoveredArg = CoveredArgs.find_first(); 1989 if (notCoveredArg >= 0) { 1990 assert((unsigned)notCoveredArg < NumDataArgs); 1991 SourceLocation Loc = getDataArg((unsigned) notCoveredArg)->getLocStart(); 1992 if (!S.getSourceManager().isInSystemMacro(Loc)) { 1993 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used), 1994 Loc, 1995 /*IsStringLocation*/false, getFormatStringRange()); 1996 } 1997 } 1998 } 1999} 2000 2001bool 2002CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 2003 SourceLocation Loc, 2004 const char *startSpec, 2005 unsigned specifierLen, 2006 const char *csStart, 2007 unsigned csLen) { 2008 2009 bool keepGoing = true; 2010 if (argIndex < NumDataArgs) { 2011 // Consider the argument coverered, even though the specifier doesn't 2012 // make sense. 2013 CoveredArgs.set(argIndex); 2014 } 2015 else { 2016 // If argIndex exceeds the number of data arguments we 2017 // don't issue a warning because that is just a cascade of warnings (and 2018 // they may have intended '%%' anyway). We don't want to continue processing 2019 // the format string after this point, however, as we will like just get 2020 // gibberish when trying to match arguments. 2021 keepGoing = false; 2022 } 2023 2024 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion) 2025 << StringRef(csStart, csLen), 2026 Loc, /*IsStringLocation*/true, 2027 getSpecifierRange(startSpec, specifierLen)); 2028 2029 return keepGoing; 2030} 2031 2032void 2033CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 2034 const char *startSpec, 2035 unsigned specifierLen) { 2036 EmitFormatDiagnostic( 2037 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 2038 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 2039} 2040 2041bool 2042CheckFormatHandler::CheckNumArgs( 2043 const analyze_format_string::FormatSpecifier &FS, 2044 const analyze_format_string::ConversionSpecifier &CS, 2045 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 2046 2047 if (argIndex >= NumDataArgs) { 2048 PartialDiagnostic PDiag = FS.usesPositionalArg() 2049 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 2050 << (argIndex+1) << NumDataArgs) 2051 : S.PDiag(diag::warn_printf_insufficient_data_args); 2052 EmitFormatDiagnostic( 2053 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 2054 getSpecifierRange(startSpecifier, specifierLen)); 2055 return false; 2056 } 2057 return true; 2058} 2059 2060template<typename Range> 2061void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 2062 SourceLocation Loc, 2063 bool IsStringLocation, 2064 Range StringRange, 2065 FixItHint FixIt) { 2066 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 2067 Loc, IsStringLocation, StringRange, FixIt); 2068} 2069 2070/// \brief If the format string is not within the funcion call, emit a note 2071/// so that the function call and string are in diagnostic messages. 2072/// 2073/// \param inFunctionCall if true, the format string is within the function 2074/// call and only one diagnostic message will be produced. Otherwise, an 2075/// extra note will be emitted pointing to location of the format string. 2076/// 2077/// \param ArgumentExpr the expression that is passed as the format string 2078/// argument in the function call. Used for getting locations when two 2079/// diagnostics are emitted. 2080/// 2081/// \param PDiag the callee should already have provided any strings for the 2082/// diagnostic message. This function only adds locations and fixits 2083/// to diagnostics. 2084/// 2085/// \param Loc primary location for diagnostic. If two diagnostics are 2086/// required, one will be at Loc and a new SourceLocation will be created for 2087/// the other one. 2088/// 2089/// \param IsStringLocation if true, Loc points to the format string should be 2090/// used for the note. Otherwise, Loc points to the argument list and will 2091/// be used with PDiag. 2092/// 2093/// \param StringRange some or all of the string to highlight. This is 2094/// templated so it can accept either a CharSourceRange or a SourceRange. 2095/// 2096/// \param Fixit optional fix it hint for the format string. 2097template<typename Range> 2098void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall, 2099 const Expr *ArgumentExpr, 2100 PartialDiagnostic PDiag, 2101 SourceLocation Loc, 2102 bool IsStringLocation, 2103 Range StringRange, 2104 FixItHint FixIt) { 2105 if (InFunctionCall) 2106 S.Diag(Loc, PDiag) << StringRange << FixIt; 2107 else { 2108 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 2109 << ArgumentExpr->getSourceRange(); 2110 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 2111 diag::note_format_string_defined) 2112 << StringRange << FixIt; 2113 } 2114} 2115 2116//===--- CHECK: Printf format string checking ------------------------------===// 2117 2118namespace { 2119class CheckPrintfHandler : public CheckFormatHandler { 2120 bool ObjCContext; 2121public: 2122 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 2123 const Expr *origFormatExpr, unsigned firstDataArg, 2124 unsigned numDataArgs, bool isObjC, 2125 const char *beg, bool hasVAListArg, 2126 Expr **Args, unsigned NumArgs, 2127 unsigned formatIdx, bool inFunctionCall) 2128 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 2129 numDataArgs, beg, hasVAListArg, Args, NumArgs, 2130 formatIdx, inFunctionCall), ObjCContext(isObjC) {} 2131 2132 2133 bool HandleInvalidPrintfConversionSpecifier( 2134 const analyze_printf::PrintfSpecifier &FS, 2135 const char *startSpecifier, 2136 unsigned specifierLen); 2137 2138 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 2139 const char *startSpecifier, 2140 unsigned specifierLen); 2141 2142 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 2143 const char *startSpecifier, unsigned specifierLen); 2144 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 2145 const analyze_printf::OptionalAmount &Amt, 2146 unsigned type, 2147 const char *startSpecifier, unsigned specifierLen); 2148 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 2149 const analyze_printf::OptionalFlag &flag, 2150 const char *startSpecifier, unsigned specifierLen); 2151 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 2152 const analyze_printf::OptionalFlag &ignoredFlag, 2153 const analyze_printf::OptionalFlag &flag, 2154 const char *startSpecifier, unsigned specifierLen); 2155}; 2156} 2157 2158bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 2159 const analyze_printf::PrintfSpecifier &FS, 2160 const char *startSpecifier, 2161 unsigned specifierLen) { 2162 const analyze_printf::PrintfConversionSpecifier &CS = 2163 FS.getConversionSpecifier(); 2164 2165 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 2166 getLocationOfByte(CS.getStart()), 2167 startSpecifier, specifierLen, 2168 CS.getStart(), CS.getLength()); 2169} 2170 2171bool CheckPrintfHandler::HandleAmount( 2172 const analyze_format_string::OptionalAmount &Amt, 2173 unsigned k, const char *startSpecifier, 2174 unsigned specifierLen) { 2175 2176 if (Amt.hasDataArgument()) { 2177 if (!HasVAListArg) { 2178 unsigned argIndex = Amt.getArgIndex(); 2179 if (argIndex >= NumDataArgs) { 2180 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 2181 << k, 2182 getLocationOfByte(Amt.getStart()), 2183 /*IsStringLocation*/true, 2184 getSpecifierRange(startSpecifier, specifierLen)); 2185 // Don't do any more checking. We will just emit 2186 // spurious errors. 2187 return false; 2188 } 2189 2190 // Type check the data argument. It should be an 'int'. 2191 // Although not in conformance with C99, we also allow the argument to be 2192 // an 'unsigned int' as that is a reasonably safe case. GCC also 2193 // doesn't emit a warning for that case. 2194 CoveredArgs.set(argIndex); 2195 const Expr *Arg = getDataArg(argIndex); 2196 QualType T = Arg->getType(); 2197 2198 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context); 2199 assert(ATR.isValid()); 2200 2201 if (!ATR.matchesType(S.Context, T)) { 2202 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 2203 << k << ATR.getRepresentativeTypeName(S.Context) 2204 << T << Arg->getSourceRange(), 2205 getLocationOfByte(Amt.getStart()), 2206 /*IsStringLocation*/true, 2207 getSpecifierRange(startSpecifier, specifierLen)); 2208 // Don't do any more checking. We will just emit 2209 // spurious errors. 2210 return false; 2211 } 2212 } 2213 } 2214 return true; 2215} 2216 2217void CheckPrintfHandler::HandleInvalidAmount( 2218 const analyze_printf::PrintfSpecifier &FS, 2219 const analyze_printf::OptionalAmount &Amt, 2220 unsigned type, 2221 const char *startSpecifier, 2222 unsigned specifierLen) { 2223 const analyze_printf::PrintfConversionSpecifier &CS = 2224 FS.getConversionSpecifier(); 2225 2226 FixItHint fixit = 2227 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 2228 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 2229 Amt.getConstantLength())) 2230 : FixItHint(); 2231 2232 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 2233 << type << CS.toString(), 2234 getLocationOfByte(Amt.getStart()), 2235 /*IsStringLocation*/true, 2236 getSpecifierRange(startSpecifier, specifierLen), 2237 fixit); 2238} 2239 2240void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 2241 const analyze_printf::OptionalFlag &flag, 2242 const char *startSpecifier, 2243 unsigned specifierLen) { 2244 // Warn about pointless flag with a fixit removal. 2245 const analyze_printf::PrintfConversionSpecifier &CS = 2246 FS.getConversionSpecifier(); 2247 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 2248 << flag.toString() << CS.toString(), 2249 getLocationOfByte(flag.getPosition()), 2250 /*IsStringLocation*/true, 2251 getSpecifierRange(startSpecifier, specifierLen), 2252 FixItHint::CreateRemoval( 2253 getSpecifierRange(flag.getPosition(), 1))); 2254} 2255 2256void CheckPrintfHandler::HandleIgnoredFlag( 2257 const analyze_printf::PrintfSpecifier &FS, 2258 const analyze_printf::OptionalFlag &ignoredFlag, 2259 const analyze_printf::OptionalFlag &flag, 2260 const char *startSpecifier, 2261 unsigned specifierLen) { 2262 // Warn about ignored flag with a fixit removal. 2263 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 2264 << ignoredFlag.toString() << flag.toString(), 2265 getLocationOfByte(ignoredFlag.getPosition()), 2266 /*IsStringLocation*/true, 2267 getSpecifierRange(startSpecifier, specifierLen), 2268 FixItHint::CreateRemoval( 2269 getSpecifierRange(ignoredFlag.getPosition(), 1))); 2270} 2271 2272bool 2273CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 2274 &FS, 2275 const char *startSpecifier, 2276 unsigned specifierLen) { 2277 2278 using namespace analyze_format_string; 2279 using namespace analyze_printf; 2280 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 2281 2282 if (FS.consumesDataArgument()) { 2283 if (atFirstArg) { 2284 atFirstArg = false; 2285 usesPositionalArgs = FS.usesPositionalArg(); 2286 } 2287 else if (usesPositionalArgs != FS.usesPositionalArg()) { 2288 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 2289 startSpecifier, specifierLen); 2290 return false; 2291 } 2292 } 2293 2294 // First check if the field width, precision, and conversion specifier 2295 // have matching data arguments. 2296 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 2297 startSpecifier, specifierLen)) { 2298 return false; 2299 } 2300 2301 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 2302 startSpecifier, specifierLen)) { 2303 return false; 2304 } 2305 2306 if (!CS.consumesDataArgument()) { 2307 // FIXME: Technically specifying a precision or field width here 2308 // makes no sense. Worth issuing a warning at some point. 2309 return true; 2310 } 2311 2312 // Consume the argument. 2313 unsigned argIndex = FS.getArgIndex(); 2314 if (argIndex < NumDataArgs) { 2315 // The check to see if the argIndex is valid will come later. 2316 // We set the bit here because we may exit early from this 2317 // function if we encounter some other error. 2318 CoveredArgs.set(argIndex); 2319 } 2320 2321 // Check for using an Objective-C specific conversion specifier 2322 // in a non-ObjC literal. 2323 if (!ObjCContext && CS.isObjCArg()) { 2324 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 2325 specifierLen); 2326 } 2327 2328 // Check for invalid use of field width 2329 if (!FS.hasValidFieldWidth()) { 2330 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 2331 startSpecifier, specifierLen); 2332 } 2333 2334 // Check for invalid use of precision 2335 if (!FS.hasValidPrecision()) { 2336 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 2337 startSpecifier, specifierLen); 2338 } 2339 2340 // Check each flag does not conflict with any other component. 2341 if (!FS.hasValidThousandsGroupingPrefix()) 2342 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 2343 if (!FS.hasValidLeadingZeros()) 2344 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 2345 if (!FS.hasValidPlusPrefix()) 2346 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 2347 if (!FS.hasValidSpacePrefix()) 2348 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 2349 if (!FS.hasValidAlternativeForm()) 2350 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 2351 if (!FS.hasValidLeftJustified()) 2352 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 2353 2354 // Check that flags are not ignored by another flag 2355 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 2356 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 2357 startSpecifier, specifierLen); 2358 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 2359 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 2360 startSpecifier, specifierLen); 2361 2362 // Check the length modifier is valid with the given conversion specifier. 2363 const LengthModifier &LM = FS.getLengthModifier(); 2364 if (!FS.hasValidLengthModifier()) 2365 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length) 2366 << LM.toString() << CS.toString(), 2367 getLocationOfByte(LM.getStart()), 2368 /*IsStringLocation*/true, 2369 getSpecifierRange(startSpecifier, specifierLen), 2370 FixItHint::CreateRemoval( 2371 getSpecifierRange(LM.getStart(), 2372 LM.getLength()))); 2373 if (!FS.hasStandardLengthModifier()) 2374 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen); 2375 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 2376 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 2377 if (!FS.hasStandardLengthConversionCombination()) 2378 HandleNonStandardConversionSpecification(LM, CS, startSpecifier, 2379 specifierLen); 2380 2381 // Are we using '%n'? 2382 if (CS.getKind() == ConversionSpecifier::nArg) { 2383 // Issue a warning about this being a possible security issue. 2384 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back), 2385 getLocationOfByte(CS.getStart()), 2386 /*IsStringLocation*/true, 2387 getSpecifierRange(startSpecifier, specifierLen)); 2388 // Continue checking the other format specifiers. 2389 return true; 2390 } 2391 2392 // The remaining checks depend on the data arguments. 2393 if (HasVAListArg) 2394 return true; 2395 2396 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 2397 return false; 2398 2399 // Now type check the data expression that matches the 2400 // format specifier. 2401 const Expr *Ex = getDataArg(argIndex); 2402 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context, 2403 ObjCContext); 2404 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) { 2405 // Look through argument promotions for our error message's reported type. 2406 // This includes the integral and floating promotions, but excludes array 2407 // and function pointer decay; seeing that an argument intended to be a 2408 // string has type 'char [6]' is probably more confusing than 'char *'. 2409 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex)) { 2410 if (ICE->getCastKind() == CK_IntegralCast || 2411 ICE->getCastKind() == CK_FloatingCast) { 2412 Ex = ICE->getSubExpr(); 2413 2414 // Check if we didn't match because of an implicit cast from a 'char' 2415 // or 'short' to an 'int'. This is done because printf is a varargs 2416 // function. 2417 if (ICE->getType() == S.Context.IntTy || 2418 ICE->getType() == S.Context.UnsignedIntTy) { 2419 // All further checking is done on the subexpression. 2420 if (ATR.matchesType(S.Context, Ex->getType())) 2421 return true; 2422 } 2423 } 2424 } 2425 2426 // We may be able to offer a FixItHint if it is a supported type. 2427 PrintfSpecifier fixedFS = FS; 2428 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(), 2429 S.Context, ObjCContext); 2430 2431 if (success) { 2432 // Get the fix string from the fixed format specifier 2433 SmallString<16> buf; 2434 llvm::raw_svector_ostream os(buf); 2435 fixedFS.toString(os); 2436 2437 EmitFormatDiagnostic( 2438 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2439 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2440 << Ex->getSourceRange(), 2441 Ex->getLocStart(), 2442 /*IsStringLocation*/false, 2443 getSpecifierRange(startSpecifier, specifierLen), 2444 FixItHint::CreateReplacement( 2445 getSpecifierRange(startSpecifier, specifierLen), 2446 os.str())); 2447 } 2448 else { 2449 EmitFormatDiagnostic( 2450 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2451 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2452 << getSpecifierRange(startSpecifier, specifierLen) 2453 << Ex->getSourceRange(), 2454 Ex->getLocStart(), 2455 /*IsStringLocation*/false, 2456 getSpecifierRange(startSpecifier, specifierLen)); 2457 } 2458 } 2459 2460 return true; 2461} 2462 2463//===--- CHECK: Scanf format string checking ------------------------------===// 2464 2465namespace { 2466class CheckScanfHandler : public CheckFormatHandler { 2467public: 2468 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 2469 const Expr *origFormatExpr, unsigned firstDataArg, 2470 unsigned numDataArgs, const char *beg, bool hasVAListArg, 2471 Expr **Args, unsigned NumArgs, 2472 unsigned formatIdx, bool inFunctionCall) 2473 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 2474 numDataArgs, beg, hasVAListArg, 2475 Args, NumArgs, formatIdx, inFunctionCall) {} 2476 2477 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 2478 const char *startSpecifier, 2479 unsigned specifierLen); 2480 2481 bool HandleInvalidScanfConversionSpecifier( 2482 const analyze_scanf::ScanfSpecifier &FS, 2483 const char *startSpecifier, 2484 unsigned specifierLen); 2485 2486 void HandleIncompleteScanList(const char *start, const char *end); 2487}; 2488} 2489 2490void CheckScanfHandler::HandleIncompleteScanList(const char *start, 2491 const char *end) { 2492 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 2493 getLocationOfByte(end), /*IsStringLocation*/true, 2494 getSpecifierRange(start, end - start)); 2495} 2496 2497bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 2498 const analyze_scanf::ScanfSpecifier &FS, 2499 const char *startSpecifier, 2500 unsigned specifierLen) { 2501 2502 const analyze_scanf::ScanfConversionSpecifier &CS = 2503 FS.getConversionSpecifier(); 2504 2505 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 2506 getLocationOfByte(CS.getStart()), 2507 startSpecifier, specifierLen, 2508 CS.getStart(), CS.getLength()); 2509} 2510 2511bool CheckScanfHandler::HandleScanfSpecifier( 2512 const analyze_scanf::ScanfSpecifier &FS, 2513 const char *startSpecifier, 2514 unsigned specifierLen) { 2515 2516 using namespace analyze_scanf; 2517 using namespace analyze_format_string; 2518 2519 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 2520 2521 // Handle case where '%' and '*' don't consume an argument. These shouldn't 2522 // be used to decide if we are using positional arguments consistently. 2523 if (FS.consumesDataArgument()) { 2524 if (atFirstArg) { 2525 atFirstArg = false; 2526 usesPositionalArgs = FS.usesPositionalArg(); 2527 } 2528 else if (usesPositionalArgs != FS.usesPositionalArg()) { 2529 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 2530 startSpecifier, specifierLen); 2531 return false; 2532 } 2533 } 2534 2535 // Check if the field with is non-zero. 2536 const OptionalAmount &Amt = FS.getFieldWidth(); 2537 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 2538 if (Amt.getConstantAmount() == 0) { 2539 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 2540 Amt.getConstantLength()); 2541 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 2542 getLocationOfByte(Amt.getStart()), 2543 /*IsStringLocation*/true, R, 2544 FixItHint::CreateRemoval(R)); 2545 } 2546 } 2547 2548 if (!FS.consumesDataArgument()) { 2549 // FIXME: Technically specifying a precision or field width here 2550 // makes no sense. Worth issuing a warning at some point. 2551 return true; 2552 } 2553 2554 // Consume the argument. 2555 unsigned argIndex = FS.getArgIndex(); 2556 if (argIndex < NumDataArgs) { 2557 // The check to see if the argIndex is valid will come later. 2558 // We set the bit here because we may exit early from this 2559 // function if we encounter some other error. 2560 CoveredArgs.set(argIndex); 2561 } 2562 2563 // Check the length modifier is valid with the given conversion specifier. 2564 const LengthModifier &LM = FS.getLengthModifier(); 2565 if (!FS.hasValidLengthModifier()) { 2566 const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength()); 2567 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length) 2568 << LM.toString() << CS.toString() 2569 << getSpecifierRange(startSpecifier, specifierLen), 2570 getLocationOfByte(LM.getStart()), 2571 /*IsStringLocation*/true, R, 2572 FixItHint::CreateRemoval(R)); 2573 } 2574 2575 if (!FS.hasStandardLengthModifier()) 2576 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen); 2577 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 2578 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 2579 if (!FS.hasStandardLengthConversionCombination()) 2580 HandleNonStandardConversionSpecification(LM, CS, startSpecifier, 2581 specifierLen); 2582 2583 // The remaining checks depend on the data arguments. 2584 if (HasVAListArg) 2585 return true; 2586 2587 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 2588 return false; 2589 2590 // Check that the argument type matches the format specifier. 2591 const Expr *Ex = getDataArg(argIndex); 2592 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context); 2593 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) { 2594 ScanfSpecifier fixedFS = FS; 2595 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(), 2596 S.Context); 2597 2598 if (success) { 2599 // Get the fix string from the fixed format specifier. 2600 SmallString<128> buf; 2601 llvm::raw_svector_ostream os(buf); 2602 fixedFS.toString(os); 2603 2604 EmitFormatDiagnostic( 2605 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2606 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2607 << Ex->getSourceRange(), 2608 Ex->getLocStart(), 2609 /*IsStringLocation*/false, 2610 getSpecifierRange(startSpecifier, specifierLen), 2611 FixItHint::CreateReplacement( 2612 getSpecifierRange(startSpecifier, specifierLen), 2613 os.str())); 2614 } else { 2615 EmitFormatDiagnostic( 2616 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2617 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2618 << Ex->getSourceRange(), 2619 Ex->getLocStart(), 2620 /*IsStringLocation*/false, 2621 getSpecifierRange(startSpecifier, specifierLen)); 2622 } 2623 } 2624 2625 return true; 2626} 2627 2628void Sema::CheckFormatString(const StringLiteral *FExpr, 2629 const Expr *OrigFormatExpr, 2630 Expr **Args, unsigned NumArgs, 2631 bool HasVAListArg, unsigned format_idx, 2632 unsigned firstDataArg, FormatStringType Type, 2633 bool inFunctionCall) { 2634 2635 // CHECK: is the format string a wide literal? 2636 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 2637 CheckFormatHandler::EmitFormatDiagnostic( 2638 *this, inFunctionCall, Args[format_idx], 2639 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 2640 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 2641 return; 2642 } 2643 2644 // Str - The format string. NOTE: this is NOT null-terminated! 2645 StringRef StrRef = FExpr->getString(); 2646 const char *Str = StrRef.data(); 2647 unsigned StrLen = StrRef.size(); 2648 const unsigned numDataArgs = NumArgs - firstDataArg; 2649 2650 // CHECK: empty format string? 2651 if (StrLen == 0 && numDataArgs > 0) { 2652 CheckFormatHandler::EmitFormatDiagnostic( 2653 *this, inFunctionCall, Args[format_idx], 2654 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 2655 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 2656 return; 2657 } 2658 2659 if (Type == FST_Printf || Type == FST_NSString) { 2660 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 2661 numDataArgs, (Type == FST_NSString), 2662 Str, HasVAListArg, Args, NumArgs, format_idx, 2663 inFunctionCall); 2664 2665 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 2666 getLangOpts())) 2667 H.DoneProcessing(); 2668 } else if (Type == FST_Scanf) { 2669 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs, 2670 Str, HasVAListArg, Args, NumArgs, format_idx, 2671 inFunctionCall); 2672 2673 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 2674 getLangOpts())) 2675 H.DoneProcessing(); 2676 } // TODO: handle other formats 2677} 2678 2679//===--- CHECK: Standard memory functions ---------------------------------===// 2680 2681/// \brief Determine whether the given type is a dynamic class type (e.g., 2682/// whether it has a vtable). 2683static bool isDynamicClassType(QualType T) { 2684 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 2685 if (CXXRecordDecl *Definition = Record->getDefinition()) 2686 if (Definition->isDynamicClass()) 2687 return true; 2688 2689 return false; 2690} 2691 2692/// \brief If E is a sizeof expression, returns its argument expression, 2693/// otherwise returns NULL. 2694static const Expr *getSizeOfExprArg(const Expr* E) { 2695 if (const UnaryExprOrTypeTraitExpr *SizeOf = 2696 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 2697 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 2698 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 2699 2700 return 0; 2701} 2702 2703/// \brief If E is a sizeof expression, returns its argument type. 2704static QualType getSizeOfArgType(const Expr* E) { 2705 if (const UnaryExprOrTypeTraitExpr *SizeOf = 2706 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 2707 if (SizeOf->getKind() == clang::UETT_SizeOf) 2708 return SizeOf->getTypeOfArgument(); 2709 2710 return QualType(); 2711} 2712 2713/// \brief Check for dangerous or invalid arguments to memset(). 2714/// 2715/// This issues warnings on known problematic, dangerous or unspecified 2716/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 2717/// function calls. 2718/// 2719/// \param Call The call expression to diagnose. 2720void Sema::CheckMemaccessArguments(const CallExpr *Call, 2721 unsigned BId, 2722 IdentifierInfo *FnName) { 2723 assert(BId != 0); 2724 2725 // It is possible to have a non-standard definition of memset. Validate 2726 // we have enough arguments, and if not, abort further checking. 2727 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3); 2728 if (Call->getNumArgs() < ExpectedNumArgs) 2729 return; 2730 2731 unsigned LastArg = (BId == Builtin::BImemset || 2732 BId == Builtin::BIstrndup ? 1 : 2); 2733 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2); 2734 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 2735 2736 // We have special checking when the length is a sizeof expression. 2737 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 2738 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 2739 llvm::FoldingSetNodeID SizeOfArgID; 2740 2741 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 2742 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 2743 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 2744 2745 QualType DestTy = Dest->getType(); 2746 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 2747 QualType PointeeTy = DestPtrTy->getPointeeType(); 2748 2749 // Never warn about void type pointers. This can be used to suppress 2750 // false positives. 2751 if (PointeeTy->isVoidType()) 2752 continue; 2753 2754 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 2755 // actually comparing the expressions for equality. Because computing the 2756 // expression IDs can be expensive, we only do this if the diagnostic is 2757 // enabled. 2758 if (SizeOfArg && 2759 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess, 2760 SizeOfArg->getExprLoc())) { 2761 // We only compute IDs for expressions if the warning is enabled, and 2762 // cache the sizeof arg's ID. 2763 if (SizeOfArgID == llvm::FoldingSetNodeID()) 2764 SizeOfArg->Profile(SizeOfArgID, Context, true); 2765 llvm::FoldingSetNodeID DestID; 2766 Dest->Profile(DestID, Context, true); 2767 if (DestID == SizeOfArgID) { 2768 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 2769 // over sizeof(src) as well. 2770 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 2771 StringRef ReadableName = FnName->getName(); 2772 2773 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 2774 if (UnaryOp->getOpcode() == UO_AddrOf) 2775 ActionIdx = 1; // If its an address-of operator, just remove it. 2776 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth()) 2777 ActionIdx = 2; // If the pointee's size is sizeof(char), 2778 // suggest an explicit length. 2779 2780 // If the function is defined as a builtin macro, do not show macro 2781 // expansion. 2782 SourceLocation SL = SizeOfArg->getExprLoc(); 2783 SourceRange DSR = Dest->getSourceRange(); 2784 SourceRange SSR = SizeOfArg->getSourceRange(); 2785 SourceManager &SM = PP.getSourceManager(); 2786 2787 if (SM.isMacroArgExpansion(SL)) { 2788 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 2789 SL = SM.getSpellingLoc(SL); 2790 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 2791 SM.getSpellingLoc(DSR.getEnd())); 2792 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 2793 SM.getSpellingLoc(SSR.getEnd())); 2794 } 2795 2796 DiagRuntimeBehavior(SL, SizeOfArg, 2797 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 2798 << ReadableName 2799 << PointeeTy 2800 << DestTy 2801 << DSR 2802 << SSR); 2803 DiagRuntimeBehavior(SL, SizeOfArg, 2804 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 2805 << ActionIdx 2806 << SSR); 2807 2808 break; 2809 } 2810 } 2811 2812 // Also check for cases where the sizeof argument is the exact same 2813 // type as the memory argument, and where it points to a user-defined 2814 // record type. 2815 if (SizeOfArgTy != QualType()) { 2816 if (PointeeTy->isRecordType() && 2817 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 2818 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 2819 PDiag(diag::warn_sizeof_pointer_type_memaccess) 2820 << FnName << SizeOfArgTy << ArgIdx 2821 << PointeeTy << Dest->getSourceRange() 2822 << LenExpr->getSourceRange()); 2823 break; 2824 } 2825 } 2826 2827 // Always complain about dynamic classes. 2828 if (isDynamicClassType(PointeeTy)) { 2829 2830 unsigned OperationType = 0; 2831 // "overwritten" if we're warning about the destination for any call 2832 // but memcmp; otherwise a verb appropriate to the call. 2833 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 2834 if (BId == Builtin::BImemcpy) 2835 OperationType = 1; 2836 else if(BId == Builtin::BImemmove) 2837 OperationType = 2; 2838 else if (BId == Builtin::BImemcmp) 2839 OperationType = 3; 2840 } 2841 2842 DiagRuntimeBehavior( 2843 Dest->getExprLoc(), Dest, 2844 PDiag(diag::warn_dyn_class_memaccess) 2845 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 2846 << FnName << PointeeTy 2847 << OperationType 2848 << Call->getCallee()->getSourceRange()); 2849 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 2850 BId != Builtin::BImemset) 2851 DiagRuntimeBehavior( 2852 Dest->getExprLoc(), Dest, 2853 PDiag(diag::warn_arc_object_memaccess) 2854 << ArgIdx << FnName << PointeeTy 2855 << Call->getCallee()->getSourceRange()); 2856 else 2857 continue; 2858 2859 DiagRuntimeBehavior( 2860 Dest->getExprLoc(), Dest, 2861 PDiag(diag::note_bad_memaccess_silence) 2862 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 2863 break; 2864 } 2865 } 2866} 2867 2868// A little helper routine: ignore addition and subtraction of integer literals. 2869// This intentionally does not ignore all integer constant expressions because 2870// we don't want to remove sizeof(). 2871static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 2872 Ex = Ex->IgnoreParenCasts(); 2873 2874 for (;;) { 2875 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 2876 if (!BO || !BO->isAdditiveOp()) 2877 break; 2878 2879 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 2880 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 2881 2882 if (isa<IntegerLiteral>(RHS)) 2883 Ex = LHS; 2884 else if (isa<IntegerLiteral>(LHS)) 2885 Ex = RHS; 2886 else 2887 break; 2888 } 2889 2890 return Ex; 2891} 2892 2893// Warn if the user has made the 'size' argument to strlcpy or strlcat 2894// be the size of the source, instead of the destination. 2895void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 2896 IdentifierInfo *FnName) { 2897 2898 // Don't crash if the user has the wrong number of arguments 2899 if (Call->getNumArgs() != 3) 2900 return; 2901 2902 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 2903 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 2904 const Expr *CompareWithSrc = NULL; 2905 2906 // Look for 'strlcpy(dst, x, sizeof(x))' 2907 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 2908 CompareWithSrc = Ex; 2909 else { 2910 // Look for 'strlcpy(dst, x, strlen(x))' 2911 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 2912 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen 2913 && SizeCall->getNumArgs() == 1) 2914 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 2915 } 2916 } 2917 2918 if (!CompareWithSrc) 2919 return; 2920 2921 // Determine if the argument to sizeof/strlen is equal to the source 2922 // argument. In principle there's all kinds of things you could do 2923 // here, for instance creating an == expression and evaluating it with 2924 // EvaluateAsBooleanCondition, but this uses a more direct technique: 2925 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 2926 if (!SrcArgDRE) 2927 return; 2928 2929 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 2930 if (!CompareWithSrcDRE || 2931 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 2932 return; 2933 2934 const Expr *OriginalSizeArg = Call->getArg(2); 2935 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 2936 << OriginalSizeArg->getSourceRange() << FnName; 2937 2938 // Output a FIXIT hint if the destination is an array (rather than a 2939 // pointer to an array). This could be enhanced to handle some 2940 // pointers if we know the actual size, like if DstArg is 'array+2' 2941 // we could say 'sizeof(array)-2'. 2942 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 2943 QualType DstArgTy = DstArg->getType(); 2944 2945 // Only handle constant-sized or VLAs, but not flexible members. 2946 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) { 2947 // Only issue the FIXIT for arrays of size > 1. 2948 if (CAT->getSize().getSExtValue() <= 1) 2949 return; 2950 } else if (!DstArgTy->isVariableArrayType()) { 2951 return; 2952 } 2953 2954 SmallString<128> sizeString; 2955 llvm::raw_svector_ostream OS(sizeString); 2956 OS << "sizeof("; 2957 DstArg->printPretty(OS, Context, 0, getPrintingPolicy()); 2958 OS << ")"; 2959 2960 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 2961 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 2962 OS.str()); 2963} 2964 2965/// Check if two expressions refer to the same declaration. 2966static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 2967 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 2968 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 2969 return D1->getDecl() == D2->getDecl(); 2970 return false; 2971} 2972 2973static const Expr *getStrlenExprArg(const Expr *E) { 2974 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 2975 const FunctionDecl *FD = CE->getDirectCallee(); 2976 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 2977 return 0; 2978 return CE->getArg(0)->IgnoreParenCasts(); 2979 } 2980 return 0; 2981} 2982 2983// Warn on anti-patterns as the 'size' argument to strncat. 2984// The correct size argument should look like following: 2985// strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 2986void Sema::CheckStrncatArguments(const CallExpr *CE, 2987 IdentifierInfo *FnName) { 2988 // Don't crash if the user has the wrong number of arguments. 2989 if (CE->getNumArgs() < 3) 2990 return; 2991 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 2992 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 2993 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 2994 2995 // Identify common expressions, which are wrongly used as the size argument 2996 // to strncat and may lead to buffer overflows. 2997 unsigned PatternType = 0; 2998 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 2999 // - sizeof(dst) 3000 if (referToTheSameDecl(SizeOfArg, DstArg)) 3001 PatternType = 1; 3002 // - sizeof(src) 3003 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 3004 PatternType = 2; 3005 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 3006 if (BE->getOpcode() == BO_Sub) { 3007 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 3008 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 3009 // - sizeof(dst) - strlen(dst) 3010 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 3011 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 3012 PatternType = 1; 3013 // - sizeof(src) - (anything) 3014 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 3015 PatternType = 2; 3016 } 3017 } 3018 3019 if (PatternType == 0) 3020 return; 3021 3022 // Generate the diagnostic. 3023 SourceLocation SL = LenArg->getLocStart(); 3024 SourceRange SR = LenArg->getSourceRange(); 3025 SourceManager &SM = PP.getSourceManager(); 3026 3027 // If the function is defined as a builtin macro, do not show macro expansion. 3028 if (SM.isMacroArgExpansion(SL)) { 3029 SL = SM.getSpellingLoc(SL); 3030 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 3031 SM.getSpellingLoc(SR.getEnd())); 3032 } 3033 3034 if (PatternType == 1) 3035 Diag(SL, diag::warn_strncat_large_size) << SR; 3036 else 3037 Diag(SL, diag::warn_strncat_src_size) << SR; 3038 3039 // Output a FIXIT hint if the destination is an array (rather than a 3040 // pointer to an array). This could be enhanced to handle some 3041 // pointers if we know the actual size, like if DstArg is 'array+2' 3042 // we could say 'sizeof(array)-2'. 3043 QualType DstArgTy = DstArg->getType(); 3044 3045 // Only handle constant-sized or VLAs, but not flexible members. 3046 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) { 3047 // Only issue the FIXIT for arrays of size > 1. 3048 if (CAT->getSize().getSExtValue() <= 1) 3049 return; 3050 } else if (!DstArgTy->isVariableArrayType()) { 3051 return; 3052 } 3053 3054 SmallString<128> sizeString; 3055 llvm::raw_svector_ostream OS(sizeString); 3056 OS << "sizeof("; 3057 DstArg->printPretty(OS, Context, 0, getPrintingPolicy()); 3058 OS << ") - "; 3059 OS << "strlen("; 3060 DstArg->printPretty(OS, Context, 0, getPrintingPolicy()); 3061 OS << ") - 1"; 3062 3063 Diag(SL, diag::note_strncat_wrong_size) 3064 << FixItHint::CreateReplacement(SR, OS.str()); 3065} 3066 3067//===--- CHECK: Return Address of Stack Variable --------------------------===// 3068 3069static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 3070 Decl *ParentDecl); 3071static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars, 3072 Decl *ParentDecl); 3073 3074/// CheckReturnStackAddr - Check if a return statement returns the address 3075/// of a stack variable. 3076void 3077Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 3078 SourceLocation ReturnLoc) { 3079 3080 Expr *stackE = 0; 3081 SmallVector<DeclRefExpr *, 8> refVars; 3082 3083 // Perform checking for returned stack addresses, local blocks, 3084 // label addresses or references to temporaries. 3085 if (lhsType->isPointerType() || 3086 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 3087 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0); 3088 } else if (lhsType->isReferenceType()) { 3089 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0); 3090 } 3091 3092 if (stackE == 0) 3093 return; // Nothing suspicious was found. 3094 3095 SourceLocation diagLoc; 3096 SourceRange diagRange; 3097 if (refVars.empty()) { 3098 diagLoc = stackE->getLocStart(); 3099 diagRange = stackE->getSourceRange(); 3100 } else { 3101 // We followed through a reference variable. 'stackE' contains the 3102 // problematic expression but we will warn at the return statement pointing 3103 // at the reference variable. We will later display the "trail" of 3104 // reference variables using notes. 3105 diagLoc = refVars[0]->getLocStart(); 3106 diagRange = refVars[0]->getSourceRange(); 3107 } 3108 3109 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var. 3110 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref 3111 : diag::warn_ret_stack_addr) 3112 << DR->getDecl()->getDeclName() << diagRange; 3113 } else if (isa<BlockExpr>(stackE)) { // local block. 3114 Diag(diagLoc, diag::err_ret_local_block) << diagRange; 3115 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 3116 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 3117 } else { // local temporary. 3118 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref 3119 : diag::warn_ret_local_temp_addr) 3120 << diagRange; 3121 } 3122 3123 // Display the "trail" of reference variables that we followed until we 3124 // found the problematic expression using notes. 3125 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 3126 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 3127 // If this var binds to another reference var, show the range of the next 3128 // var, otherwise the var binds to the problematic expression, in which case 3129 // show the range of the expression. 3130 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange() 3131 : stackE->getSourceRange(); 3132 Diag(VD->getLocation(), diag::note_ref_var_local_bind) 3133 << VD->getDeclName() << range; 3134 } 3135} 3136 3137/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 3138/// check if the expression in a return statement evaluates to an address 3139/// to a location on the stack, a local block, an address of a label, or a 3140/// reference to local temporary. The recursion is used to traverse the 3141/// AST of the return expression, with recursion backtracking when we 3142/// encounter a subexpression that (1) clearly does not lead to one of the 3143/// above problematic expressions (2) is something we cannot determine leads to 3144/// a problematic expression based on such local checking. 3145/// 3146/// Both EvalAddr and EvalVal follow through reference variables to evaluate 3147/// the expression that they point to. Such variables are added to the 3148/// 'refVars' vector so that we know what the reference variable "trail" was. 3149/// 3150/// EvalAddr processes expressions that are pointers that are used as 3151/// references (and not L-values). EvalVal handles all other values. 3152/// At the base case of the recursion is a check for the above problematic 3153/// expressions. 3154/// 3155/// This implementation handles: 3156/// 3157/// * pointer-to-pointer casts 3158/// * implicit conversions from array references to pointers 3159/// * taking the address of fields 3160/// * arbitrary interplay between "&" and "*" operators 3161/// * pointer arithmetic from an address of a stack variable 3162/// * taking the address of an array element where the array is on the stack 3163static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 3164 Decl *ParentDecl) { 3165 if (E->isTypeDependent()) 3166 return NULL; 3167 3168 // We should only be called for evaluating pointer expressions. 3169 assert((E->getType()->isAnyPointerType() || 3170 E->getType()->isBlockPointerType() || 3171 E->getType()->isObjCQualifiedIdType()) && 3172 "EvalAddr only works on pointers"); 3173 3174 E = E->IgnoreParens(); 3175 3176 // Our "symbolic interpreter" is just a dispatch off the currently 3177 // viewed AST node. We then recursively traverse the AST by calling 3178 // EvalAddr and EvalVal appropriately. 3179 switch (E->getStmtClass()) { 3180 case Stmt::DeclRefExprClass: { 3181 DeclRefExpr *DR = cast<DeclRefExpr>(E); 3182 3183 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 3184 // If this is a reference variable, follow through to the expression that 3185 // it points to. 3186 if (V->hasLocalStorage() && 3187 V->getType()->isReferenceType() && V->hasInit()) { 3188 // Add the reference variable to the "trail". 3189 refVars.push_back(DR); 3190 return EvalAddr(V->getInit(), refVars, ParentDecl); 3191 } 3192 3193 return NULL; 3194 } 3195 3196 case Stmt::UnaryOperatorClass: { 3197 // The only unary operator that make sense to handle here 3198 // is AddrOf. All others don't make sense as pointers. 3199 UnaryOperator *U = cast<UnaryOperator>(E); 3200 3201 if (U->getOpcode() == UO_AddrOf) 3202 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 3203 else 3204 return NULL; 3205 } 3206 3207 case Stmt::BinaryOperatorClass: { 3208 // Handle pointer arithmetic. All other binary operators are not valid 3209 // in this context. 3210 BinaryOperator *B = cast<BinaryOperator>(E); 3211 BinaryOperatorKind op = B->getOpcode(); 3212 3213 if (op != BO_Add && op != BO_Sub) 3214 return NULL; 3215 3216 Expr *Base = B->getLHS(); 3217 3218 // Determine which argument is the real pointer base. It could be 3219 // the RHS argument instead of the LHS. 3220 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 3221 3222 assert (Base->getType()->isPointerType()); 3223 return EvalAddr(Base, refVars, ParentDecl); 3224 } 3225 3226 // For conditional operators we need to see if either the LHS or RHS are 3227 // valid DeclRefExpr*s. If one of them is valid, we return it. 3228 case Stmt::ConditionalOperatorClass: { 3229 ConditionalOperator *C = cast<ConditionalOperator>(E); 3230 3231 // Handle the GNU extension for missing LHS. 3232 if (Expr *lhsExpr = C->getLHS()) { 3233 // In C++, we can have a throw-expression, which has 'void' type. 3234 if (!lhsExpr->getType()->isVoidType()) 3235 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl)) 3236 return LHS; 3237 } 3238 3239 // In C++, we can have a throw-expression, which has 'void' type. 3240 if (C->getRHS()->getType()->isVoidType()) 3241 return NULL; 3242 3243 return EvalAddr(C->getRHS(), refVars, ParentDecl); 3244 } 3245 3246 case Stmt::BlockExprClass: 3247 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 3248 return E; // local block. 3249 return NULL; 3250 3251 case Stmt::AddrLabelExprClass: 3252 return E; // address of label. 3253 3254 case Stmt::ExprWithCleanupsClass: 3255 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 3256 ParentDecl); 3257 3258 // For casts, we need to handle conversions from arrays to 3259 // pointer values, and pointer-to-pointer conversions. 3260 case Stmt::ImplicitCastExprClass: 3261 case Stmt::CStyleCastExprClass: 3262 case Stmt::CXXFunctionalCastExprClass: 3263 case Stmt::ObjCBridgedCastExprClass: 3264 case Stmt::CXXStaticCastExprClass: 3265 case Stmt::CXXDynamicCastExprClass: 3266 case Stmt::CXXConstCastExprClass: 3267 case Stmt::CXXReinterpretCastExprClass: { 3268 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 3269 switch (cast<CastExpr>(E)->getCastKind()) { 3270 case CK_BitCast: 3271 case CK_LValueToRValue: 3272 case CK_NoOp: 3273 case CK_BaseToDerived: 3274 case CK_DerivedToBase: 3275 case CK_UncheckedDerivedToBase: 3276 case CK_Dynamic: 3277 case CK_CPointerToObjCPointerCast: 3278 case CK_BlockPointerToObjCPointerCast: 3279 case CK_AnyPointerToBlockPointerCast: 3280 return EvalAddr(SubExpr, refVars, ParentDecl); 3281 3282 case CK_ArrayToPointerDecay: 3283 return EvalVal(SubExpr, refVars, ParentDecl); 3284 3285 default: 3286 return 0; 3287 } 3288 } 3289 3290 case Stmt::MaterializeTemporaryExprClass: 3291 if (Expr *Result = EvalAddr( 3292 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 3293 refVars, ParentDecl)) 3294 return Result; 3295 3296 return E; 3297 3298 // Everything else: we simply don't reason about them. 3299 default: 3300 return NULL; 3301 } 3302} 3303 3304 3305/// EvalVal - This function is complements EvalAddr in the mutual recursion. 3306/// See the comments for EvalAddr for more details. 3307static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 3308 Decl *ParentDecl) { 3309do { 3310 // We should only be called for evaluating non-pointer expressions, or 3311 // expressions with a pointer type that are not used as references but instead 3312 // are l-values (e.g., DeclRefExpr with a pointer type). 3313 3314 // Our "symbolic interpreter" is just a dispatch off the currently 3315 // viewed AST node. We then recursively traverse the AST by calling 3316 // EvalAddr and EvalVal appropriately. 3317 3318 E = E->IgnoreParens(); 3319 switch (E->getStmtClass()) { 3320 case Stmt::ImplicitCastExprClass: { 3321 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 3322 if (IE->getValueKind() == VK_LValue) { 3323 E = IE->getSubExpr(); 3324 continue; 3325 } 3326 return NULL; 3327 } 3328 3329 case Stmt::ExprWithCleanupsClass: 3330 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl); 3331 3332 case Stmt::DeclRefExprClass: { 3333 // When we hit a DeclRefExpr we are looking at code that refers to a 3334 // variable's name. If it's not a reference variable we check if it has 3335 // local storage within the function, and if so, return the expression. 3336 DeclRefExpr *DR = cast<DeclRefExpr>(E); 3337 3338 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 3339 // Check if it refers to itself, e.g. "int& i = i;". 3340 if (V == ParentDecl) 3341 return DR; 3342 3343 if (V->hasLocalStorage()) { 3344 if (!V->getType()->isReferenceType()) 3345 return DR; 3346 3347 // Reference variable, follow through to the expression that 3348 // it points to. 3349 if (V->hasInit()) { 3350 // Add the reference variable to the "trail". 3351 refVars.push_back(DR); 3352 return EvalVal(V->getInit(), refVars, V); 3353 } 3354 } 3355 } 3356 3357 return NULL; 3358 } 3359 3360 case Stmt::UnaryOperatorClass: { 3361 // The only unary operator that make sense to handle here 3362 // is Deref. All others don't resolve to a "name." This includes 3363 // handling all sorts of rvalues passed to a unary operator. 3364 UnaryOperator *U = cast<UnaryOperator>(E); 3365 3366 if (U->getOpcode() == UO_Deref) 3367 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 3368 3369 return NULL; 3370 } 3371 3372 case Stmt::ArraySubscriptExprClass: { 3373 // Array subscripts are potential references to data on the stack. We 3374 // retrieve the DeclRefExpr* for the array variable if it indeed 3375 // has local storage. 3376 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl); 3377 } 3378 3379 case Stmt::ConditionalOperatorClass: { 3380 // For conditional operators we need to see if either the LHS or RHS are 3381 // non-NULL Expr's. If one is non-NULL, we return it. 3382 ConditionalOperator *C = cast<ConditionalOperator>(E); 3383 3384 // Handle the GNU extension for missing LHS. 3385 if (Expr *lhsExpr = C->getLHS()) 3386 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl)) 3387 return LHS; 3388 3389 return EvalVal(C->getRHS(), refVars, ParentDecl); 3390 } 3391 3392 // Accesses to members are potential references to data on the stack. 3393 case Stmt::MemberExprClass: { 3394 MemberExpr *M = cast<MemberExpr>(E); 3395 3396 // Check for indirect access. We only want direct field accesses. 3397 if (M->isArrow()) 3398 return NULL; 3399 3400 // Check whether the member type is itself a reference, in which case 3401 // we're not going to refer to the member, but to what the member refers to. 3402 if (M->getMemberDecl()->getType()->isReferenceType()) 3403 return NULL; 3404 3405 return EvalVal(M->getBase(), refVars, ParentDecl); 3406 } 3407 3408 case Stmt::MaterializeTemporaryExprClass: 3409 if (Expr *Result = EvalVal( 3410 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 3411 refVars, ParentDecl)) 3412 return Result; 3413 3414 return E; 3415 3416 default: 3417 // Check that we don't return or take the address of a reference to a 3418 // temporary. This is only useful in C++. 3419 if (!E->isTypeDependent() && E->isRValue()) 3420 return E; 3421 3422 // Everything else: we simply don't reason about them. 3423 return NULL; 3424 } 3425} while (true); 3426} 3427 3428//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 3429 3430/// Check for comparisons of floating point operands using != and ==. 3431/// Issue a warning if these are no self-comparisons, as they are not likely 3432/// to do what the programmer intended. 3433void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 3434 bool EmitWarning = true; 3435 3436 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 3437 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 3438 3439 // Special case: check for x == x (which is OK). 3440 // Do not emit warnings for such cases. 3441 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 3442 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 3443 if (DRL->getDecl() == DRR->getDecl()) 3444 EmitWarning = false; 3445 3446 3447 // Special case: check for comparisons against literals that can be exactly 3448 // represented by APFloat. In such cases, do not emit a warning. This 3449 // is a heuristic: often comparison against such literals are used to 3450 // detect if a value in a variable has not changed. This clearly can 3451 // lead to false negatives. 3452 if (EmitWarning) { 3453 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 3454 if (FLL->isExact()) 3455 EmitWarning = false; 3456 } else 3457 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){ 3458 if (FLR->isExact()) 3459 EmitWarning = false; 3460 } 3461 } 3462 3463 // Check for comparisons with builtin types. 3464 if (EmitWarning) 3465 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 3466 if (CL->isBuiltinCall()) 3467 EmitWarning = false; 3468 3469 if (EmitWarning) 3470 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 3471 if (CR->isBuiltinCall()) 3472 EmitWarning = false; 3473 3474 // Emit the diagnostic. 3475 if (EmitWarning) 3476 Diag(Loc, diag::warn_floatingpoint_eq) 3477 << LHS->getSourceRange() << RHS->getSourceRange(); 3478} 3479 3480//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 3481//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 3482 3483namespace { 3484 3485/// Structure recording the 'active' range of an integer-valued 3486/// expression. 3487struct IntRange { 3488 /// The number of bits active in the int. 3489 unsigned Width; 3490 3491 /// True if the int is known not to have negative values. 3492 bool NonNegative; 3493 3494 IntRange(unsigned Width, bool NonNegative) 3495 : Width(Width), NonNegative(NonNegative) 3496 {} 3497 3498 /// Returns the range of the bool type. 3499 static IntRange forBoolType() { 3500 return IntRange(1, true); 3501 } 3502 3503 /// Returns the range of an opaque value of the given integral type. 3504 static IntRange forValueOfType(ASTContext &C, QualType T) { 3505 return forValueOfCanonicalType(C, 3506 T->getCanonicalTypeInternal().getTypePtr()); 3507 } 3508 3509 /// Returns the range of an opaque value of a canonical integral type. 3510 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 3511 assert(T->isCanonicalUnqualified()); 3512 3513 if (const VectorType *VT = dyn_cast<VectorType>(T)) 3514 T = VT->getElementType().getTypePtr(); 3515 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 3516 T = CT->getElementType().getTypePtr(); 3517 3518 // For enum types, use the known bit width of the enumerators. 3519 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 3520 EnumDecl *Enum = ET->getDecl(); 3521 if (!Enum->isCompleteDefinition()) 3522 return IntRange(C.getIntWidth(QualType(T, 0)), false); 3523 3524 unsigned NumPositive = Enum->getNumPositiveBits(); 3525 unsigned NumNegative = Enum->getNumNegativeBits(); 3526 3527 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0); 3528 } 3529 3530 const BuiltinType *BT = cast<BuiltinType>(T); 3531 assert(BT->isInteger()); 3532 3533 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 3534 } 3535 3536 /// Returns the "target" range of a canonical integral type, i.e. 3537 /// the range of values expressible in the type. 3538 /// 3539 /// This matches forValueOfCanonicalType except that enums have the 3540 /// full range of their type, not the range of their enumerators. 3541 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 3542 assert(T->isCanonicalUnqualified()); 3543 3544 if (const VectorType *VT = dyn_cast<VectorType>(T)) 3545 T = VT->getElementType().getTypePtr(); 3546 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 3547 T = CT->getElementType().getTypePtr(); 3548 if (const EnumType *ET = dyn_cast<EnumType>(T)) 3549 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 3550 3551 const BuiltinType *BT = cast<BuiltinType>(T); 3552 assert(BT->isInteger()); 3553 3554 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 3555 } 3556 3557 /// Returns the supremum of two ranges: i.e. their conservative merge. 3558 static IntRange join(IntRange L, IntRange R) { 3559 return IntRange(std::max(L.Width, R.Width), 3560 L.NonNegative && R.NonNegative); 3561 } 3562 3563 /// Returns the infinum of two ranges: i.e. their aggressive merge. 3564 static IntRange meet(IntRange L, IntRange R) { 3565 return IntRange(std::min(L.Width, R.Width), 3566 L.NonNegative || R.NonNegative); 3567 } 3568}; 3569 3570static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 3571 unsigned MaxWidth) { 3572 if (value.isSigned() && value.isNegative()) 3573 return IntRange(value.getMinSignedBits(), false); 3574 3575 if (value.getBitWidth() > MaxWidth) 3576 value = value.trunc(MaxWidth); 3577 3578 // isNonNegative() just checks the sign bit without considering 3579 // signedness. 3580 return IntRange(value.getActiveBits(), true); 3581} 3582 3583static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 3584 unsigned MaxWidth) { 3585 if (result.isInt()) 3586 return GetValueRange(C, result.getInt(), MaxWidth); 3587 3588 if (result.isVector()) { 3589 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 3590 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 3591 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 3592 R = IntRange::join(R, El); 3593 } 3594 return R; 3595 } 3596 3597 if (result.isComplexInt()) { 3598 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 3599 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 3600 return IntRange::join(R, I); 3601 } 3602 3603 // This can happen with lossless casts to intptr_t of "based" lvalues. 3604 // Assume it might use arbitrary bits. 3605 // FIXME: The only reason we need to pass the type in here is to get 3606 // the sign right on this one case. It would be nice if APValue 3607 // preserved this. 3608 assert(result.isLValue() || result.isAddrLabelDiff()); 3609 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 3610} 3611 3612/// Pseudo-evaluate the given integer expression, estimating the 3613/// range of values it might take. 3614/// 3615/// \param MaxWidth - the width to which the value will be truncated 3616static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { 3617 E = E->IgnoreParens(); 3618 3619 // Try a full evaluation first. 3620 Expr::EvalResult result; 3621 if (E->EvaluateAsRValue(result, C)) 3622 return GetValueRange(C, result.Val, E->getType(), MaxWidth); 3623 3624 // I think we only want to look through implicit casts here; if the 3625 // user has an explicit widening cast, we should treat the value as 3626 // being of the new, wider type. 3627 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 3628 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 3629 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 3630 3631 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType()); 3632 3633 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast); 3634 3635 // Assume that non-integer casts can span the full range of the type. 3636 if (!isIntegerCast) 3637 return OutputTypeRange; 3638 3639 IntRange SubRange 3640 = GetExprRange(C, CE->getSubExpr(), 3641 std::min(MaxWidth, OutputTypeRange.Width)); 3642 3643 // Bail out if the subexpr's range is as wide as the cast type. 3644 if (SubRange.Width >= OutputTypeRange.Width) 3645 return OutputTypeRange; 3646 3647 // Otherwise, we take the smaller width, and we're non-negative if 3648 // either the output type or the subexpr is. 3649 return IntRange(SubRange.Width, 3650 SubRange.NonNegative || OutputTypeRange.NonNegative); 3651 } 3652 3653 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3654 // If we can fold the condition, just take that operand. 3655 bool CondResult; 3656 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 3657 return GetExprRange(C, CondResult ? CO->getTrueExpr() 3658 : CO->getFalseExpr(), 3659 MaxWidth); 3660 3661 // Otherwise, conservatively merge. 3662 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 3663 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 3664 return IntRange::join(L, R); 3665 } 3666 3667 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3668 switch (BO->getOpcode()) { 3669 3670 // Boolean-valued operations are single-bit and positive. 3671 case BO_LAnd: 3672 case BO_LOr: 3673 case BO_LT: 3674 case BO_GT: 3675 case BO_LE: 3676 case BO_GE: 3677 case BO_EQ: 3678 case BO_NE: 3679 return IntRange::forBoolType(); 3680 3681 // The type of the assignments is the type of the LHS, so the RHS 3682 // is not necessarily the same type. 3683 case BO_MulAssign: 3684 case BO_DivAssign: 3685 case BO_RemAssign: 3686 case BO_AddAssign: 3687 case BO_SubAssign: 3688 case BO_XorAssign: 3689 case BO_OrAssign: 3690 // TODO: bitfields? 3691 return IntRange::forValueOfType(C, E->getType()); 3692 3693 // Simple assignments just pass through the RHS, which will have 3694 // been coerced to the LHS type. 3695 case BO_Assign: 3696 // TODO: bitfields? 3697 return GetExprRange(C, BO->getRHS(), MaxWidth); 3698 3699 // Operations with opaque sources are black-listed. 3700 case BO_PtrMemD: 3701 case BO_PtrMemI: 3702 return IntRange::forValueOfType(C, E->getType()); 3703 3704 // Bitwise-and uses the *infinum* of the two source ranges. 3705 case BO_And: 3706 case BO_AndAssign: 3707 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 3708 GetExprRange(C, BO->getRHS(), MaxWidth)); 3709 3710 // Left shift gets black-listed based on a judgement call. 3711 case BO_Shl: 3712 // ...except that we want to treat '1 << (blah)' as logically 3713 // positive. It's an important idiom. 3714 if (IntegerLiteral *I 3715 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 3716 if (I->getValue() == 1) { 3717 IntRange R = IntRange::forValueOfType(C, E->getType()); 3718 return IntRange(R.Width, /*NonNegative*/ true); 3719 } 3720 } 3721 // fallthrough 3722 3723 case BO_ShlAssign: 3724 return IntRange::forValueOfType(C, E->getType()); 3725 3726 // Right shift by a constant can narrow its left argument. 3727 case BO_Shr: 3728 case BO_ShrAssign: { 3729 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 3730 3731 // If the shift amount is a positive constant, drop the width by 3732 // that much. 3733 llvm::APSInt shift; 3734 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 3735 shift.isNonNegative()) { 3736 unsigned zext = shift.getZExtValue(); 3737 if (zext >= L.Width) 3738 L.Width = (L.NonNegative ? 0 : 1); 3739 else 3740 L.Width -= zext; 3741 } 3742 3743 return L; 3744 } 3745 3746 // Comma acts as its right operand. 3747 case BO_Comma: 3748 return GetExprRange(C, BO->getRHS(), MaxWidth); 3749 3750 // Black-list pointer subtractions. 3751 case BO_Sub: 3752 if (BO->getLHS()->getType()->isPointerType()) 3753 return IntRange::forValueOfType(C, E->getType()); 3754 break; 3755 3756 // The width of a division result is mostly determined by the size 3757 // of the LHS. 3758 case BO_Div: { 3759 // Don't 'pre-truncate' the operands. 3760 unsigned opWidth = C.getIntWidth(E->getType()); 3761 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 3762 3763 // If the divisor is constant, use that. 3764 llvm::APSInt divisor; 3765 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 3766 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 3767 if (log2 >= L.Width) 3768 L.Width = (L.NonNegative ? 0 : 1); 3769 else 3770 L.Width = std::min(L.Width - log2, MaxWidth); 3771 return L; 3772 } 3773 3774 // Otherwise, just use the LHS's width. 3775 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 3776 return IntRange(L.Width, L.NonNegative && R.NonNegative); 3777 } 3778 3779 // The result of a remainder can't be larger than the result of 3780 // either side. 3781 case BO_Rem: { 3782 // Don't 'pre-truncate' the operands. 3783 unsigned opWidth = C.getIntWidth(E->getType()); 3784 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 3785 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 3786 3787 IntRange meet = IntRange::meet(L, R); 3788 meet.Width = std::min(meet.Width, MaxWidth); 3789 return meet; 3790 } 3791 3792 // The default behavior is okay for these. 3793 case BO_Mul: 3794 case BO_Add: 3795 case BO_Xor: 3796 case BO_Or: 3797 break; 3798 } 3799 3800 // The default case is to treat the operation as if it were closed 3801 // on the narrowest type that encompasses both operands. 3802 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 3803 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 3804 return IntRange::join(L, R); 3805 } 3806 3807 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 3808 switch (UO->getOpcode()) { 3809 // Boolean-valued operations are white-listed. 3810 case UO_LNot: 3811 return IntRange::forBoolType(); 3812 3813 // Operations with opaque sources are black-listed. 3814 case UO_Deref: 3815 case UO_AddrOf: // should be impossible 3816 return IntRange::forValueOfType(C, E->getType()); 3817 3818 default: 3819 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 3820 } 3821 } 3822 3823 if (dyn_cast<OffsetOfExpr>(E)) { 3824 IntRange::forValueOfType(C, E->getType()); 3825 } 3826 3827 if (FieldDecl *BitField = E->getBitField()) 3828 return IntRange(BitField->getBitWidthValue(C), 3829 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 3830 3831 return IntRange::forValueOfType(C, E->getType()); 3832} 3833 3834static IntRange GetExprRange(ASTContext &C, Expr *E) { 3835 return GetExprRange(C, E, C.getIntWidth(E->getType())); 3836} 3837 3838/// Checks whether the given value, which currently has the given 3839/// source semantics, has the same value when coerced through the 3840/// target semantics. 3841static bool IsSameFloatAfterCast(const llvm::APFloat &value, 3842 const llvm::fltSemantics &Src, 3843 const llvm::fltSemantics &Tgt) { 3844 llvm::APFloat truncated = value; 3845 3846 bool ignored; 3847 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 3848 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 3849 3850 return truncated.bitwiseIsEqual(value); 3851} 3852 3853/// Checks whether the given value, which currently has the given 3854/// source semantics, has the same value when coerced through the 3855/// target semantics. 3856/// 3857/// The value might be a vector of floats (or a complex number). 3858static bool IsSameFloatAfterCast(const APValue &value, 3859 const llvm::fltSemantics &Src, 3860 const llvm::fltSemantics &Tgt) { 3861 if (value.isFloat()) 3862 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 3863 3864 if (value.isVector()) { 3865 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 3866 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 3867 return false; 3868 return true; 3869 } 3870 3871 assert(value.isComplexFloat()); 3872 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 3873 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 3874} 3875 3876static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 3877 3878static bool IsZero(Sema &S, Expr *E) { 3879 // Suppress cases where we are comparing against an enum constant. 3880 if (const DeclRefExpr *DR = 3881 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 3882 if (isa<EnumConstantDecl>(DR->getDecl())) 3883 return false; 3884 3885 // Suppress cases where the '0' value is expanded from a macro. 3886 if (E->getLocStart().isMacroID()) 3887 return false; 3888 3889 llvm::APSInt Value; 3890 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 3891} 3892 3893static bool HasEnumType(Expr *E) { 3894 // Strip off implicit integral promotions. 3895 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 3896 if (ICE->getCastKind() != CK_IntegralCast && 3897 ICE->getCastKind() != CK_NoOp) 3898 break; 3899 E = ICE->getSubExpr(); 3900 } 3901 3902 return E->getType()->isEnumeralType(); 3903} 3904 3905static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 3906 BinaryOperatorKind op = E->getOpcode(); 3907 if (E->isValueDependent()) 3908 return; 3909 3910 if (op == BO_LT && IsZero(S, E->getRHS())) { 3911 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 3912 << "< 0" << "false" << HasEnumType(E->getLHS()) 3913 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3914 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 3915 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 3916 << ">= 0" << "true" << HasEnumType(E->getLHS()) 3917 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3918 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 3919 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 3920 << "0 >" << "false" << HasEnumType(E->getRHS()) 3921 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3922 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 3923 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 3924 << "0 <=" << "true" << HasEnumType(E->getRHS()) 3925 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3926 } 3927} 3928 3929/// Analyze the operands of the given comparison. Implements the 3930/// fallback case from AnalyzeComparison. 3931static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 3932 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 3933 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 3934} 3935 3936/// \brief Implements -Wsign-compare. 3937/// 3938/// \param E the binary operator to check for warnings 3939static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 3940 // The type the comparison is being performed in. 3941 QualType T = E->getLHS()->getType(); 3942 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()) 3943 && "comparison with mismatched types"); 3944 3945 // We don't do anything special if this isn't an unsigned integral 3946 // comparison: we're only interested in integral comparisons, and 3947 // signed comparisons only happen in cases we don't care to warn about. 3948 // 3949 // We also don't care about value-dependent expressions or expressions 3950 // whose result is a constant. 3951 if (!T->hasUnsignedIntegerRepresentation() 3952 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context)) 3953 return AnalyzeImpConvsInComparison(S, E); 3954 3955 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 3956 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 3957 3958 // Check to see if one of the (unmodified) operands is of different 3959 // signedness. 3960 Expr *signedOperand, *unsignedOperand; 3961 if (LHS->getType()->hasSignedIntegerRepresentation()) { 3962 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 3963 "unsigned comparison between two signed integer expressions?"); 3964 signedOperand = LHS; 3965 unsignedOperand = RHS; 3966 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 3967 signedOperand = RHS; 3968 unsignedOperand = LHS; 3969 } else { 3970 CheckTrivialUnsignedComparison(S, E); 3971 return AnalyzeImpConvsInComparison(S, E); 3972 } 3973 3974 // Otherwise, calculate the effective range of the signed operand. 3975 IntRange signedRange = GetExprRange(S.Context, signedOperand); 3976 3977 // Go ahead and analyze implicit conversions in the operands. Note 3978 // that we skip the implicit conversions on both sides. 3979 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 3980 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 3981 3982 // If the signed range is non-negative, -Wsign-compare won't fire, 3983 // but we should still check for comparisons which are always true 3984 // or false. 3985 if (signedRange.NonNegative) 3986 return CheckTrivialUnsignedComparison(S, E); 3987 3988 // For (in)equality comparisons, if the unsigned operand is a 3989 // constant which cannot collide with a overflowed signed operand, 3990 // then reinterpreting the signed operand as unsigned will not 3991 // change the result of the comparison. 3992 if (E->isEqualityOp()) { 3993 unsigned comparisonWidth = S.Context.getIntWidth(T); 3994 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 3995 3996 // We should never be unable to prove that the unsigned operand is 3997 // non-negative. 3998 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 3999 4000 if (unsignedRange.Width < comparisonWidth) 4001 return; 4002 } 4003 4004 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 4005 S.PDiag(diag::warn_mixed_sign_comparison) 4006 << LHS->getType() << RHS->getType() 4007 << LHS->getSourceRange() << RHS->getSourceRange()); 4008} 4009 4010/// Analyzes an attempt to assign the given value to a bitfield. 4011/// 4012/// Returns true if there was something fishy about the attempt. 4013static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 4014 SourceLocation InitLoc) { 4015 assert(Bitfield->isBitField()); 4016 if (Bitfield->isInvalidDecl()) 4017 return false; 4018 4019 // White-list bool bitfields. 4020 if (Bitfield->getType()->isBooleanType()) 4021 return false; 4022 4023 // Ignore value- or type-dependent expressions. 4024 if (Bitfield->getBitWidth()->isValueDependent() || 4025 Bitfield->getBitWidth()->isTypeDependent() || 4026 Init->isValueDependent() || 4027 Init->isTypeDependent()) 4028 return false; 4029 4030 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 4031 4032 llvm::APSInt Value; 4033 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 4034 return false; 4035 4036 unsigned OriginalWidth = Value.getBitWidth(); 4037 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 4038 4039 if (OriginalWidth <= FieldWidth) 4040 return false; 4041 4042 // Compute the value which the bitfield will contain. 4043 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 4044 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType()); 4045 4046 // Check whether the stored value is equal to the original value. 4047 TruncatedValue = TruncatedValue.extend(OriginalWidth); 4048 if (Value == TruncatedValue) 4049 return false; 4050 4051 // Special-case bitfields of width 1: booleans are naturally 0/1, and 4052 // therefore don't strictly fit into a signed bitfield of width 1. 4053 if (FieldWidth == 1 && Value == 1) 4054 return false; 4055 4056 std::string PrettyValue = Value.toString(10); 4057 std::string PrettyTrunc = TruncatedValue.toString(10); 4058 4059 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 4060 << PrettyValue << PrettyTrunc << OriginalInit->getType() 4061 << Init->getSourceRange(); 4062 4063 return true; 4064} 4065 4066/// Analyze the given simple or compound assignment for warning-worthy 4067/// operations. 4068static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 4069 // Just recurse on the LHS. 4070 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 4071 4072 // We want to recurse on the RHS as normal unless we're assigning to 4073 // a bitfield. 4074 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) { 4075 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 4076 E->getOperatorLoc())) { 4077 // Recurse, ignoring any implicit conversions on the RHS. 4078 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 4079 E->getOperatorLoc()); 4080 } 4081 } 4082 4083 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 4084} 4085 4086/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 4087static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 4088 SourceLocation CContext, unsigned diag, 4089 bool pruneControlFlow = false) { 4090 if (pruneControlFlow) { 4091 S.DiagRuntimeBehavior(E->getExprLoc(), E, 4092 S.PDiag(diag) 4093 << SourceType << T << E->getSourceRange() 4094 << SourceRange(CContext)); 4095 return; 4096 } 4097 S.Diag(E->getExprLoc(), diag) 4098 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 4099} 4100 4101/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 4102static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 4103 SourceLocation CContext, unsigned diag, 4104 bool pruneControlFlow = false) { 4105 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 4106} 4107 4108/// Diagnose an implicit cast from a literal expression. Does not warn when the 4109/// cast wouldn't lose information. 4110void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T, 4111 SourceLocation CContext) { 4112 // Try to convert the literal exactly to an integer. If we can, don't warn. 4113 bool isExact = false; 4114 const llvm::APFloat &Value = FL->getValue(); 4115 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 4116 T->hasUnsignedIntegerRepresentation()); 4117 if (Value.convertToInteger(IntegerValue, 4118 llvm::APFloat::rmTowardZero, &isExact) 4119 == llvm::APFloat::opOK && isExact) 4120 return; 4121 4122 SmallString<16> PrettySourceValue; 4123 Value.toString(PrettySourceValue); 4124 SmallString<16> PrettyTargetValue; 4125 if (T->isSpecificBuiltinType(BuiltinType::Bool)) 4126 PrettyTargetValue = IntegerValue == 0 ? "false" : "true"; 4127 else 4128 IntegerValue.toString(PrettyTargetValue); 4129 4130 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer) 4131 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue 4132 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext); 4133} 4134 4135std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 4136 if (!Range.Width) return "0"; 4137 4138 llvm::APSInt ValueInRange = Value; 4139 ValueInRange.setIsSigned(!Range.NonNegative); 4140 ValueInRange = ValueInRange.trunc(Range.Width); 4141 return ValueInRange.toString(10); 4142} 4143 4144void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 4145 SourceLocation CC, bool *ICContext = 0) { 4146 if (E->isTypeDependent() || E->isValueDependent()) return; 4147 4148 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 4149 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 4150 if (Source == Target) return; 4151 if (Target->isDependentType()) return; 4152 4153 // If the conversion context location is invalid don't complain. We also 4154 // don't want to emit a warning if the issue occurs from the expansion of 4155 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 4156 // delay this check as long as possible. Once we detect we are in that 4157 // scenario, we just return. 4158 if (CC.isInvalid()) 4159 return; 4160 4161 // Diagnose implicit casts to bool. 4162 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 4163 if (isa<StringLiteral>(E)) 4164 // Warn on string literal to bool. Checks for string literals in logical 4165 // expressions, for instances, assert(0 && "error here"), is prevented 4166 // by a check in AnalyzeImplicitConversions(). 4167 return DiagnoseImpCast(S, E, T, CC, 4168 diag::warn_impcast_string_literal_to_bool); 4169 if (Source->isFunctionType()) { 4170 // Warn on function to bool. Checks free functions and static member 4171 // functions. Weakly imported functions are excluded from the check, 4172 // since it's common to test their value to check whether the linker 4173 // found a definition for them. 4174 ValueDecl *D = 0; 4175 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) { 4176 D = R->getDecl(); 4177 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 4178 D = M->getMemberDecl(); 4179 } 4180 4181 if (D && !D->isWeak()) { 4182 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) { 4183 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool) 4184 << F << E->getSourceRange() << SourceRange(CC); 4185 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence) 4186 << FixItHint::CreateInsertion(E->getExprLoc(), "&"); 4187 QualType ReturnType; 4188 UnresolvedSet<4> NonTemplateOverloads; 4189 S.isExprCallable(*E, ReturnType, NonTemplateOverloads); 4190 if (!ReturnType.isNull() 4191 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 4192 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call) 4193 << FixItHint::CreateInsertion( 4194 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()"); 4195 return; 4196 } 4197 } 4198 } 4199 } 4200 4201 // Strip vector types. 4202 if (isa<VectorType>(Source)) { 4203 if (!isa<VectorType>(Target)) { 4204 if (S.SourceMgr.isInSystemMacro(CC)) 4205 return; 4206 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 4207 } 4208 4209 // If the vector cast is cast between two vectors of the same size, it is 4210 // a bitcast, not a conversion. 4211 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 4212 return; 4213 4214 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 4215 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 4216 } 4217 4218 // Strip complex types. 4219 if (isa<ComplexType>(Source)) { 4220 if (!isa<ComplexType>(Target)) { 4221 if (S.SourceMgr.isInSystemMacro(CC)) 4222 return; 4223 4224 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 4225 } 4226 4227 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 4228 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 4229 } 4230 4231 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 4232 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 4233 4234 // If the source is floating point... 4235 if (SourceBT && SourceBT->isFloatingPoint()) { 4236 // ...and the target is floating point... 4237 if (TargetBT && TargetBT->isFloatingPoint()) { 4238 // ...then warn if we're dropping FP rank. 4239 4240 // Builtin FP kinds are ordered by increasing FP rank. 4241 if (SourceBT->getKind() > TargetBT->getKind()) { 4242 // Don't warn about float constants that are precisely 4243 // representable in the target type. 4244 Expr::EvalResult result; 4245 if (E->EvaluateAsRValue(result, S.Context)) { 4246 // Value might be a float, a float vector, or a float complex. 4247 if (IsSameFloatAfterCast(result.Val, 4248 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 4249 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 4250 return; 4251 } 4252 4253 if (S.SourceMgr.isInSystemMacro(CC)) 4254 return; 4255 4256 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 4257 } 4258 return; 4259 } 4260 4261 // If the target is integral, always warn. 4262 if (TargetBT && TargetBT->isInteger()) { 4263 if (S.SourceMgr.isInSystemMacro(CC)) 4264 return; 4265 4266 Expr *InnerE = E->IgnoreParenImpCasts(); 4267 // We also want to warn on, e.g., "int i = -1.234" 4268 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 4269 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 4270 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 4271 4272 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) { 4273 DiagnoseFloatingLiteralImpCast(S, FL, T, CC); 4274 } else { 4275 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer); 4276 } 4277 } 4278 4279 return; 4280 } 4281 4282 if (!Source->isIntegerType() || !Target->isIntegerType()) 4283 return; 4284 4285 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) 4286 == Expr::NPCK_GNUNull) && Target->isIntegerType()) { 4287 SourceLocation Loc = E->getSourceRange().getBegin(); 4288 if (Loc.isMacroID()) 4289 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 4290 if (!Loc.isMacroID() || CC.isMacroID()) 4291 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 4292 << T << clang::SourceRange(CC) 4293 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T)); 4294 return; 4295 } 4296 4297 // TODO: remove this early return once the false positives for constant->bool 4298 // in templates, macros, etc, are reduced or removed. 4299 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 4300 return; 4301 4302 IntRange SourceRange = GetExprRange(S.Context, E); 4303 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 4304 4305 if (SourceRange.Width > TargetRange.Width) { 4306 // If the source is a constant, use a default-on diagnostic. 4307 // TODO: this should happen for bitfield stores, too. 4308 llvm::APSInt Value(32); 4309 if (E->isIntegerConstantExpr(Value, S.Context)) { 4310 if (S.SourceMgr.isInSystemMacro(CC)) 4311 return; 4312 4313 std::string PrettySourceValue = Value.toString(10); 4314 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 4315 4316 S.DiagRuntimeBehavior(E->getExprLoc(), E, 4317 S.PDiag(diag::warn_impcast_integer_precision_constant) 4318 << PrettySourceValue << PrettyTargetValue 4319 << E->getType() << T << E->getSourceRange() 4320 << clang::SourceRange(CC)); 4321 return; 4322 } 4323 4324 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 4325 if (S.SourceMgr.isInSystemMacro(CC)) 4326 return; 4327 4328 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 4329 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 4330 /* pruneControlFlow */ true); 4331 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 4332 } 4333 4334 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 4335 (!TargetRange.NonNegative && SourceRange.NonNegative && 4336 SourceRange.Width == TargetRange.Width)) { 4337 4338 if (S.SourceMgr.isInSystemMacro(CC)) 4339 return; 4340 4341 unsigned DiagID = diag::warn_impcast_integer_sign; 4342 4343 // Traditionally, gcc has warned about this under -Wsign-compare. 4344 // We also want to warn about it in -Wconversion. 4345 // So if -Wconversion is off, use a completely identical diagnostic 4346 // in the sign-compare group. 4347 // The conditional-checking code will 4348 if (ICContext) { 4349 DiagID = diag::warn_impcast_integer_sign_conditional; 4350 *ICContext = true; 4351 } 4352 4353 return DiagnoseImpCast(S, E, T, CC, DiagID); 4354 } 4355 4356 // Diagnose conversions between different enumeration types. 4357 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 4358 // type, to give us better diagnostics. 4359 QualType SourceType = E->getType(); 4360 if (!S.getLangOpts().CPlusPlus) { 4361 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 4362 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 4363 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 4364 SourceType = S.Context.getTypeDeclType(Enum); 4365 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 4366 } 4367 } 4368 4369 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 4370 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 4371 if ((SourceEnum->getDecl()->getIdentifier() || 4372 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) && 4373 (TargetEnum->getDecl()->getIdentifier() || 4374 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) && 4375 SourceEnum != TargetEnum) { 4376 if (S.SourceMgr.isInSystemMacro(CC)) 4377 return; 4378 4379 return DiagnoseImpCast(S, E, SourceType, T, CC, 4380 diag::warn_impcast_different_enum_types); 4381 } 4382 4383 return; 4384} 4385 4386void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 4387 SourceLocation CC, QualType T); 4388 4389void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 4390 SourceLocation CC, bool &ICContext) { 4391 E = E->IgnoreParenImpCasts(); 4392 4393 if (isa<ConditionalOperator>(E)) 4394 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 4395 4396 AnalyzeImplicitConversions(S, E, CC); 4397 if (E->getType() != T) 4398 return CheckImplicitConversion(S, E, T, CC, &ICContext); 4399 return; 4400} 4401 4402void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 4403 SourceLocation CC, QualType T) { 4404 AnalyzeImplicitConversions(S, E->getCond(), CC); 4405 4406 bool Suspicious = false; 4407 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 4408 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 4409 4410 // If -Wconversion would have warned about either of the candidates 4411 // for a signedness conversion to the context type... 4412 if (!Suspicious) return; 4413 4414 // ...but it's currently ignored... 4415 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional, 4416 CC)) 4417 return; 4418 4419 // ...then check whether it would have warned about either of the 4420 // candidates for a signedness conversion to the condition type. 4421 if (E->getType() == T) return; 4422 4423 Suspicious = false; 4424 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 4425 E->getType(), CC, &Suspicious); 4426 if (!Suspicious) 4427 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 4428 E->getType(), CC, &Suspicious); 4429} 4430 4431/// AnalyzeImplicitConversions - Find and report any interesting 4432/// implicit conversions in the given expression. There are a couple 4433/// of competing diagnostics here, -Wconversion and -Wsign-compare. 4434void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 4435 QualType T = OrigE->getType(); 4436 Expr *E = OrigE->IgnoreParenImpCasts(); 4437 4438 if (E->isTypeDependent() || E->isValueDependent()) 4439 return; 4440 4441 // For conditional operators, we analyze the arguments as if they 4442 // were being fed directly into the output. 4443 if (isa<ConditionalOperator>(E)) { 4444 ConditionalOperator *CO = cast<ConditionalOperator>(E); 4445 CheckConditionalOperator(S, CO, CC, T); 4446 return; 4447 } 4448 4449 // Go ahead and check any implicit conversions we might have skipped. 4450 // The non-canonical typecheck is just an optimization; 4451 // CheckImplicitConversion will filter out dead implicit conversions. 4452 if (E->getType() != T) 4453 CheckImplicitConversion(S, E, T, CC); 4454 4455 // Now continue drilling into this expression. 4456 4457 // Skip past explicit casts. 4458 if (isa<ExplicitCastExpr>(E)) { 4459 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 4460 return AnalyzeImplicitConversions(S, E, CC); 4461 } 4462 4463 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 4464 // Do a somewhat different check with comparison operators. 4465 if (BO->isComparisonOp()) 4466 return AnalyzeComparison(S, BO); 4467 4468 // And with simple assignments. 4469 if (BO->getOpcode() == BO_Assign) 4470 return AnalyzeAssignment(S, BO); 4471 } 4472 4473 // These break the otherwise-useful invariant below. Fortunately, 4474 // we don't really need to recurse into them, because any internal 4475 // expressions should have been analyzed already when they were 4476 // built into statements. 4477 if (isa<StmtExpr>(E)) return; 4478 4479 // Don't descend into unevaluated contexts. 4480 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 4481 4482 // Now just recurse over the expression's children. 4483 CC = E->getExprLoc(); 4484 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 4485 bool IsLogicalOperator = BO && BO->isLogicalOp(); 4486 for (Stmt::child_range I = E->children(); I; ++I) { 4487 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I); 4488 if (!ChildExpr) 4489 continue; 4490 4491 if (IsLogicalOperator && 4492 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 4493 // Ignore checking string literals that are in logical operators. 4494 continue; 4495 AnalyzeImplicitConversions(S, ChildExpr, CC); 4496 } 4497} 4498 4499} // end anonymous namespace 4500 4501/// Diagnoses "dangerous" implicit conversions within the given 4502/// expression (which is a full expression). Implements -Wconversion 4503/// and -Wsign-compare. 4504/// 4505/// \param CC the "context" location of the implicit conversion, i.e. 4506/// the most location of the syntactic entity requiring the implicit 4507/// conversion 4508void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 4509 // Don't diagnose in unevaluated contexts. 4510 if (ExprEvalContexts.back().Context == Sema::Unevaluated) 4511 return; 4512 4513 // Don't diagnose for value- or type-dependent expressions. 4514 if (E->isTypeDependent() || E->isValueDependent()) 4515 return; 4516 4517 // Check for array bounds violations in cases where the check isn't triggered 4518 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 4519 // ArraySubscriptExpr is on the RHS of a variable initialization. 4520 CheckArrayAccess(E); 4521 4522 // This is not the right CC for (e.g.) a variable initialization. 4523 AnalyzeImplicitConversions(*this, E, CC); 4524} 4525 4526void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 4527 FieldDecl *BitField, 4528 Expr *Init) { 4529 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 4530} 4531 4532/// CheckParmsForFunctionDef - Check that the parameters of the given 4533/// function are appropriate for the definition of a function. This 4534/// takes care of any checks that cannot be performed on the 4535/// declaration itself, e.g., that the types of each of the function 4536/// parameters are complete. 4537bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd, 4538 bool CheckParameterNames) { 4539 bool HasInvalidParm = false; 4540 for (; P != PEnd; ++P) { 4541 ParmVarDecl *Param = *P; 4542 4543 // C99 6.7.5.3p4: the parameters in a parameter type list in a 4544 // function declarator that is part of a function definition of 4545 // that function shall not have incomplete type. 4546 // 4547 // This is also C++ [dcl.fct]p6. 4548 if (!Param->isInvalidDecl() && 4549 RequireCompleteType(Param->getLocation(), Param->getType(), 4550 diag::err_typecheck_decl_incomplete_type)) { 4551 Param->setInvalidDecl(); 4552 HasInvalidParm = true; 4553 } 4554 4555 // C99 6.9.1p5: If the declarator includes a parameter type list, the 4556 // declaration of each parameter shall include an identifier. 4557 if (CheckParameterNames && 4558 Param->getIdentifier() == 0 && 4559 !Param->isImplicit() && 4560 !getLangOpts().CPlusPlus) 4561 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 4562 4563 // C99 6.7.5.3p12: 4564 // If the function declarator is not part of a definition of that 4565 // function, parameters may have incomplete type and may use the [*] 4566 // notation in their sequences of declarator specifiers to specify 4567 // variable length array types. 4568 QualType PType = Param->getOriginalType(); 4569 if (const ArrayType *AT = Context.getAsArrayType(PType)) { 4570 if (AT->getSizeModifier() == ArrayType::Star) { 4571 // FIXME: This diagnosic should point the the '[*]' if source-location 4572 // information is added for it. 4573 Diag(Param->getLocation(), diag::err_array_star_in_function_definition); 4574 } 4575 } 4576 } 4577 4578 return HasInvalidParm; 4579} 4580 4581/// CheckCastAlign - Implements -Wcast-align, which warns when a 4582/// pointer cast increases the alignment requirements. 4583void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 4584 // This is actually a lot of work to potentially be doing on every 4585 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 4586 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align, 4587 TRange.getBegin()) 4588 == DiagnosticsEngine::Ignored) 4589 return; 4590 4591 // Ignore dependent types. 4592 if (T->isDependentType() || Op->getType()->isDependentType()) 4593 return; 4594 4595 // Require that the destination be a pointer type. 4596 const PointerType *DestPtr = T->getAs<PointerType>(); 4597 if (!DestPtr) return; 4598 4599 // If the destination has alignment 1, we're done. 4600 QualType DestPointee = DestPtr->getPointeeType(); 4601 if (DestPointee->isIncompleteType()) return; 4602 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 4603 if (DestAlign.isOne()) return; 4604 4605 // Require that the source be a pointer type. 4606 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 4607 if (!SrcPtr) return; 4608 QualType SrcPointee = SrcPtr->getPointeeType(); 4609 4610 // Whitelist casts from cv void*. We already implicitly 4611 // whitelisted casts to cv void*, since they have alignment 1. 4612 // Also whitelist casts involving incomplete types, which implicitly 4613 // includes 'void'. 4614 if (SrcPointee->isIncompleteType()) return; 4615 4616 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 4617 if (SrcAlign >= DestAlign) return; 4618 4619 Diag(TRange.getBegin(), diag::warn_cast_align) 4620 << Op->getType() << T 4621 << static_cast<unsigned>(SrcAlign.getQuantity()) 4622 << static_cast<unsigned>(DestAlign.getQuantity()) 4623 << TRange << Op->getSourceRange(); 4624} 4625 4626static const Type* getElementType(const Expr *BaseExpr) { 4627 const Type* EltType = BaseExpr->getType().getTypePtr(); 4628 if (EltType->isAnyPointerType()) 4629 return EltType->getPointeeType().getTypePtr(); 4630 else if (EltType->isArrayType()) 4631 return EltType->getBaseElementTypeUnsafe(); 4632 return EltType; 4633} 4634 4635/// \brief Check whether this array fits the idiom of a size-one tail padded 4636/// array member of a struct. 4637/// 4638/// We avoid emitting out-of-bounds access warnings for such arrays as they are 4639/// commonly used to emulate flexible arrays in C89 code. 4640static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size, 4641 const NamedDecl *ND) { 4642 if (Size != 1 || !ND) return false; 4643 4644 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 4645 if (!FD) return false; 4646 4647 // Don't consider sizes resulting from macro expansions or template argument 4648 // substitution to form C89 tail-padded arrays. 4649 4650 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 4651 while (TInfo) { 4652 TypeLoc TL = TInfo->getTypeLoc(); 4653 // Look through typedefs. 4654 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL); 4655 if (TTL) { 4656 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl(); 4657 TInfo = TDL->getTypeSourceInfo(); 4658 continue; 4659 } 4660 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL); 4661 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 4662 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 4663 return false; 4664 break; 4665 } 4666 4667 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 4668 if (!RD) return false; 4669 if (RD->isUnion()) return false; 4670 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 4671 if (!CRD->isStandardLayout()) return false; 4672 } 4673 4674 // See if this is the last field decl in the record. 4675 const Decl *D = FD; 4676 while ((D = D->getNextDeclInContext())) 4677 if (isa<FieldDecl>(D)) 4678 return false; 4679 return true; 4680} 4681 4682void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 4683 const ArraySubscriptExpr *ASE, 4684 bool AllowOnePastEnd, bool IndexNegated) { 4685 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 4686 if (IndexExpr->isValueDependent()) 4687 return; 4688 4689 const Type *EffectiveType = getElementType(BaseExpr); 4690 BaseExpr = BaseExpr->IgnoreParenCasts(); 4691 const ConstantArrayType *ArrayTy = 4692 Context.getAsConstantArrayType(BaseExpr->getType()); 4693 if (!ArrayTy) 4694 return; 4695 4696 llvm::APSInt index; 4697 if (!IndexExpr->EvaluateAsInt(index, Context)) 4698 return; 4699 if (IndexNegated) 4700 index = -index; 4701 4702 const NamedDecl *ND = NULL; 4703 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 4704 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 4705 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 4706 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 4707 4708 if (index.isUnsigned() || !index.isNegative()) { 4709 llvm::APInt size = ArrayTy->getSize(); 4710 if (!size.isStrictlyPositive()) 4711 return; 4712 4713 const Type* BaseType = getElementType(BaseExpr); 4714 if (BaseType != EffectiveType) { 4715 // Make sure we're comparing apples to apples when comparing index to size 4716 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 4717 uint64_t array_typesize = Context.getTypeSize(BaseType); 4718 // Handle ptrarith_typesize being zero, such as when casting to void* 4719 if (!ptrarith_typesize) ptrarith_typesize = 1; 4720 if (ptrarith_typesize != array_typesize) { 4721 // There's a cast to a different size type involved 4722 uint64_t ratio = array_typesize / ptrarith_typesize; 4723 // TODO: Be smarter about handling cases where array_typesize is not a 4724 // multiple of ptrarith_typesize 4725 if (ptrarith_typesize * ratio == array_typesize) 4726 size *= llvm::APInt(size.getBitWidth(), ratio); 4727 } 4728 } 4729 4730 if (size.getBitWidth() > index.getBitWidth()) 4731 index = index.zext(size.getBitWidth()); 4732 else if (size.getBitWidth() < index.getBitWidth()) 4733 size = size.zext(index.getBitWidth()); 4734 4735 // For array subscripting the index must be less than size, but for pointer 4736 // arithmetic also allow the index (offset) to be equal to size since 4737 // computing the next address after the end of the array is legal and 4738 // commonly done e.g. in C++ iterators and range-based for loops. 4739 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 4740 return; 4741 4742 // Also don't warn for arrays of size 1 which are members of some 4743 // structure. These are often used to approximate flexible arrays in C89 4744 // code. 4745 if (IsTailPaddedMemberArray(*this, size, ND)) 4746 return; 4747 4748 // Suppress the warning if the subscript expression (as identified by the 4749 // ']' location) and the index expression are both from macro expansions 4750 // within a system header. 4751 if (ASE) { 4752 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 4753 ASE->getRBracketLoc()); 4754 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 4755 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 4756 IndexExpr->getLocStart()); 4757 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc)) 4758 return; 4759 } 4760 } 4761 4762 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 4763 if (ASE) 4764 DiagID = diag::warn_array_index_exceeds_bounds; 4765 4766 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 4767 PDiag(DiagID) << index.toString(10, true) 4768 << size.toString(10, true) 4769 << (unsigned)size.getLimitedValue(~0U) 4770 << IndexExpr->getSourceRange()); 4771 } else { 4772 unsigned DiagID = diag::warn_array_index_precedes_bounds; 4773 if (!ASE) { 4774 DiagID = diag::warn_ptr_arith_precedes_bounds; 4775 if (index.isNegative()) index = -index; 4776 } 4777 4778 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 4779 PDiag(DiagID) << index.toString(10, true) 4780 << IndexExpr->getSourceRange()); 4781 } 4782 4783 if (!ND) { 4784 // Try harder to find a NamedDecl to point at in the note. 4785 while (const ArraySubscriptExpr *ASE = 4786 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 4787 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 4788 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 4789 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 4790 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 4791 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 4792 } 4793 4794 if (ND) 4795 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 4796 PDiag(diag::note_array_index_out_of_bounds) 4797 << ND->getDeclName()); 4798} 4799 4800void Sema::CheckArrayAccess(const Expr *expr) { 4801 int AllowOnePastEnd = 0; 4802 while (expr) { 4803 expr = expr->IgnoreParenImpCasts(); 4804 switch (expr->getStmtClass()) { 4805 case Stmt::ArraySubscriptExprClass: { 4806 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 4807 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 4808 AllowOnePastEnd > 0); 4809 return; 4810 } 4811 case Stmt::UnaryOperatorClass: { 4812 // Only unwrap the * and & unary operators 4813 const UnaryOperator *UO = cast<UnaryOperator>(expr); 4814 expr = UO->getSubExpr(); 4815 switch (UO->getOpcode()) { 4816 case UO_AddrOf: 4817 AllowOnePastEnd++; 4818 break; 4819 case UO_Deref: 4820 AllowOnePastEnd--; 4821 break; 4822 default: 4823 return; 4824 } 4825 break; 4826 } 4827 case Stmt::ConditionalOperatorClass: { 4828 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 4829 if (const Expr *lhs = cond->getLHS()) 4830 CheckArrayAccess(lhs); 4831 if (const Expr *rhs = cond->getRHS()) 4832 CheckArrayAccess(rhs); 4833 return; 4834 } 4835 default: 4836 return; 4837 } 4838 } 4839} 4840 4841//===--- CHECK: Objective-C retain cycles ----------------------------------// 4842 4843namespace { 4844 struct RetainCycleOwner { 4845 RetainCycleOwner() : Variable(0), Indirect(false) {} 4846 VarDecl *Variable; 4847 SourceRange Range; 4848 SourceLocation Loc; 4849 bool Indirect; 4850 4851 void setLocsFrom(Expr *e) { 4852 Loc = e->getExprLoc(); 4853 Range = e->getSourceRange(); 4854 } 4855 }; 4856} 4857 4858/// Consider whether capturing the given variable can possibly lead to 4859/// a retain cycle. 4860static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 4861 // In ARC, it's captured strongly iff the variable has __strong 4862 // lifetime. In MRR, it's captured strongly if the variable is 4863 // __block and has an appropriate type. 4864 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 4865 return false; 4866 4867 owner.Variable = var; 4868 owner.setLocsFrom(ref); 4869 return true; 4870} 4871 4872static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 4873 while (true) { 4874 e = e->IgnoreParens(); 4875 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 4876 switch (cast->getCastKind()) { 4877 case CK_BitCast: 4878 case CK_LValueBitCast: 4879 case CK_LValueToRValue: 4880 case CK_ARCReclaimReturnedObject: 4881 e = cast->getSubExpr(); 4882 continue; 4883 4884 default: 4885 return false; 4886 } 4887 } 4888 4889 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 4890 ObjCIvarDecl *ivar = ref->getDecl(); 4891 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 4892 return false; 4893 4894 // Try to find a retain cycle in the base. 4895 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 4896 return false; 4897 4898 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 4899 owner.Indirect = true; 4900 return true; 4901 } 4902 4903 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 4904 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 4905 if (!var) return false; 4906 return considerVariable(var, ref, owner); 4907 } 4908 4909 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 4910 if (member->isArrow()) return false; 4911 4912 // Don't count this as an indirect ownership. 4913 e = member->getBase(); 4914 continue; 4915 } 4916 4917 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 4918 // Only pay attention to pseudo-objects on property references. 4919 ObjCPropertyRefExpr *pre 4920 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 4921 ->IgnoreParens()); 4922 if (!pre) return false; 4923 if (pre->isImplicitProperty()) return false; 4924 ObjCPropertyDecl *property = pre->getExplicitProperty(); 4925 if (!property->isRetaining() && 4926 !(property->getPropertyIvarDecl() && 4927 property->getPropertyIvarDecl()->getType() 4928 .getObjCLifetime() == Qualifiers::OCL_Strong)) 4929 return false; 4930 4931 owner.Indirect = true; 4932 if (pre->isSuperReceiver()) { 4933 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 4934 if (!owner.Variable) 4935 return false; 4936 owner.Loc = pre->getLocation(); 4937 owner.Range = pre->getSourceRange(); 4938 return true; 4939 } 4940 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 4941 ->getSourceExpr()); 4942 continue; 4943 } 4944 4945 // Array ivars? 4946 4947 return false; 4948 } 4949} 4950 4951namespace { 4952 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 4953 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 4954 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 4955 Variable(variable), Capturer(0) {} 4956 4957 VarDecl *Variable; 4958 Expr *Capturer; 4959 4960 void VisitDeclRefExpr(DeclRefExpr *ref) { 4961 if (ref->getDecl() == Variable && !Capturer) 4962 Capturer = ref; 4963 } 4964 4965 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 4966 if (Capturer) return; 4967 Visit(ref->getBase()); 4968 if (Capturer && ref->isFreeIvar()) 4969 Capturer = ref; 4970 } 4971 4972 void VisitBlockExpr(BlockExpr *block) { 4973 // Look inside nested blocks 4974 if (block->getBlockDecl()->capturesVariable(Variable)) 4975 Visit(block->getBlockDecl()->getBody()); 4976 } 4977 }; 4978} 4979 4980/// Check whether the given argument is a block which captures a 4981/// variable. 4982static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 4983 assert(owner.Variable && owner.Loc.isValid()); 4984 4985 e = e->IgnoreParenCasts(); 4986 BlockExpr *block = dyn_cast<BlockExpr>(e); 4987 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 4988 return 0; 4989 4990 FindCaptureVisitor visitor(S.Context, owner.Variable); 4991 visitor.Visit(block->getBlockDecl()->getBody()); 4992 return visitor.Capturer; 4993} 4994 4995static void diagnoseRetainCycle(Sema &S, Expr *capturer, 4996 RetainCycleOwner &owner) { 4997 assert(capturer); 4998 assert(owner.Variable && owner.Loc.isValid()); 4999 5000 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 5001 << owner.Variable << capturer->getSourceRange(); 5002 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 5003 << owner.Indirect << owner.Range; 5004} 5005 5006/// Check for a keyword selector that starts with the word 'add' or 5007/// 'set'. 5008static bool isSetterLikeSelector(Selector sel) { 5009 if (sel.isUnarySelector()) return false; 5010 5011 StringRef str = sel.getNameForSlot(0); 5012 while (!str.empty() && str.front() == '_') str = str.substr(1); 5013 if (str.startswith("set")) 5014 str = str.substr(3); 5015 else if (str.startswith("add")) { 5016 // Specially whitelist 'addOperationWithBlock:'. 5017 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 5018 return false; 5019 str = str.substr(3); 5020 } 5021 else 5022 return false; 5023 5024 if (str.empty()) return true; 5025 return !islower(str.front()); 5026} 5027 5028/// Check a message send to see if it's likely to cause a retain cycle. 5029void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 5030 // Only check instance methods whose selector looks like a setter. 5031 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 5032 return; 5033 5034 // Try to find a variable that the receiver is strongly owned by. 5035 RetainCycleOwner owner; 5036 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 5037 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 5038 return; 5039 } else { 5040 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 5041 owner.Variable = getCurMethodDecl()->getSelfDecl(); 5042 owner.Loc = msg->getSuperLoc(); 5043 owner.Range = msg->getSuperLoc(); 5044 } 5045 5046 // Check whether the receiver is captured by any of the arguments. 5047 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 5048 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 5049 return diagnoseRetainCycle(*this, capturer, owner); 5050} 5051 5052/// Check a property assign to see if it's likely to cause a retain cycle. 5053void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 5054 RetainCycleOwner owner; 5055 if (!findRetainCycleOwner(*this, receiver, owner)) 5056 return; 5057 5058 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 5059 diagnoseRetainCycle(*this, capturer, owner); 5060} 5061 5062bool Sema::checkUnsafeAssigns(SourceLocation Loc, 5063 QualType LHS, Expr *RHS) { 5064 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 5065 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 5066 return false; 5067 // strip off any implicit cast added to get to the one arc-specific 5068 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 5069 if (cast->getCastKind() == CK_ARCConsumeObject) { 5070 Diag(Loc, diag::warn_arc_retained_assign) 5071 << (LT == Qualifiers::OCL_ExplicitNone) 5072 << RHS->getSourceRange(); 5073 return true; 5074 } 5075 RHS = cast->getSubExpr(); 5076 } 5077 return false; 5078} 5079 5080void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 5081 Expr *LHS, Expr *RHS) { 5082 QualType LHSType; 5083 // PropertyRef on LHS type need be directly obtained from 5084 // its declaration as it has a PsuedoType. 5085 ObjCPropertyRefExpr *PRE 5086 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 5087 if (PRE && !PRE->isImplicitProperty()) { 5088 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 5089 if (PD) 5090 LHSType = PD->getType(); 5091 } 5092 5093 if (LHSType.isNull()) 5094 LHSType = LHS->getType(); 5095 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 5096 return; 5097 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 5098 // FIXME. Check for other life times. 5099 if (LT != Qualifiers::OCL_None) 5100 return; 5101 5102 if (PRE) { 5103 if (PRE->isImplicitProperty()) 5104 return; 5105 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 5106 if (!PD) 5107 return; 5108 5109 unsigned Attributes = PD->getPropertyAttributes(); 5110 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 5111 // when 'assign' attribute was not explicitly specified 5112 // by user, ignore it and rely on property type itself 5113 // for lifetime info. 5114 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 5115 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 5116 LHSType->isObjCRetainableType()) 5117 return; 5118 5119 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 5120 if (cast->getCastKind() == CK_ARCConsumeObject) { 5121 Diag(Loc, diag::warn_arc_retained_property_assign) 5122 << RHS->getSourceRange(); 5123 return; 5124 } 5125 RHS = cast->getSubExpr(); 5126 } 5127 } 5128 } 5129} 5130 5131//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 5132 5133namespace { 5134bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 5135 SourceLocation StmtLoc, 5136 const NullStmt *Body) { 5137 // Do not warn if the body is a macro that expands to nothing, e.g: 5138 // 5139 // #define CALL(x) 5140 // if (condition) 5141 // CALL(0); 5142 // 5143 if (Body->hasLeadingEmptyMacro()) 5144 return false; 5145 5146 // Get line numbers of statement and body. 5147 bool StmtLineInvalid; 5148 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc, 5149 &StmtLineInvalid); 5150 if (StmtLineInvalid) 5151 return false; 5152 5153 bool BodyLineInvalid; 5154 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 5155 &BodyLineInvalid); 5156 if (BodyLineInvalid) 5157 return false; 5158 5159 // Warn if null statement and body are on the same line. 5160 if (StmtLine != BodyLine) 5161 return false; 5162 5163 return true; 5164} 5165} // Unnamed namespace 5166 5167void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 5168 const Stmt *Body, 5169 unsigned DiagID) { 5170 // Since this is a syntactic check, don't emit diagnostic for template 5171 // instantiations, this just adds noise. 5172 if (CurrentInstantiationScope) 5173 return; 5174 5175 // The body should be a null statement. 5176 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 5177 if (!NBody) 5178 return; 5179 5180 // Do the usual checks. 5181 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 5182 return; 5183 5184 Diag(NBody->getSemiLoc(), DiagID); 5185 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 5186} 5187 5188void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 5189 const Stmt *PossibleBody) { 5190 assert(!CurrentInstantiationScope); // Ensured by caller 5191 5192 SourceLocation StmtLoc; 5193 const Stmt *Body; 5194 unsigned DiagID; 5195 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 5196 StmtLoc = FS->getRParenLoc(); 5197 Body = FS->getBody(); 5198 DiagID = diag::warn_empty_for_body; 5199 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 5200 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 5201 Body = WS->getBody(); 5202 DiagID = diag::warn_empty_while_body; 5203 } else 5204 return; // Neither `for' nor `while'. 5205 5206 // The body should be a null statement. 5207 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 5208 if (!NBody) 5209 return; 5210 5211 // Skip expensive checks if diagnostic is disabled. 5212 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) == 5213 DiagnosticsEngine::Ignored) 5214 return; 5215 5216 // Do the usual checks. 5217 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 5218 return; 5219 5220 // `for(...);' and `while(...);' are popular idioms, so in order to keep 5221 // noise level low, emit diagnostics only if for/while is followed by a 5222 // CompoundStmt, e.g.: 5223 // for (int i = 0; i < n; i++); 5224 // { 5225 // a(i); 5226 // } 5227 // or if for/while is followed by a statement with more indentation 5228 // than for/while itself: 5229 // for (int i = 0; i < n; i++); 5230 // a(i); 5231 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 5232 if (!ProbableTypo) { 5233 bool BodyColInvalid; 5234 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 5235 PossibleBody->getLocStart(), 5236 &BodyColInvalid); 5237 if (BodyColInvalid) 5238 return; 5239 5240 bool StmtColInvalid; 5241 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 5242 S->getLocStart(), 5243 &StmtColInvalid); 5244 if (StmtColInvalid) 5245 return; 5246 5247 if (BodyCol > StmtCol) 5248 ProbableTypo = true; 5249 } 5250 5251 if (ProbableTypo) { 5252 Diag(NBody->getSemiLoc(), DiagID); 5253 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 5254 } 5255} 5256