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/SemaInternal.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/CharUnits.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/EvaluatedExprVisitor.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/ExprObjC.h" 24 #include "clang/AST/StmtCXX.h" 25 #include "clang/AST/StmtObjC.h" 26 #include "clang/Analysis/Analyses/FormatString.h" 27 #include "clang/Basic/CharInfo.h" 28 #include "clang/Basic/TargetBuiltins.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/Preprocessor.h" 31 #include "clang/Sema/Initialization.h" 32 #include "clang/Sema/Lookup.h" 33 #include "clang/Sema/ScopeInfo.h" 34 #include "clang/Sema/Sema.h" 35 #include "llvm/ADT/STLExtras.h" 36 #include "llvm/ADT/SmallBitVector.h" 37 #include "llvm/ADT/SmallString.h" 38 #include "llvm/Support/ConvertUTF.h" 39 #include "llvm/Support/raw_ostream.h" 40 #include <limits> 41 using namespace clang; 42 using namespace sema; 43 44 SourceLocation 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. 52 static 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. 72 static 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 98 /// Check that the argument to __builtin_addressof is a glvalue, and set the 99 /// result type to the corresponding pointer type. 100 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 101 if (checkArgCount(S, TheCall, 1)) 102 return true; 103 104 ExprResult Arg(S.Owned(TheCall->getArg(0))); 105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 106 if (ResultType.isNull()) 107 return true; 108 109 TheCall->setArg(0, Arg.take()); 110 TheCall->setType(ResultType); 111 return false; 112 } 113 114 ExprResult 115 Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 116 ExprResult TheCallResult(Owned(TheCall)); 117 118 // Find out if any arguments are required to be integer constant expressions. 119 unsigned ICEArguments = 0; 120 ASTContext::GetBuiltinTypeError Error; 121 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 122 if (Error != ASTContext::GE_None) 123 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 124 125 // If any arguments are required to be ICE's, check and diagnose. 126 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 127 // Skip arguments not required to be ICE's. 128 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 129 130 llvm::APSInt Result; 131 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 132 return true; 133 ICEArguments &= ~(1 << ArgNo); 134 } 135 136 switch (BuiltinID) { 137 case Builtin::BI__builtin___CFStringMakeConstantString: 138 assert(TheCall->getNumArgs() == 1 && 139 "Wrong # arguments to builtin CFStringMakeConstantString"); 140 if (CheckObjCString(TheCall->getArg(0))) 141 return ExprError(); 142 break; 143 case Builtin::BI__builtin_stdarg_start: 144 case Builtin::BI__builtin_va_start: 145 if (SemaBuiltinVAStart(TheCall)) 146 return ExprError(); 147 break; 148 case Builtin::BI__builtin_isgreater: 149 case Builtin::BI__builtin_isgreaterequal: 150 case Builtin::BI__builtin_isless: 151 case Builtin::BI__builtin_islessequal: 152 case Builtin::BI__builtin_islessgreater: 153 case Builtin::BI__builtin_isunordered: 154 if (SemaBuiltinUnorderedCompare(TheCall)) 155 return ExprError(); 156 break; 157 case Builtin::BI__builtin_fpclassify: 158 if (SemaBuiltinFPClassification(TheCall, 6)) 159 return ExprError(); 160 break; 161 case Builtin::BI__builtin_isfinite: 162 case Builtin::BI__builtin_isinf: 163 case Builtin::BI__builtin_isinf_sign: 164 case Builtin::BI__builtin_isnan: 165 case Builtin::BI__builtin_isnormal: 166 if (SemaBuiltinFPClassification(TheCall, 1)) 167 return ExprError(); 168 break; 169 case Builtin::BI__builtin_shufflevector: 170 return SemaBuiltinShuffleVector(TheCall); 171 // TheCall will be freed by the smart pointer here, but that's fine, since 172 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 173 case Builtin::BI__builtin_prefetch: 174 if (SemaBuiltinPrefetch(TheCall)) 175 return ExprError(); 176 break; 177 case Builtin::BI__builtin_object_size: 178 if (SemaBuiltinObjectSize(TheCall)) 179 return ExprError(); 180 break; 181 case Builtin::BI__builtin_longjmp: 182 if (SemaBuiltinLongjmp(TheCall)) 183 return ExprError(); 184 break; 185 186 case Builtin::BI__builtin_classify_type: 187 if (checkArgCount(*this, TheCall, 1)) return true; 188 TheCall->setType(Context.IntTy); 189 break; 190 case Builtin::BI__builtin_constant_p: 191 if (checkArgCount(*this, TheCall, 1)) return true; 192 TheCall->setType(Context.IntTy); 193 break; 194 case Builtin::BI__sync_fetch_and_add: 195 case Builtin::BI__sync_fetch_and_add_1: 196 case Builtin::BI__sync_fetch_and_add_2: 197 case Builtin::BI__sync_fetch_and_add_4: 198 case Builtin::BI__sync_fetch_and_add_8: 199 case Builtin::BI__sync_fetch_and_add_16: 200 case Builtin::BI__sync_fetch_and_sub: 201 case Builtin::BI__sync_fetch_and_sub_1: 202 case Builtin::BI__sync_fetch_and_sub_2: 203 case Builtin::BI__sync_fetch_and_sub_4: 204 case Builtin::BI__sync_fetch_and_sub_8: 205 case Builtin::BI__sync_fetch_and_sub_16: 206 case Builtin::BI__sync_fetch_and_or: 207 case Builtin::BI__sync_fetch_and_or_1: 208 case Builtin::BI__sync_fetch_and_or_2: 209 case Builtin::BI__sync_fetch_and_or_4: 210 case Builtin::BI__sync_fetch_and_or_8: 211 case Builtin::BI__sync_fetch_and_or_16: 212 case Builtin::BI__sync_fetch_and_and: 213 case Builtin::BI__sync_fetch_and_and_1: 214 case Builtin::BI__sync_fetch_and_and_2: 215 case Builtin::BI__sync_fetch_and_and_4: 216 case Builtin::BI__sync_fetch_and_and_8: 217 case Builtin::BI__sync_fetch_and_and_16: 218 case Builtin::BI__sync_fetch_and_xor: 219 case Builtin::BI__sync_fetch_and_xor_1: 220 case Builtin::BI__sync_fetch_and_xor_2: 221 case Builtin::BI__sync_fetch_and_xor_4: 222 case Builtin::BI__sync_fetch_and_xor_8: 223 case Builtin::BI__sync_fetch_and_xor_16: 224 case Builtin::BI__sync_add_and_fetch: 225 case Builtin::BI__sync_add_and_fetch_1: 226 case Builtin::BI__sync_add_and_fetch_2: 227 case Builtin::BI__sync_add_and_fetch_4: 228 case Builtin::BI__sync_add_and_fetch_8: 229 case Builtin::BI__sync_add_and_fetch_16: 230 case Builtin::BI__sync_sub_and_fetch: 231 case Builtin::BI__sync_sub_and_fetch_1: 232 case Builtin::BI__sync_sub_and_fetch_2: 233 case Builtin::BI__sync_sub_and_fetch_4: 234 case Builtin::BI__sync_sub_and_fetch_8: 235 case Builtin::BI__sync_sub_and_fetch_16: 236 case Builtin::BI__sync_and_and_fetch: 237 case Builtin::BI__sync_and_and_fetch_1: 238 case Builtin::BI__sync_and_and_fetch_2: 239 case Builtin::BI__sync_and_and_fetch_4: 240 case Builtin::BI__sync_and_and_fetch_8: 241 case Builtin::BI__sync_and_and_fetch_16: 242 case Builtin::BI__sync_or_and_fetch: 243 case Builtin::BI__sync_or_and_fetch_1: 244 case Builtin::BI__sync_or_and_fetch_2: 245 case Builtin::BI__sync_or_and_fetch_4: 246 case Builtin::BI__sync_or_and_fetch_8: 247 case Builtin::BI__sync_or_and_fetch_16: 248 case Builtin::BI__sync_xor_and_fetch: 249 case Builtin::BI__sync_xor_and_fetch_1: 250 case Builtin::BI__sync_xor_and_fetch_2: 251 case Builtin::BI__sync_xor_and_fetch_4: 252 case Builtin::BI__sync_xor_and_fetch_8: 253 case Builtin::BI__sync_xor_and_fetch_16: 254 case Builtin::BI__sync_val_compare_and_swap: 255 case Builtin::BI__sync_val_compare_and_swap_1: 256 case Builtin::BI__sync_val_compare_and_swap_2: 257 case Builtin::BI__sync_val_compare_and_swap_4: 258 case Builtin::BI__sync_val_compare_and_swap_8: 259 case Builtin::BI__sync_val_compare_and_swap_16: 260 case Builtin::BI__sync_bool_compare_and_swap: 261 case Builtin::BI__sync_bool_compare_and_swap_1: 262 case Builtin::BI__sync_bool_compare_and_swap_2: 263 case Builtin::BI__sync_bool_compare_and_swap_4: 264 case Builtin::BI__sync_bool_compare_and_swap_8: 265 case Builtin::BI__sync_bool_compare_and_swap_16: 266 case Builtin::BI__sync_lock_test_and_set: 267 case Builtin::BI__sync_lock_test_and_set_1: 268 case Builtin::BI__sync_lock_test_and_set_2: 269 case Builtin::BI__sync_lock_test_and_set_4: 270 case Builtin::BI__sync_lock_test_and_set_8: 271 case Builtin::BI__sync_lock_test_and_set_16: 272 case Builtin::BI__sync_lock_release: 273 case Builtin::BI__sync_lock_release_1: 274 case Builtin::BI__sync_lock_release_2: 275 case Builtin::BI__sync_lock_release_4: 276 case Builtin::BI__sync_lock_release_8: 277 case Builtin::BI__sync_lock_release_16: 278 case Builtin::BI__sync_swap: 279 case Builtin::BI__sync_swap_1: 280 case Builtin::BI__sync_swap_2: 281 case Builtin::BI__sync_swap_4: 282 case Builtin::BI__sync_swap_8: 283 case Builtin::BI__sync_swap_16: 284 return SemaBuiltinAtomicOverloaded(TheCallResult); 285 #define BUILTIN(ID, TYPE, ATTRS) 286 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 287 case Builtin::BI##ID: \ 288 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 289 #include "clang/Basic/Builtins.def" 290 case Builtin::BI__builtin_annotation: 291 if (SemaBuiltinAnnotation(*this, TheCall)) 292 return ExprError(); 293 break; 294 case Builtin::BI__builtin_addressof: 295 if (SemaBuiltinAddressof(*this, TheCall)) 296 return ExprError(); 297 break; 298 } 299 300 // Since the target specific builtins for each arch overlap, only check those 301 // of the arch we are compiling for. 302 if (BuiltinID >= Builtin::FirstTSBuiltin) { 303 switch (Context.getTargetInfo().getTriple().getArch()) { 304 case llvm::Triple::arm: 305 case llvm::Triple::thumb: 306 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 307 return ExprError(); 308 break; 309 case llvm::Triple::aarch64: 310 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 311 return ExprError(); 312 break; 313 case llvm::Triple::mips: 314 case llvm::Triple::mipsel: 315 case llvm::Triple::mips64: 316 case llvm::Triple::mips64el: 317 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 318 return ExprError(); 319 break; 320 default: 321 break; 322 } 323 } 324 325 return TheCallResult; 326 } 327 328 // Get the valid immediate range for the specified NEON type code. 329 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 330 NeonTypeFlags Type(t); 331 int IsQuad = ForceQuad ? true : Type.isQuad(); 332 switch (Type.getEltType()) { 333 case NeonTypeFlags::Int8: 334 case NeonTypeFlags::Poly8: 335 return shift ? 7 : (8 << IsQuad) - 1; 336 case NeonTypeFlags::Int16: 337 case NeonTypeFlags::Poly16: 338 return shift ? 15 : (4 << IsQuad) - 1; 339 case NeonTypeFlags::Int32: 340 return shift ? 31 : (2 << IsQuad) - 1; 341 case NeonTypeFlags::Int64: 342 case NeonTypeFlags::Poly64: 343 return shift ? 63 : (1 << IsQuad) - 1; 344 case NeonTypeFlags::Poly128: 345 return shift ? 127 : (1 << IsQuad) - 1; 346 case NeonTypeFlags::Float16: 347 assert(!shift && "cannot shift float types!"); 348 return (4 << IsQuad) - 1; 349 case NeonTypeFlags::Float32: 350 assert(!shift && "cannot shift float types!"); 351 return (2 << IsQuad) - 1; 352 case NeonTypeFlags::Float64: 353 assert(!shift && "cannot shift float types!"); 354 return (1 << IsQuad) - 1; 355 } 356 llvm_unreachable("Invalid NeonTypeFlag!"); 357 } 358 359 /// getNeonEltType - Return the QualType corresponding to the elements of 360 /// the vector type specified by the NeonTypeFlags. This is used to check 361 /// the pointer arguments for Neon load/store intrinsics. 362 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 363 bool IsAArch64) { 364 switch (Flags.getEltType()) { 365 case NeonTypeFlags::Int8: 366 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 367 case NeonTypeFlags::Int16: 368 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 369 case NeonTypeFlags::Int32: 370 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 371 case NeonTypeFlags::Int64: 372 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy; 373 case NeonTypeFlags::Poly8: 374 return IsAArch64 ? Context.UnsignedCharTy : Context.SignedCharTy; 375 case NeonTypeFlags::Poly16: 376 return IsAArch64 ? Context.UnsignedShortTy : Context.ShortTy; 377 case NeonTypeFlags::Poly64: 378 return Context.UnsignedLongLongTy; 379 case NeonTypeFlags::Poly128: 380 break; 381 case NeonTypeFlags::Float16: 382 return Context.HalfTy; 383 case NeonTypeFlags::Float32: 384 return Context.FloatTy; 385 case NeonTypeFlags::Float64: 386 return Context.DoubleTy; 387 } 388 llvm_unreachable("Invalid NeonTypeFlag!"); 389 } 390 391 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 392 CallExpr *TheCall) { 393 394 llvm::APSInt Result; 395 396 uint64_t mask = 0; 397 unsigned TV = 0; 398 int PtrArgNum = -1; 399 bool HasConstPtr = false; 400 switch (BuiltinID) { 401 #define GET_NEON_AARCH64_OVERLOAD_CHECK 402 #include "clang/Basic/arm_neon.inc" 403 #undef GET_NEON_AARCH64_OVERLOAD_CHECK 404 } 405 406 // For NEON intrinsics which are overloaded on vector element type, validate 407 // the immediate which specifies which variant to emit. 408 unsigned ImmArg = TheCall->getNumArgs() - 1; 409 if (mask) { 410 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 411 return true; 412 413 TV = Result.getLimitedValue(64); 414 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 415 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 416 << TheCall->getArg(ImmArg)->getSourceRange(); 417 } 418 419 if (PtrArgNum >= 0) { 420 // Check that pointer arguments have the specified type. 421 Expr *Arg = TheCall->getArg(PtrArgNum); 422 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 423 Arg = ICE->getSubExpr(); 424 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 425 QualType RHSTy = RHS.get()->getType(); 426 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, true); 427 if (HasConstPtr) 428 EltTy = EltTy.withConst(); 429 QualType LHSTy = Context.getPointerType(EltTy); 430 AssignConvertType ConvTy; 431 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 432 if (RHS.isInvalid()) 433 return true; 434 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 435 RHS.get(), AA_Assigning)) 436 return true; 437 } 438 439 // For NEON intrinsics which take an immediate value as part of the 440 // instruction, range check them here. 441 unsigned i = 0, l = 0, u = 0; 442 switch (BuiltinID) { 443 default: 444 return false; 445 #define GET_NEON_AARCH64_IMMEDIATE_CHECK 446 #include "clang/Basic/arm_neon.inc" 447 #undef GET_NEON_AARCH64_IMMEDIATE_CHECK 448 } 449 ; 450 451 // We can't check the value of a dependent argument. 452 if (TheCall->getArg(i)->isTypeDependent() || 453 TheCall->getArg(i)->isValueDependent()) 454 return false; 455 456 // Check that the immediate argument is actually a constant. 457 if (SemaBuiltinConstantArg(TheCall, i, Result)) 458 return true; 459 460 // Range check against the upper/lower values for this isntruction. 461 unsigned Val = Result.getZExtValue(); 462 if (Val < l || Val > (u + l)) 463 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 464 << l << u + l << TheCall->getArg(i)->getSourceRange(); 465 466 return false; 467 } 468 469 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) { 470 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 471 BuiltinID == ARM::BI__builtin_arm_strex) && 472 "unexpected ARM builtin"); 473 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex; 474 475 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 476 477 // Ensure that we have the proper number of arguments. 478 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 479 return true; 480 481 // Inspect the pointer argument of the atomic builtin. This should always be 482 // a pointer type, whose element is an integral scalar or pointer type. 483 // Because it is a pointer type, we don't have to worry about any implicit 484 // casts here. 485 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 486 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 487 if (PointerArgRes.isInvalid()) 488 return true; 489 PointerArg = PointerArgRes.take(); 490 491 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 492 if (!pointerType) { 493 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 494 << PointerArg->getType() << PointerArg->getSourceRange(); 495 return true; 496 } 497 498 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 499 // task is to insert the appropriate casts into the AST. First work out just 500 // what the appropriate type is. 501 QualType ValType = pointerType->getPointeeType(); 502 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 503 if (IsLdrex) 504 AddrType.addConst(); 505 506 // Issue a warning if the cast is dodgy. 507 CastKind CastNeeded = CK_NoOp; 508 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 509 CastNeeded = CK_BitCast; 510 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 511 << PointerArg->getType() 512 << Context.getPointerType(AddrType) 513 << AA_Passing << PointerArg->getSourceRange(); 514 } 515 516 // Finally, do the cast and replace the argument with the corrected version. 517 AddrType = Context.getPointerType(AddrType); 518 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 519 if (PointerArgRes.isInvalid()) 520 return true; 521 PointerArg = PointerArgRes.take(); 522 523 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 524 525 // In general, we allow ints, floats and pointers to be loaded and stored. 526 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 527 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 528 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 529 << PointerArg->getType() << PointerArg->getSourceRange(); 530 return true; 531 } 532 533 // But ARM doesn't have instructions to deal with 128-bit versions. 534 if (Context.getTypeSize(ValType) > 64) { 535 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 536 << PointerArg->getType() << PointerArg->getSourceRange(); 537 return true; 538 } 539 540 switch (ValType.getObjCLifetime()) { 541 case Qualifiers::OCL_None: 542 case Qualifiers::OCL_ExplicitNone: 543 // okay 544 break; 545 546 case Qualifiers::OCL_Weak: 547 case Qualifiers::OCL_Strong: 548 case Qualifiers::OCL_Autoreleasing: 549 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 550 << ValType << PointerArg->getSourceRange(); 551 return true; 552 } 553 554 555 if (IsLdrex) { 556 TheCall->setType(ValType); 557 return false; 558 } 559 560 // Initialize the argument to be stored. 561 ExprResult ValArg = TheCall->getArg(0); 562 InitializedEntity Entity = InitializedEntity::InitializeParameter( 563 Context, ValType, /*consume*/ false); 564 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 565 if (ValArg.isInvalid()) 566 return true; 567 TheCall->setArg(0, ValArg.get()); 568 569 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 570 // but the custom checker bypasses all default analysis. 571 TheCall->setType(Context.IntTy); 572 return false; 573 } 574 575 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 576 llvm::APSInt Result; 577 578 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 579 BuiltinID == ARM::BI__builtin_arm_strex) { 580 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall); 581 } 582 583 uint64_t mask = 0; 584 unsigned TV = 0; 585 int PtrArgNum = -1; 586 bool HasConstPtr = false; 587 switch (BuiltinID) { 588 #define GET_NEON_OVERLOAD_CHECK 589 #include "clang/Basic/arm_neon.inc" 590 #undef GET_NEON_OVERLOAD_CHECK 591 } 592 593 // For NEON intrinsics which are overloaded on vector element type, validate 594 // the immediate which specifies which variant to emit. 595 unsigned ImmArg = TheCall->getNumArgs()-1; 596 if (mask) { 597 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 598 return true; 599 600 TV = Result.getLimitedValue(64); 601 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 602 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 603 << TheCall->getArg(ImmArg)->getSourceRange(); 604 } 605 606 if (PtrArgNum >= 0) { 607 // Check that pointer arguments have the specified type. 608 Expr *Arg = TheCall->getArg(PtrArgNum); 609 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 610 Arg = ICE->getSubExpr(); 611 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 612 QualType RHSTy = RHS.get()->getType(); 613 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, false); 614 if (HasConstPtr) 615 EltTy = EltTy.withConst(); 616 QualType LHSTy = Context.getPointerType(EltTy); 617 AssignConvertType ConvTy; 618 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 619 if (RHS.isInvalid()) 620 return true; 621 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 622 RHS.get(), AA_Assigning)) 623 return true; 624 } 625 626 // For NEON intrinsics which take an immediate value as part of the 627 // instruction, range check them here. 628 unsigned i = 0, l = 0, u = 0; 629 switch (BuiltinID) { 630 default: return false; 631 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 632 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 633 case ARM::BI__builtin_arm_vcvtr_f: 634 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 635 case ARM::BI__builtin_arm_dmb: 636 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break; 637 #define GET_NEON_IMMEDIATE_CHECK 638 #include "clang/Basic/arm_neon.inc" 639 #undef GET_NEON_IMMEDIATE_CHECK 640 }; 641 642 // We can't check the value of a dependent argument. 643 if (TheCall->getArg(i)->isTypeDependent() || 644 TheCall->getArg(i)->isValueDependent()) 645 return false; 646 647 // Check that the immediate argument is actually a constant. 648 if (SemaBuiltinConstantArg(TheCall, i, Result)) 649 return true; 650 651 // Range check against the upper/lower values for this isntruction. 652 unsigned Val = Result.getZExtValue(); 653 if (Val < l || Val > (u + l)) 654 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 655 << l << u+l << TheCall->getArg(i)->getSourceRange(); 656 657 // FIXME: VFP Intrinsics should error if VFP not present. 658 return false; 659 } 660 661 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 662 unsigned i = 0, l = 0, u = 0; 663 switch (BuiltinID) { 664 default: return false; 665 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 666 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 667 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 668 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 669 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 670 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 671 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 672 }; 673 674 // We can't check the value of a dependent argument. 675 if (TheCall->getArg(i)->isTypeDependent() || 676 TheCall->getArg(i)->isValueDependent()) 677 return false; 678 679 // Check that the immediate argument is actually a constant. 680 llvm::APSInt Result; 681 if (SemaBuiltinConstantArg(TheCall, i, Result)) 682 return true; 683 684 // Range check against the upper/lower values for this instruction. 685 unsigned Val = Result.getZExtValue(); 686 if (Val < l || Val > u) 687 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 688 << l << u << TheCall->getArg(i)->getSourceRange(); 689 690 return false; 691 } 692 693 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 694 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 695 /// Returns true when the format fits the function and the FormatStringInfo has 696 /// been populated. 697 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 698 FormatStringInfo *FSI) { 699 FSI->HasVAListArg = Format->getFirstArg() == 0; 700 FSI->FormatIdx = Format->getFormatIdx() - 1; 701 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 702 703 // The way the format attribute works in GCC, the implicit this argument 704 // of member functions is counted. However, it doesn't appear in our own 705 // lists, so decrement format_idx in that case. 706 if (IsCXXMember) { 707 if(FSI->FormatIdx == 0) 708 return false; 709 --FSI->FormatIdx; 710 if (FSI->FirstDataArg != 0) 711 --FSI->FirstDataArg; 712 } 713 return true; 714 } 715 716 /// Checks if a the given expression evaluates to null. 717 /// 718 /// \brief Returns true if the value evaluates to null. 719 static bool CheckNonNullExpr(Sema &S, 720 const Expr *Expr) { 721 // As a special case, transparent unions initialized with zero are 722 // considered null for the purposes of the nonnull attribute. 723 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 724 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 725 if (const CompoundLiteralExpr *CLE = 726 dyn_cast<CompoundLiteralExpr>(Expr)) 727 if (const InitListExpr *ILE = 728 dyn_cast<InitListExpr>(CLE->getInitializer())) 729 Expr = ILE->getInit(0); 730 } 731 732 bool Result; 733 return (!Expr->isValueDependent() && 734 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 735 !Result); 736 } 737 738 static void CheckNonNullArgument(Sema &S, 739 const Expr *ArgExpr, 740 SourceLocation CallSiteLoc) { 741 if (CheckNonNullExpr(S, ArgExpr)) 742 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 743 } 744 745 static void CheckNonNullArguments(Sema &S, 746 const NamedDecl *FDecl, 747 const Expr * const *ExprArgs, 748 SourceLocation CallSiteLoc) { 749 // Check the attributes attached to the method/function itself. 750 for (specific_attr_iterator<NonNullAttr> 751 I = FDecl->specific_attr_begin<NonNullAttr>(), 752 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) { 753 754 const NonNullAttr *NonNull = *I; 755 for (NonNullAttr::args_iterator i = NonNull->args_begin(), 756 e = NonNull->args_end(); 757 i != e; ++i) { 758 CheckNonNullArgument(S, ExprArgs[*i], CallSiteLoc); 759 } 760 } 761 762 // Check the attributes on the parameters. 763 ArrayRef<ParmVarDecl*> parms; 764 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 765 parms = FD->parameters(); 766 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl)) 767 parms = MD->parameters(); 768 769 unsigned argIndex = 0; 770 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 771 I != E; ++I, ++argIndex) { 772 const ParmVarDecl *PVD = *I; 773 if (PVD->hasAttr<NonNullAttr>()) 774 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc); 775 } 776 } 777 778 /// Handles the checks for format strings, non-POD arguments to vararg 779 /// functions, and NULL arguments passed to non-NULL parameters. 780 void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args, 781 unsigned NumParams, bool IsMemberFunction, 782 SourceLocation Loc, SourceRange Range, 783 VariadicCallType CallType) { 784 // FIXME: We should check as much as we can in the template definition. 785 if (CurContext->isDependentContext()) 786 return; 787 788 // Printf and scanf checking. 789 llvm::SmallBitVector CheckedVarArgs; 790 if (FDecl) { 791 for (specific_attr_iterator<FormatAttr> 792 I = FDecl->specific_attr_begin<FormatAttr>(), 793 E = FDecl->specific_attr_end<FormatAttr>(); 794 I != E; ++I) { 795 // Only create vector if there are format attributes. 796 CheckedVarArgs.resize(Args.size()); 797 798 CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range, 799 CheckedVarArgs); 800 } 801 } 802 803 // Refuse POD arguments that weren't caught by the format string 804 // checks above. 805 if (CallType != VariadicDoesNotApply) { 806 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 807 // Args[ArgIdx] can be null in malformed code. 808 if (const Expr *Arg = Args[ArgIdx]) { 809 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 810 checkVariadicArgument(Arg, CallType); 811 } 812 } 813 } 814 815 if (FDecl) { 816 CheckNonNullArguments(*this, FDecl, Args.data(), Loc); 817 818 // Type safety checking. 819 for (specific_attr_iterator<ArgumentWithTypeTagAttr> 820 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(), 821 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>(); 822 i != e; ++i) { 823 CheckArgumentWithTypeTag(*i, Args.data()); 824 } 825 } 826 } 827 828 /// CheckConstructorCall - Check a constructor call for correctness and safety 829 /// properties not enforced by the C type system. 830 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 831 ArrayRef<const Expr *> Args, 832 const FunctionProtoType *Proto, 833 SourceLocation Loc) { 834 VariadicCallType CallType = 835 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 836 checkCall(FDecl, Args, Proto->getNumParams(), 837 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType); 838 } 839 840 /// CheckFunctionCall - Check a direct function call for various correctness 841 /// and safety properties not strictly enforced by the C type system. 842 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 843 const FunctionProtoType *Proto) { 844 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 845 isa<CXXMethodDecl>(FDecl); 846 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 847 IsMemberOperatorCall; 848 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 849 TheCall->getCallee()); 850 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 851 Expr** Args = TheCall->getArgs(); 852 unsigned NumArgs = TheCall->getNumArgs(); 853 if (IsMemberOperatorCall) { 854 // If this is a call to a member operator, hide the first argument 855 // from checkCall. 856 // FIXME: Our choice of AST representation here is less than ideal. 857 ++Args; 858 --NumArgs; 859 } 860 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams, 861 IsMemberFunction, TheCall->getRParenLoc(), 862 TheCall->getCallee()->getSourceRange(), CallType); 863 864 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 865 // None of the checks below are needed for functions that don't have 866 // simple names (e.g., C++ conversion functions). 867 if (!FnInfo) 868 return false; 869 870 unsigned CMId = FDecl->getMemoryFunctionKind(); 871 if (CMId == 0) 872 return false; 873 874 // Handle memory setting and copying functions. 875 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 876 CheckStrlcpycatArguments(TheCall, FnInfo); 877 else if (CMId == Builtin::BIstrncat) 878 CheckStrncatArguments(TheCall, FnInfo); 879 else 880 CheckMemaccessArguments(TheCall, CMId, FnInfo); 881 882 return false; 883 } 884 885 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 886 ArrayRef<const Expr *> Args) { 887 VariadicCallType CallType = 888 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 889 890 checkCall(Method, Args, Method->param_size(), 891 /*IsMemberFunction=*/false, 892 lbrac, Method->getSourceRange(), CallType); 893 894 return false; 895 } 896 897 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 898 const FunctionProtoType *Proto) { 899 const VarDecl *V = dyn_cast<VarDecl>(NDecl); 900 if (!V) 901 return false; 902 903 QualType Ty = V->getType(); 904 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType()) 905 return false; 906 907 VariadicCallType CallType; 908 if (!Proto || !Proto->isVariadic()) { 909 CallType = VariadicDoesNotApply; 910 } else if (Ty->isBlockPointerType()) { 911 CallType = VariadicBlock; 912 } else { // Ty->isFunctionPointerType() 913 CallType = VariadicFunction; 914 } 915 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 916 917 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(), 918 TheCall->getNumArgs()), 919 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 920 TheCall->getCallee()->getSourceRange(), CallType); 921 922 return false; 923 } 924 925 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 926 /// such as function pointers returned from functions. 927 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 928 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto, 929 TheCall->getCallee()); 930 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 931 932 checkCall(/*FDecl=*/0, llvm::makeArrayRef<const Expr *>( 933 TheCall->getArgs(), TheCall->getNumArgs()), 934 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 935 TheCall->getCallee()->getSourceRange(), CallType); 936 937 return false; 938 } 939 940 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 941 AtomicExpr::AtomicOp Op) { 942 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 943 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 944 945 // All these operations take one of the following forms: 946 enum { 947 // C __c11_atomic_init(A *, C) 948 Init, 949 // C __c11_atomic_load(A *, int) 950 Load, 951 // void __atomic_load(A *, CP, int) 952 Copy, 953 // C __c11_atomic_add(A *, M, int) 954 Arithmetic, 955 // C __atomic_exchange_n(A *, CP, int) 956 Xchg, 957 // void __atomic_exchange(A *, C *, CP, int) 958 GNUXchg, 959 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 960 C11CmpXchg, 961 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 962 GNUCmpXchg 963 } Form = Init; 964 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 }; 965 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 }; 966 // where: 967 // C is an appropriate type, 968 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 969 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 970 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 971 // the int parameters are for orderings. 972 973 assert(AtomicExpr::AO__c11_atomic_init == 0 && 974 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load 975 && "need to update code for modified C11 atomics"); 976 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init && 977 Op <= AtomicExpr::AO__c11_atomic_fetch_xor; 978 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 979 Op == AtomicExpr::AO__atomic_store_n || 980 Op == AtomicExpr::AO__atomic_exchange_n || 981 Op == AtomicExpr::AO__atomic_compare_exchange_n; 982 bool IsAddSub = false; 983 984 switch (Op) { 985 case AtomicExpr::AO__c11_atomic_init: 986 Form = Init; 987 break; 988 989 case AtomicExpr::AO__c11_atomic_load: 990 case AtomicExpr::AO__atomic_load_n: 991 Form = Load; 992 break; 993 994 case AtomicExpr::AO__c11_atomic_store: 995 case AtomicExpr::AO__atomic_load: 996 case AtomicExpr::AO__atomic_store: 997 case AtomicExpr::AO__atomic_store_n: 998 Form = Copy; 999 break; 1000 1001 case AtomicExpr::AO__c11_atomic_fetch_add: 1002 case AtomicExpr::AO__c11_atomic_fetch_sub: 1003 case AtomicExpr::AO__atomic_fetch_add: 1004 case AtomicExpr::AO__atomic_fetch_sub: 1005 case AtomicExpr::AO__atomic_add_fetch: 1006 case AtomicExpr::AO__atomic_sub_fetch: 1007 IsAddSub = true; 1008 // Fall through. 1009 case AtomicExpr::AO__c11_atomic_fetch_and: 1010 case AtomicExpr::AO__c11_atomic_fetch_or: 1011 case AtomicExpr::AO__c11_atomic_fetch_xor: 1012 case AtomicExpr::AO__atomic_fetch_and: 1013 case AtomicExpr::AO__atomic_fetch_or: 1014 case AtomicExpr::AO__atomic_fetch_xor: 1015 case AtomicExpr::AO__atomic_fetch_nand: 1016 case AtomicExpr::AO__atomic_and_fetch: 1017 case AtomicExpr::AO__atomic_or_fetch: 1018 case AtomicExpr::AO__atomic_xor_fetch: 1019 case AtomicExpr::AO__atomic_nand_fetch: 1020 Form = Arithmetic; 1021 break; 1022 1023 case AtomicExpr::AO__c11_atomic_exchange: 1024 case AtomicExpr::AO__atomic_exchange_n: 1025 Form = Xchg; 1026 break; 1027 1028 case AtomicExpr::AO__atomic_exchange: 1029 Form = GNUXchg; 1030 break; 1031 1032 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 1033 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 1034 Form = C11CmpXchg; 1035 break; 1036 1037 case AtomicExpr::AO__atomic_compare_exchange: 1038 case AtomicExpr::AO__atomic_compare_exchange_n: 1039 Form = GNUCmpXchg; 1040 break; 1041 } 1042 1043 // Check we have the right number of arguments. 1044 if (TheCall->getNumArgs() < NumArgs[Form]) { 1045 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1046 << 0 << NumArgs[Form] << TheCall->getNumArgs() 1047 << TheCall->getCallee()->getSourceRange(); 1048 return ExprError(); 1049 } else if (TheCall->getNumArgs() > NumArgs[Form]) { 1050 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(), 1051 diag::err_typecheck_call_too_many_args) 1052 << 0 << NumArgs[Form] << TheCall->getNumArgs() 1053 << TheCall->getCallee()->getSourceRange(); 1054 return ExprError(); 1055 } 1056 1057 // Inspect the first argument of the atomic operation. 1058 Expr *Ptr = TheCall->getArg(0); 1059 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get(); 1060 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 1061 if (!pointerType) { 1062 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1063 << Ptr->getType() << Ptr->getSourceRange(); 1064 return ExprError(); 1065 } 1066 1067 // For a __c11 builtin, this should be a pointer to an _Atomic type. 1068 QualType AtomTy = pointerType->getPointeeType(); // 'A' 1069 QualType ValType = AtomTy; // 'C' 1070 if (IsC11) { 1071 if (!AtomTy->isAtomicType()) { 1072 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 1073 << Ptr->getType() << Ptr->getSourceRange(); 1074 return ExprError(); 1075 } 1076 if (AtomTy.isConstQualified()) { 1077 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 1078 << Ptr->getType() << Ptr->getSourceRange(); 1079 return ExprError(); 1080 } 1081 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 1082 } 1083 1084 // For an arithmetic operation, the implied arithmetic must be well-formed. 1085 if (Form == Arithmetic) { 1086 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 1087 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 1088 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 1089 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 1090 return ExprError(); 1091 } 1092 if (!IsAddSub && !ValType->isIntegerType()) { 1093 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 1094 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 1095 return ExprError(); 1096 } 1097 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 1098 // For __atomic_*_n operations, the value type must be a scalar integral or 1099 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 1100 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 1101 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 1102 return ExprError(); 1103 } 1104 1105 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 1106 !AtomTy->isScalarType()) { 1107 // For GNU atomics, require a trivially-copyable type. This is not part of 1108 // the GNU atomics specification, but we enforce it for sanity. 1109 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 1110 << Ptr->getType() << Ptr->getSourceRange(); 1111 return ExprError(); 1112 } 1113 1114 // FIXME: For any builtin other than a load, the ValType must not be 1115 // const-qualified. 1116 1117 switch (ValType.getObjCLifetime()) { 1118 case Qualifiers::OCL_None: 1119 case Qualifiers::OCL_ExplicitNone: 1120 // okay 1121 break; 1122 1123 case Qualifiers::OCL_Weak: 1124 case Qualifiers::OCL_Strong: 1125 case Qualifiers::OCL_Autoreleasing: 1126 // FIXME: Can this happen? By this point, ValType should be known 1127 // to be trivially copyable. 1128 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1129 << ValType << Ptr->getSourceRange(); 1130 return ExprError(); 1131 } 1132 1133 QualType ResultType = ValType; 1134 if (Form == Copy || Form == GNUXchg || Form == Init) 1135 ResultType = Context.VoidTy; 1136 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 1137 ResultType = Context.BoolTy; 1138 1139 // The type of a parameter passed 'by value'. In the GNU atomics, such 1140 // arguments are actually passed as pointers. 1141 QualType ByValType = ValType; // 'CP' 1142 if (!IsC11 && !IsN) 1143 ByValType = Ptr->getType(); 1144 1145 // The first argument --- the pointer --- has a fixed type; we 1146 // deduce the types of the rest of the arguments accordingly. Walk 1147 // the remaining arguments, converting them to the deduced value type. 1148 for (unsigned i = 1; i != NumArgs[Form]; ++i) { 1149 QualType Ty; 1150 if (i < NumVals[Form] + 1) { 1151 switch (i) { 1152 case 1: 1153 // The second argument is the non-atomic operand. For arithmetic, this 1154 // is always passed by value, and for a compare_exchange it is always 1155 // passed by address. For the rest, GNU uses by-address and C11 uses 1156 // by-value. 1157 assert(Form != Load); 1158 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 1159 Ty = ValType; 1160 else if (Form == Copy || Form == Xchg) 1161 Ty = ByValType; 1162 else if (Form == Arithmetic) 1163 Ty = Context.getPointerDiffType(); 1164 else 1165 Ty = Context.getPointerType(ValType.getUnqualifiedType()); 1166 break; 1167 case 2: 1168 // The third argument to compare_exchange / GNU exchange is a 1169 // (pointer to a) desired value. 1170 Ty = ByValType; 1171 break; 1172 case 3: 1173 // The fourth argument to GNU compare_exchange is a 'weak' flag. 1174 Ty = Context.BoolTy; 1175 break; 1176 } 1177 } else { 1178 // The order(s) are always converted to int. 1179 Ty = Context.IntTy; 1180 } 1181 1182 InitializedEntity Entity = 1183 InitializedEntity::InitializeParameter(Context, Ty, false); 1184 ExprResult Arg = TheCall->getArg(i); 1185 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 1186 if (Arg.isInvalid()) 1187 return true; 1188 TheCall->setArg(i, Arg.get()); 1189 } 1190 1191 // Permute the arguments into a 'consistent' order. 1192 SmallVector<Expr*, 5> SubExprs; 1193 SubExprs.push_back(Ptr); 1194 switch (Form) { 1195 case Init: 1196 // Note, AtomicExpr::getVal1() has a special case for this atomic. 1197 SubExprs.push_back(TheCall->getArg(1)); // Val1 1198 break; 1199 case Load: 1200 SubExprs.push_back(TheCall->getArg(1)); // Order 1201 break; 1202 case Copy: 1203 case Arithmetic: 1204 case Xchg: 1205 SubExprs.push_back(TheCall->getArg(2)); // Order 1206 SubExprs.push_back(TheCall->getArg(1)); // Val1 1207 break; 1208 case GNUXchg: 1209 // Note, AtomicExpr::getVal2() has a special case for this atomic. 1210 SubExprs.push_back(TheCall->getArg(3)); // Order 1211 SubExprs.push_back(TheCall->getArg(1)); // Val1 1212 SubExprs.push_back(TheCall->getArg(2)); // Val2 1213 break; 1214 case C11CmpXchg: 1215 SubExprs.push_back(TheCall->getArg(3)); // Order 1216 SubExprs.push_back(TheCall->getArg(1)); // Val1 1217 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 1218 SubExprs.push_back(TheCall->getArg(2)); // Val2 1219 break; 1220 case GNUCmpXchg: 1221 SubExprs.push_back(TheCall->getArg(4)); // Order 1222 SubExprs.push_back(TheCall->getArg(1)); // Val1 1223 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 1224 SubExprs.push_back(TheCall->getArg(2)); // Val2 1225 SubExprs.push_back(TheCall->getArg(3)); // Weak 1226 break; 1227 } 1228 1229 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 1230 SubExprs, ResultType, Op, 1231 TheCall->getRParenLoc()); 1232 1233 if ((Op == AtomicExpr::AO__c11_atomic_load || 1234 (Op == AtomicExpr::AO__c11_atomic_store)) && 1235 Context.AtomicUsesUnsupportedLibcall(AE)) 1236 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) << 1237 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1); 1238 1239 return Owned(AE); 1240 } 1241 1242 1243 /// checkBuiltinArgument - Given a call to a builtin function, perform 1244 /// normal type-checking on the given argument, updating the call in 1245 /// place. This is useful when a builtin function requires custom 1246 /// type-checking for some of its arguments but not necessarily all of 1247 /// them. 1248 /// 1249 /// Returns true on error. 1250 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 1251 FunctionDecl *Fn = E->getDirectCallee(); 1252 assert(Fn && "builtin call without direct callee!"); 1253 1254 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 1255 InitializedEntity Entity = 1256 InitializedEntity::InitializeParameter(S.Context, Param); 1257 1258 ExprResult Arg = E->getArg(0); 1259 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 1260 if (Arg.isInvalid()) 1261 return true; 1262 1263 E->setArg(ArgIndex, Arg.take()); 1264 return false; 1265 } 1266 1267 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 1268 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 1269 /// type of its first argument. The main ActOnCallExpr routines have already 1270 /// promoted the types of arguments because all of these calls are prototyped as 1271 /// void(...). 1272 /// 1273 /// This function goes through and does final semantic checking for these 1274 /// builtins, 1275 ExprResult 1276 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 1277 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 1278 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1279 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 1280 1281 // Ensure that we have at least one argument to do type inference from. 1282 if (TheCall->getNumArgs() < 1) { 1283 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 1284 << 0 << 1 << TheCall->getNumArgs() 1285 << TheCall->getCallee()->getSourceRange(); 1286 return ExprError(); 1287 } 1288 1289 // Inspect the first argument of the atomic builtin. This should always be 1290 // a pointer type, whose element is an integral scalar or pointer type. 1291 // Because it is a pointer type, we don't have to worry about any implicit 1292 // casts here. 1293 // FIXME: We don't allow floating point scalars as input. 1294 Expr *FirstArg = TheCall->getArg(0); 1295 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 1296 if (FirstArgResult.isInvalid()) 1297 return ExprError(); 1298 FirstArg = FirstArgResult.take(); 1299 TheCall->setArg(0, FirstArg); 1300 1301 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 1302 if (!pointerType) { 1303 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1304 << FirstArg->getType() << FirstArg->getSourceRange(); 1305 return ExprError(); 1306 } 1307 1308 QualType ValType = pointerType->getPointeeType(); 1309 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1310 !ValType->isBlockPointerType()) { 1311 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 1312 << FirstArg->getType() << FirstArg->getSourceRange(); 1313 return ExprError(); 1314 } 1315 1316 switch (ValType.getObjCLifetime()) { 1317 case Qualifiers::OCL_None: 1318 case Qualifiers::OCL_ExplicitNone: 1319 // okay 1320 break; 1321 1322 case Qualifiers::OCL_Weak: 1323 case Qualifiers::OCL_Strong: 1324 case Qualifiers::OCL_Autoreleasing: 1325 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1326 << ValType << FirstArg->getSourceRange(); 1327 return ExprError(); 1328 } 1329 1330 // Strip any qualifiers off ValType. 1331 ValType = ValType.getUnqualifiedType(); 1332 1333 // The majority of builtins return a value, but a few have special return 1334 // types, so allow them to override appropriately below. 1335 QualType ResultType = ValType; 1336 1337 // We need to figure out which concrete builtin this maps onto. For example, 1338 // __sync_fetch_and_add with a 2 byte object turns into 1339 // __sync_fetch_and_add_2. 1340 #define BUILTIN_ROW(x) \ 1341 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 1342 Builtin::BI##x##_8, Builtin::BI##x##_16 } 1343 1344 static const unsigned BuiltinIndices[][5] = { 1345 BUILTIN_ROW(__sync_fetch_and_add), 1346 BUILTIN_ROW(__sync_fetch_and_sub), 1347 BUILTIN_ROW(__sync_fetch_and_or), 1348 BUILTIN_ROW(__sync_fetch_and_and), 1349 BUILTIN_ROW(__sync_fetch_and_xor), 1350 1351 BUILTIN_ROW(__sync_add_and_fetch), 1352 BUILTIN_ROW(__sync_sub_and_fetch), 1353 BUILTIN_ROW(__sync_and_and_fetch), 1354 BUILTIN_ROW(__sync_or_and_fetch), 1355 BUILTIN_ROW(__sync_xor_and_fetch), 1356 1357 BUILTIN_ROW(__sync_val_compare_and_swap), 1358 BUILTIN_ROW(__sync_bool_compare_and_swap), 1359 BUILTIN_ROW(__sync_lock_test_and_set), 1360 BUILTIN_ROW(__sync_lock_release), 1361 BUILTIN_ROW(__sync_swap) 1362 }; 1363 #undef BUILTIN_ROW 1364 1365 // Determine the index of the size. 1366 unsigned SizeIndex; 1367 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 1368 case 1: SizeIndex = 0; break; 1369 case 2: SizeIndex = 1; break; 1370 case 4: SizeIndex = 2; break; 1371 case 8: SizeIndex = 3; break; 1372 case 16: SizeIndex = 4; break; 1373 default: 1374 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 1375 << FirstArg->getType() << FirstArg->getSourceRange(); 1376 return ExprError(); 1377 } 1378 1379 // Each of these builtins has one pointer argument, followed by some number of 1380 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 1381 // that we ignore. Find out which row of BuiltinIndices to read from as well 1382 // as the number of fixed args. 1383 unsigned BuiltinID = FDecl->getBuiltinID(); 1384 unsigned BuiltinIndex, NumFixed = 1; 1385 switch (BuiltinID) { 1386 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 1387 case Builtin::BI__sync_fetch_and_add: 1388 case Builtin::BI__sync_fetch_and_add_1: 1389 case Builtin::BI__sync_fetch_and_add_2: 1390 case Builtin::BI__sync_fetch_and_add_4: 1391 case Builtin::BI__sync_fetch_and_add_8: 1392 case Builtin::BI__sync_fetch_and_add_16: 1393 BuiltinIndex = 0; 1394 break; 1395 1396 case Builtin::BI__sync_fetch_and_sub: 1397 case Builtin::BI__sync_fetch_and_sub_1: 1398 case Builtin::BI__sync_fetch_and_sub_2: 1399 case Builtin::BI__sync_fetch_and_sub_4: 1400 case Builtin::BI__sync_fetch_and_sub_8: 1401 case Builtin::BI__sync_fetch_and_sub_16: 1402 BuiltinIndex = 1; 1403 break; 1404 1405 case Builtin::BI__sync_fetch_and_or: 1406 case Builtin::BI__sync_fetch_and_or_1: 1407 case Builtin::BI__sync_fetch_and_or_2: 1408 case Builtin::BI__sync_fetch_and_or_4: 1409 case Builtin::BI__sync_fetch_and_or_8: 1410 case Builtin::BI__sync_fetch_and_or_16: 1411 BuiltinIndex = 2; 1412 break; 1413 1414 case Builtin::BI__sync_fetch_and_and: 1415 case Builtin::BI__sync_fetch_and_and_1: 1416 case Builtin::BI__sync_fetch_and_and_2: 1417 case Builtin::BI__sync_fetch_and_and_4: 1418 case Builtin::BI__sync_fetch_and_and_8: 1419 case Builtin::BI__sync_fetch_and_and_16: 1420 BuiltinIndex = 3; 1421 break; 1422 1423 case Builtin::BI__sync_fetch_and_xor: 1424 case Builtin::BI__sync_fetch_and_xor_1: 1425 case Builtin::BI__sync_fetch_and_xor_2: 1426 case Builtin::BI__sync_fetch_and_xor_4: 1427 case Builtin::BI__sync_fetch_and_xor_8: 1428 case Builtin::BI__sync_fetch_and_xor_16: 1429 BuiltinIndex = 4; 1430 break; 1431 1432 case Builtin::BI__sync_add_and_fetch: 1433 case Builtin::BI__sync_add_and_fetch_1: 1434 case Builtin::BI__sync_add_and_fetch_2: 1435 case Builtin::BI__sync_add_and_fetch_4: 1436 case Builtin::BI__sync_add_and_fetch_8: 1437 case Builtin::BI__sync_add_and_fetch_16: 1438 BuiltinIndex = 5; 1439 break; 1440 1441 case Builtin::BI__sync_sub_and_fetch: 1442 case Builtin::BI__sync_sub_and_fetch_1: 1443 case Builtin::BI__sync_sub_and_fetch_2: 1444 case Builtin::BI__sync_sub_and_fetch_4: 1445 case Builtin::BI__sync_sub_and_fetch_8: 1446 case Builtin::BI__sync_sub_and_fetch_16: 1447 BuiltinIndex = 6; 1448 break; 1449 1450 case Builtin::BI__sync_and_and_fetch: 1451 case Builtin::BI__sync_and_and_fetch_1: 1452 case Builtin::BI__sync_and_and_fetch_2: 1453 case Builtin::BI__sync_and_and_fetch_4: 1454 case Builtin::BI__sync_and_and_fetch_8: 1455 case Builtin::BI__sync_and_and_fetch_16: 1456 BuiltinIndex = 7; 1457 break; 1458 1459 case Builtin::BI__sync_or_and_fetch: 1460 case Builtin::BI__sync_or_and_fetch_1: 1461 case Builtin::BI__sync_or_and_fetch_2: 1462 case Builtin::BI__sync_or_and_fetch_4: 1463 case Builtin::BI__sync_or_and_fetch_8: 1464 case Builtin::BI__sync_or_and_fetch_16: 1465 BuiltinIndex = 8; 1466 break; 1467 1468 case Builtin::BI__sync_xor_and_fetch: 1469 case Builtin::BI__sync_xor_and_fetch_1: 1470 case Builtin::BI__sync_xor_and_fetch_2: 1471 case Builtin::BI__sync_xor_and_fetch_4: 1472 case Builtin::BI__sync_xor_and_fetch_8: 1473 case Builtin::BI__sync_xor_and_fetch_16: 1474 BuiltinIndex = 9; 1475 break; 1476 1477 case Builtin::BI__sync_val_compare_and_swap: 1478 case Builtin::BI__sync_val_compare_and_swap_1: 1479 case Builtin::BI__sync_val_compare_and_swap_2: 1480 case Builtin::BI__sync_val_compare_and_swap_4: 1481 case Builtin::BI__sync_val_compare_and_swap_8: 1482 case Builtin::BI__sync_val_compare_and_swap_16: 1483 BuiltinIndex = 10; 1484 NumFixed = 2; 1485 break; 1486 1487 case Builtin::BI__sync_bool_compare_and_swap: 1488 case Builtin::BI__sync_bool_compare_and_swap_1: 1489 case Builtin::BI__sync_bool_compare_and_swap_2: 1490 case Builtin::BI__sync_bool_compare_and_swap_4: 1491 case Builtin::BI__sync_bool_compare_and_swap_8: 1492 case Builtin::BI__sync_bool_compare_and_swap_16: 1493 BuiltinIndex = 11; 1494 NumFixed = 2; 1495 ResultType = Context.BoolTy; 1496 break; 1497 1498 case Builtin::BI__sync_lock_test_and_set: 1499 case Builtin::BI__sync_lock_test_and_set_1: 1500 case Builtin::BI__sync_lock_test_and_set_2: 1501 case Builtin::BI__sync_lock_test_and_set_4: 1502 case Builtin::BI__sync_lock_test_and_set_8: 1503 case Builtin::BI__sync_lock_test_and_set_16: 1504 BuiltinIndex = 12; 1505 break; 1506 1507 case Builtin::BI__sync_lock_release: 1508 case Builtin::BI__sync_lock_release_1: 1509 case Builtin::BI__sync_lock_release_2: 1510 case Builtin::BI__sync_lock_release_4: 1511 case Builtin::BI__sync_lock_release_8: 1512 case Builtin::BI__sync_lock_release_16: 1513 BuiltinIndex = 13; 1514 NumFixed = 0; 1515 ResultType = Context.VoidTy; 1516 break; 1517 1518 case Builtin::BI__sync_swap: 1519 case Builtin::BI__sync_swap_1: 1520 case Builtin::BI__sync_swap_2: 1521 case Builtin::BI__sync_swap_4: 1522 case Builtin::BI__sync_swap_8: 1523 case Builtin::BI__sync_swap_16: 1524 BuiltinIndex = 14; 1525 break; 1526 } 1527 1528 // Now that we know how many fixed arguments we expect, first check that we 1529 // have at least that many. 1530 if (TheCall->getNumArgs() < 1+NumFixed) { 1531 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 1532 << 0 << 1+NumFixed << TheCall->getNumArgs() 1533 << TheCall->getCallee()->getSourceRange(); 1534 return ExprError(); 1535 } 1536 1537 // Get the decl for the concrete builtin from this, we can tell what the 1538 // concrete integer type we should convert to is. 1539 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 1540 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID); 1541 FunctionDecl *NewBuiltinDecl; 1542 if (NewBuiltinID == BuiltinID) 1543 NewBuiltinDecl = FDecl; 1544 else { 1545 // Perform builtin lookup to avoid redeclaring it. 1546 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 1547 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 1548 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 1549 assert(Res.getFoundDecl()); 1550 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 1551 if (NewBuiltinDecl == 0) 1552 return ExprError(); 1553 } 1554 1555 // The first argument --- the pointer --- has a fixed type; we 1556 // deduce the types of the rest of the arguments accordingly. Walk 1557 // the remaining arguments, converting them to the deduced value type. 1558 for (unsigned i = 0; i != NumFixed; ++i) { 1559 ExprResult Arg = TheCall->getArg(i+1); 1560 1561 // GCC does an implicit conversion to the pointer or integer ValType. This 1562 // can fail in some cases (1i -> int**), check for this error case now. 1563 // Initialize the argument. 1564 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 1565 ValType, /*consume*/ false); 1566 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 1567 if (Arg.isInvalid()) 1568 return ExprError(); 1569 1570 // Okay, we have something that *can* be converted to the right type. Check 1571 // to see if there is a potentially weird extension going on here. This can 1572 // happen when you do an atomic operation on something like an char* and 1573 // pass in 42. The 42 gets converted to char. This is even more strange 1574 // for things like 45.123 -> char, etc. 1575 // FIXME: Do this check. 1576 TheCall->setArg(i+1, Arg.take()); 1577 } 1578 1579 ASTContext& Context = this->getASTContext(); 1580 1581 // Create a new DeclRefExpr to refer to the new decl. 1582 DeclRefExpr* NewDRE = DeclRefExpr::Create( 1583 Context, 1584 DRE->getQualifierLoc(), 1585 SourceLocation(), 1586 NewBuiltinDecl, 1587 /*enclosing*/ false, 1588 DRE->getLocation(), 1589 Context.BuiltinFnTy, 1590 DRE->getValueKind()); 1591 1592 // Set the callee in the CallExpr. 1593 // FIXME: This loses syntactic information. 1594 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 1595 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 1596 CK_BuiltinFnToFnPtr); 1597 TheCall->setCallee(PromotedCall.take()); 1598 1599 // Change the result type of the call to match the original value type. This 1600 // is arbitrary, but the codegen for these builtins ins design to handle it 1601 // gracefully. 1602 TheCall->setType(ResultType); 1603 1604 return TheCallResult; 1605 } 1606 1607 /// CheckObjCString - Checks that the argument to the builtin 1608 /// CFString constructor is correct 1609 /// Note: It might also make sense to do the UTF-16 conversion here (would 1610 /// simplify the backend). 1611 bool Sema::CheckObjCString(Expr *Arg) { 1612 Arg = Arg->IgnoreParenCasts(); 1613 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 1614 1615 if (!Literal || !Literal->isAscii()) { 1616 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 1617 << Arg->getSourceRange(); 1618 return true; 1619 } 1620 1621 if (Literal->containsNonAsciiOrNull()) { 1622 StringRef String = Literal->getString(); 1623 unsigned NumBytes = String.size(); 1624 SmallVector<UTF16, 128> ToBuf(NumBytes); 1625 const UTF8 *FromPtr = (const UTF8 *)String.data(); 1626 UTF16 *ToPtr = &ToBuf[0]; 1627 1628 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1629 &ToPtr, ToPtr + NumBytes, 1630 strictConversion); 1631 // Check for conversion failure. 1632 if (Result != conversionOK) 1633 Diag(Arg->getLocStart(), 1634 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 1635 } 1636 return false; 1637 } 1638 1639 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 1640 /// Emit an error and return true on failure, return false on success. 1641 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 1642 Expr *Fn = TheCall->getCallee(); 1643 if (TheCall->getNumArgs() > 2) { 1644 Diag(TheCall->getArg(2)->getLocStart(), 1645 diag::err_typecheck_call_too_many_args) 1646 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1647 << Fn->getSourceRange() 1648 << SourceRange(TheCall->getArg(2)->getLocStart(), 1649 (*(TheCall->arg_end()-1))->getLocEnd()); 1650 return true; 1651 } 1652 1653 if (TheCall->getNumArgs() < 2) { 1654 return Diag(TheCall->getLocEnd(), 1655 diag::err_typecheck_call_too_few_args_at_least) 1656 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 1657 } 1658 1659 // Type-check the first argument normally. 1660 if (checkBuiltinArgument(*this, TheCall, 0)) 1661 return true; 1662 1663 // Determine whether the current function is variadic or not. 1664 BlockScopeInfo *CurBlock = getCurBlock(); 1665 bool isVariadic; 1666 if (CurBlock) 1667 isVariadic = CurBlock->TheDecl->isVariadic(); 1668 else if (FunctionDecl *FD = getCurFunctionDecl()) 1669 isVariadic = FD->isVariadic(); 1670 else 1671 isVariadic = getCurMethodDecl()->isVariadic(); 1672 1673 if (!isVariadic) { 1674 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 1675 return true; 1676 } 1677 1678 // Verify that the second argument to the builtin is the last argument of the 1679 // current function or method. 1680 bool SecondArgIsLastNamedArgument = false; 1681 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 1682 1683 // These are valid if SecondArgIsLastNamedArgument is false after the next 1684 // block. 1685 QualType Type; 1686 SourceLocation ParamLoc; 1687 1688 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 1689 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 1690 // FIXME: This isn't correct for methods (results in bogus warning). 1691 // Get the last formal in the current function. 1692 const ParmVarDecl *LastArg; 1693 if (CurBlock) 1694 LastArg = *(CurBlock->TheDecl->param_end()-1); 1695 else if (FunctionDecl *FD = getCurFunctionDecl()) 1696 LastArg = *(FD->param_end()-1); 1697 else 1698 LastArg = *(getCurMethodDecl()->param_end()-1); 1699 SecondArgIsLastNamedArgument = PV == LastArg; 1700 1701 Type = PV->getType(); 1702 ParamLoc = PV->getLocation(); 1703 } 1704 } 1705 1706 if (!SecondArgIsLastNamedArgument) 1707 Diag(TheCall->getArg(1)->getLocStart(), 1708 diag::warn_second_parameter_of_va_start_not_last_named_argument); 1709 else if (Type->isReferenceType()) { 1710 Diag(Arg->getLocStart(), 1711 diag::warn_va_start_of_reference_type_is_undefined); 1712 Diag(ParamLoc, diag::note_parameter_type) << Type; 1713 } 1714 1715 TheCall->setType(Context.VoidTy); 1716 return false; 1717 } 1718 1719 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 1720 /// friends. This is declared to take (...), so we have to check everything. 1721 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 1722 if (TheCall->getNumArgs() < 2) 1723 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1724 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 1725 if (TheCall->getNumArgs() > 2) 1726 return Diag(TheCall->getArg(2)->getLocStart(), 1727 diag::err_typecheck_call_too_many_args) 1728 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1729 << SourceRange(TheCall->getArg(2)->getLocStart(), 1730 (*(TheCall->arg_end()-1))->getLocEnd()); 1731 1732 ExprResult OrigArg0 = TheCall->getArg(0); 1733 ExprResult OrigArg1 = TheCall->getArg(1); 1734 1735 // Do standard promotions between the two arguments, returning their common 1736 // type. 1737 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 1738 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 1739 return true; 1740 1741 // Make sure any conversions are pushed back into the call; this is 1742 // type safe since unordered compare builtins are declared as "_Bool 1743 // foo(...)". 1744 TheCall->setArg(0, OrigArg0.get()); 1745 TheCall->setArg(1, OrigArg1.get()); 1746 1747 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 1748 return false; 1749 1750 // If the common type isn't a real floating type, then the arguments were 1751 // invalid for this operation. 1752 if (Res.isNull() || !Res->isRealFloatingType()) 1753 return Diag(OrigArg0.get()->getLocStart(), 1754 diag::err_typecheck_call_invalid_ordered_compare) 1755 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 1756 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 1757 1758 return false; 1759 } 1760 1761 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 1762 /// __builtin_isnan and friends. This is declared to take (...), so we have 1763 /// to check everything. We expect the last argument to be a floating point 1764 /// value. 1765 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 1766 if (TheCall->getNumArgs() < NumArgs) 1767 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1768 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 1769 if (TheCall->getNumArgs() > NumArgs) 1770 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 1771 diag::err_typecheck_call_too_many_args) 1772 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 1773 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 1774 (*(TheCall->arg_end()-1))->getLocEnd()); 1775 1776 Expr *OrigArg = TheCall->getArg(NumArgs-1); 1777 1778 if (OrigArg->isTypeDependent()) 1779 return false; 1780 1781 // This operation requires a non-_Complex floating-point number. 1782 if (!OrigArg->getType()->isRealFloatingType()) 1783 return Diag(OrigArg->getLocStart(), 1784 diag::err_typecheck_call_invalid_unary_fp) 1785 << OrigArg->getType() << OrigArg->getSourceRange(); 1786 1787 // If this is an implicit conversion from float -> double, remove it. 1788 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 1789 Expr *CastArg = Cast->getSubExpr(); 1790 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 1791 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 1792 "promotion from float to double is the only expected cast here"); 1793 Cast->setSubExpr(0); 1794 TheCall->setArg(NumArgs-1, CastArg); 1795 } 1796 } 1797 1798 return false; 1799 } 1800 1801 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 1802 // This is declared to take (...), so we have to check everything. 1803 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 1804 if (TheCall->getNumArgs() < 2) 1805 return ExprError(Diag(TheCall->getLocEnd(), 1806 diag::err_typecheck_call_too_few_args_at_least) 1807 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1808 << TheCall->getSourceRange()); 1809 1810 // Determine which of the following types of shufflevector we're checking: 1811 // 1) unary, vector mask: (lhs, mask) 1812 // 2) binary, vector mask: (lhs, rhs, mask) 1813 // 3) binary, scalar mask: (lhs, rhs, index, ..., index) 1814 QualType resType = TheCall->getArg(0)->getType(); 1815 unsigned numElements = 0; 1816 1817 if (!TheCall->getArg(0)->isTypeDependent() && 1818 !TheCall->getArg(1)->isTypeDependent()) { 1819 QualType LHSType = TheCall->getArg(0)->getType(); 1820 QualType RHSType = TheCall->getArg(1)->getType(); 1821 1822 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 1823 return ExprError(Diag(TheCall->getLocStart(), 1824 diag::err_shufflevector_non_vector) 1825 << SourceRange(TheCall->getArg(0)->getLocStart(), 1826 TheCall->getArg(1)->getLocEnd())); 1827 1828 numElements = LHSType->getAs<VectorType>()->getNumElements(); 1829 unsigned numResElements = TheCall->getNumArgs() - 2; 1830 1831 // Check to see if we have a call with 2 vector arguments, the unary shuffle 1832 // with mask. If so, verify that RHS is an integer vector type with the 1833 // same number of elts as lhs. 1834 if (TheCall->getNumArgs() == 2) { 1835 if (!RHSType->hasIntegerRepresentation() || 1836 RHSType->getAs<VectorType>()->getNumElements() != numElements) 1837 return ExprError(Diag(TheCall->getLocStart(), 1838 diag::err_shufflevector_incompatible_vector) 1839 << SourceRange(TheCall->getArg(1)->getLocStart(), 1840 TheCall->getArg(1)->getLocEnd())); 1841 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 1842 return ExprError(Diag(TheCall->getLocStart(), 1843 diag::err_shufflevector_incompatible_vector) 1844 << SourceRange(TheCall->getArg(0)->getLocStart(), 1845 TheCall->getArg(1)->getLocEnd())); 1846 } else if (numElements != numResElements) { 1847 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 1848 resType = Context.getVectorType(eltType, numResElements, 1849 VectorType::GenericVector); 1850 } 1851 } 1852 1853 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 1854 if (TheCall->getArg(i)->isTypeDependent() || 1855 TheCall->getArg(i)->isValueDependent()) 1856 continue; 1857 1858 llvm::APSInt Result(32); 1859 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 1860 return ExprError(Diag(TheCall->getLocStart(), 1861 diag::err_shufflevector_nonconstant_argument) 1862 << TheCall->getArg(i)->getSourceRange()); 1863 1864 // Allow -1 which will be translated to undef in the IR. 1865 if (Result.isSigned() && Result.isAllOnesValue()) 1866 continue; 1867 1868 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 1869 return ExprError(Diag(TheCall->getLocStart(), 1870 diag::err_shufflevector_argument_too_large) 1871 << TheCall->getArg(i)->getSourceRange()); 1872 } 1873 1874 SmallVector<Expr*, 32> exprs; 1875 1876 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 1877 exprs.push_back(TheCall->getArg(i)); 1878 TheCall->setArg(i, 0); 1879 } 1880 1881 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType, 1882 TheCall->getCallee()->getLocStart(), 1883 TheCall->getRParenLoc())); 1884 } 1885 1886 /// SemaConvertVectorExpr - Handle __builtin_convertvector 1887 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 1888 SourceLocation BuiltinLoc, 1889 SourceLocation RParenLoc) { 1890 ExprValueKind VK = VK_RValue; 1891 ExprObjectKind OK = OK_Ordinary; 1892 QualType DstTy = TInfo->getType(); 1893 QualType SrcTy = E->getType(); 1894 1895 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 1896 return ExprError(Diag(BuiltinLoc, 1897 diag::err_convertvector_non_vector) 1898 << E->getSourceRange()); 1899 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 1900 return ExprError(Diag(BuiltinLoc, 1901 diag::err_convertvector_non_vector_type)); 1902 1903 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 1904 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 1905 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 1906 if (SrcElts != DstElts) 1907 return ExprError(Diag(BuiltinLoc, 1908 diag::err_convertvector_incompatible_vector) 1909 << E->getSourceRange()); 1910 } 1911 1912 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK, 1913 BuiltinLoc, RParenLoc)); 1914 1915 } 1916 1917 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 1918 // This is declared to take (const void*, ...) and can take two 1919 // optional constant int args. 1920 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 1921 unsigned NumArgs = TheCall->getNumArgs(); 1922 1923 if (NumArgs > 3) 1924 return Diag(TheCall->getLocEnd(), 1925 diag::err_typecheck_call_too_many_args_at_most) 1926 << 0 /*function call*/ << 3 << NumArgs 1927 << TheCall->getSourceRange(); 1928 1929 // Argument 0 is checked for us and the remaining arguments must be 1930 // constant integers. 1931 for (unsigned i = 1; i != NumArgs; ++i) { 1932 Expr *Arg = TheCall->getArg(i); 1933 1934 // We can't check the value of a dependent argument. 1935 if (Arg->isTypeDependent() || Arg->isValueDependent()) 1936 continue; 1937 1938 llvm::APSInt Result; 1939 if (SemaBuiltinConstantArg(TheCall, i, Result)) 1940 return true; 1941 1942 // FIXME: gcc issues a warning and rewrites these to 0. These 1943 // seems especially odd for the third argument since the default 1944 // is 3. 1945 if (i == 1) { 1946 if (Result.getLimitedValue() > 1) 1947 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1948 << "0" << "1" << Arg->getSourceRange(); 1949 } else { 1950 if (Result.getLimitedValue() > 3) 1951 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1952 << "0" << "3" << Arg->getSourceRange(); 1953 } 1954 } 1955 1956 return false; 1957 } 1958 1959 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 1960 /// TheCall is a constant expression. 1961 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 1962 llvm::APSInt &Result) { 1963 Expr *Arg = TheCall->getArg(ArgNum); 1964 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1965 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 1966 1967 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 1968 1969 if (!Arg->isIntegerConstantExpr(Result, Context)) 1970 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 1971 << FDecl->getDeclName() << Arg->getSourceRange(); 1972 1973 return false; 1974 } 1975 1976 /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, 1977 /// int type). This simply type checks that type is one of the defined 1978 /// constants (0-3). 1979 // For compatibility check 0-3, llvm only handles 0 and 2. 1980 bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { 1981 llvm::APSInt Result; 1982 1983 // We can't check the value of a dependent argument. 1984 if (TheCall->getArg(1)->isTypeDependent() || 1985 TheCall->getArg(1)->isValueDependent()) 1986 return false; 1987 1988 // Check constant-ness first. 1989 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 1990 return true; 1991 1992 Expr *Arg = TheCall->getArg(1); 1993 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { 1994 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1995 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 1996 } 1997 1998 return false; 1999 } 2000 2001 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 2002 /// This checks that val is a constant 1. 2003 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 2004 Expr *Arg = TheCall->getArg(1); 2005 llvm::APSInt Result; 2006 2007 // TODO: This is less than ideal. Overload this to take a value. 2008 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 2009 return true; 2010 2011 if (Result != 1) 2012 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 2013 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 2014 2015 return false; 2016 } 2017 2018 namespace { 2019 enum StringLiteralCheckType { 2020 SLCT_NotALiteral, 2021 SLCT_UncheckedLiteral, 2022 SLCT_CheckedLiteral 2023 }; 2024 } 2025 2026 // Determine if an expression is a string literal or constant string. 2027 // If this function returns false on the arguments to a function expecting a 2028 // format string, we will usually need to emit a warning. 2029 // True string literals are then checked by CheckFormatString. 2030 static StringLiteralCheckType 2031 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 2032 bool HasVAListArg, unsigned format_idx, 2033 unsigned firstDataArg, Sema::FormatStringType Type, 2034 Sema::VariadicCallType CallType, bool InFunctionCall, 2035 llvm::SmallBitVector &CheckedVarArgs) { 2036 tryAgain: 2037 if (E->isTypeDependent() || E->isValueDependent()) 2038 return SLCT_NotALiteral; 2039 2040 E = E->IgnoreParenCasts(); 2041 2042 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 2043 // Technically -Wformat-nonliteral does not warn about this case. 2044 // The behavior of printf and friends in this case is implementation 2045 // dependent. Ideally if the format string cannot be null then 2046 // it should have a 'nonnull' attribute in the function prototype. 2047 return SLCT_UncheckedLiteral; 2048 2049 switch (E->getStmtClass()) { 2050 case Stmt::BinaryConditionalOperatorClass: 2051 case Stmt::ConditionalOperatorClass: { 2052 // The expression is a literal if both sub-expressions were, and it was 2053 // completely checked only if both sub-expressions were checked. 2054 const AbstractConditionalOperator *C = 2055 cast<AbstractConditionalOperator>(E); 2056 StringLiteralCheckType Left = 2057 checkFormatStringExpr(S, C->getTrueExpr(), Args, 2058 HasVAListArg, format_idx, firstDataArg, 2059 Type, CallType, InFunctionCall, CheckedVarArgs); 2060 if (Left == SLCT_NotALiteral) 2061 return SLCT_NotALiteral; 2062 StringLiteralCheckType Right = 2063 checkFormatStringExpr(S, C->getFalseExpr(), Args, 2064 HasVAListArg, format_idx, firstDataArg, 2065 Type, CallType, InFunctionCall, CheckedVarArgs); 2066 return Left < Right ? Left : Right; 2067 } 2068 2069 case Stmt::ImplicitCastExprClass: { 2070 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 2071 goto tryAgain; 2072 } 2073 2074 case Stmt::OpaqueValueExprClass: 2075 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 2076 E = src; 2077 goto tryAgain; 2078 } 2079 return SLCT_NotALiteral; 2080 2081 case Stmt::PredefinedExprClass: 2082 // While __func__, etc., are technically not string literals, they 2083 // cannot contain format specifiers and thus are not a security 2084 // liability. 2085 return SLCT_UncheckedLiteral; 2086 2087 case Stmt::DeclRefExprClass: { 2088 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 2089 2090 // As an exception, do not flag errors for variables binding to 2091 // const string literals. 2092 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 2093 bool isConstant = false; 2094 QualType T = DR->getType(); 2095 2096 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 2097 isConstant = AT->getElementType().isConstant(S.Context); 2098 } else if (const PointerType *PT = T->getAs<PointerType>()) { 2099 isConstant = T.isConstant(S.Context) && 2100 PT->getPointeeType().isConstant(S.Context); 2101 } else if (T->isObjCObjectPointerType()) { 2102 // In ObjC, there is usually no "const ObjectPointer" type, 2103 // so don't check if the pointee type is constant. 2104 isConstant = T.isConstant(S.Context); 2105 } 2106 2107 if (isConstant) { 2108 if (const Expr *Init = VD->getAnyInitializer()) { 2109 // Look through initializers like const char c[] = { "foo" } 2110 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2111 if (InitList->isStringLiteralInit()) 2112 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 2113 } 2114 return checkFormatStringExpr(S, Init, Args, 2115 HasVAListArg, format_idx, 2116 firstDataArg, Type, CallType, 2117 /*InFunctionCall*/false, CheckedVarArgs); 2118 } 2119 } 2120 2121 // For vprintf* functions (i.e., HasVAListArg==true), we add a 2122 // special check to see if the format string is a function parameter 2123 // of the function calling the printf function. If the function 2124 // has an attribute indicating it is a printf-like function, then we 2125 // should suppress warnings concerning non-literals being used in a call 2126 // to a vprintf function. For example: 2127 // 2128 // void 2129 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 2130 // va_list ap; 2131 // va_start(ap, fmt); 2132 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 2133 // ... 2134 // } 2135 if (HasVAListArg) { 2136 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 2137 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 2138 int PVIndex = PV->getFunctionScopeIndex() + 1; 2139 for (specific_attr_iterator<FormatAttr> 2140 i = ND->specific_attr_begin<FormatAttr>(), 2141 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) { 2142 FormatAttr *PVFormat = *i; 2143 // adjust for implicit parameter 2144 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 2145 if (MD->isInstance()) 2146 ++PVIndex; 2147 // We also check if the formats are compatible. 2148 // We can't pass a 'scanf' string to a 'printf' function. 2149 if (PVIndex == PVFormat->getFormatIdx() && 2150 Type == S.GetFormatStringType(PVFormat)) 2151 return SLCT_UncheckedLiteral; 2152 } 2153 } 2154 } 2155 } 2156 } 2157 2158 return SLCT_NotALiteral; 2159 } 2160 2161 case Stmt::CallExprClass: 2162 case Stmt::CXXMemberCallExprClass: { 2163 const CallExpr *CE = cast<CallExpr>(E); 2164 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 2165 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 2166 unsigned ArgIndex = FA->getFormatIdx(); 2167 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 2168 if (MD->isInstance()) 2169 --ArgIndex; 2170 const Expr *Arg = CE->getArg(ArgIndex - 1); 2171 2172 return checkFormatStringExpr(S, Arg, Args, 2173 HasVAListArg, format_idx, firstDataArg, 2174 Type, CallType, InFunctionCall, 2175 CheckedVarArgs); 2176 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 2177 unsigned BuiltinID = FD->getBuiltinID(); 2178 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 2179 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 2180 const Expr *Arg = CE->getArg(0); 2181 return checkFormatStringExpr(S, Arg, Args, 2182 HasVAListArg, format_idx, 2183 firstDataArg, Type, CallType, 2184 InFunctionCall, CheckedVarArgs); 2185 } 2186 } 2187 } 2188 2189 return SLCT_NotALiteral; 2190 } 2191 case Stmt::ObjCStringLiteralClass: 2192 case Stmt::StringLiteralClass: { 2193 const StringLiteral *StrE = NULL; 2194 2195 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 2196 StrE = ObjCFExpr->getString(); 2197 else 2198 StrE = cast<StringLiteral>(E); 2199 2200 if (StrE) { 2201 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg, 2202 Type, InFunctionCall, CallType, CheckedVarArgs); 2203 return SLCT_CheckedLiteral; 2204 } 2205 2206 return SLCT_NotALiteral; 2207 } 2208 2209 default: 2210 return SLCT_NotALiteral; 2211 } 2212 } 2213 2214 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 2215 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 2216 .Case("scanf", FST_Scanf) 2217 .Cases("printf", "printf0", FST_Printf) 2218 .Cases("NSString", "CFString", FST_NSString) 2219 .Case("strftime", FST_Strftime) 2220 .Case("strfmon", FST_Strfmon) 2221 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 2222 .Default(FST_Unknown); 2223 } 2224 2225 /// CheckFormatArguments - Check calls to printf and scanf (and similar 2226 /// functions) for correct use of format strings. 2227 /// Returns true if a format string has been fully checked. 2228 bool Sema::CheckFormatArguments(const FormatAttr *Format, 2229 ArrayRef<const Expr *> Args, 2230 bool IsCXXMember, 2231 VariadicCallType CallType, 2232 SourceLocation Loc, SourceRange Range, 2233 llvm::SmallBitVector &CheckedVarArgs) { 2234 FormatStringInfo FSI; 2235 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 2236 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 2237 FSI.FirstDataArg, GetFormatStringType(Format), 2238 CallType, Loc, Range, CheckedVarArgs); 2239 return false; 2240 } 2241 2242 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 2243 bool HasVAListArg, unsigned format_idx, 2244 unsigned firstDataArg, FormatStringType Type, 2245 VariadicCallType CallType, 2246 SourceLocation Loc, SourceRange Range, 2247 llvm::SmallBitVector &CheckedVarArgs) { 2248 // CHECK: printf/scanf-like function is called with no format string. 2249 if (format_idx >= Args.size()) { 2250 Diag(Loc, diag::warn_missing_format_string) << Range; 2251 return false; 2252 } 2253 2254 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 2255 2256 // CHECK: format string is not a string literal. 2257 // 2258 // Dynamically generated format strings are difficult to 2259 // automatically vet at compile time. Requiring that format strings 2260 // are string literals: (1) permits the checking of format strings by 2261 // the compiler and thereby (2) can practically remove the source of 2262 // many format string exploits. 2263 2264 // Format string can be either ObjC string (e.g. @"%d") or 2265 // C string (e.g. "%d") 2266 // ObjC string uses the same format specifiers as C string, so we can use 2267 // the same format string checking logic for both ObjC and C strings. 2268 StringLiteralCheckType CT = 2269 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 2270 format_idx, firstDataArg, Type, CallType, 2271 /*IsFunctionCall*/true, CheckedVarArgs); 2272 if (CT != SLCT_NotALiteral) 2273 // Literal format string found, check done! 2274 return CT == SLCT_CheckedLiteral; 2275 2276 // Strftime is particular as it always uses a single 'time' argument, 2277 // so it is safe to pass a non-literal string. 2278 if (Type == FST_Strftime) 2279 return false; 2280 2281 // Do not emit diag when the string param is a macro expansion and the 2282 // format is either NSString or CFString. This is a hack to prevent 2283 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 2284 // which are usually used in place of NS and CF string literals. 2285 if (Type == FST_NSString && 2286 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart())) 2287 return false; 2288 2289 // If there are no arguments specified, warn with -Wformat-security, otherwise 2290 // warn only with -Wformat-nonliteral. 2291 if (Args.size() == firstDataArg) 2292 Diag(Args[format_idx]->getLocStart(), 2293 diag::warn_format_nonliteral_noargs) 2294 << OrigFormatExpr->getSourceRange(); 2295 else 2296 Diag(Args[format_idx]->getLocStart(), 2297 diag::warn_format_nonliteral) 2298 << OrigFormatExpr->getSourceRange(); 2299 return false; 2300 } 2301 2302 namespace { 2303 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 2304 protected: 2305 Sema &S; 2306 const StringLiteral *FExpr; 2307 const Expr *OrigFormatExpr; 2308 const unsigned FirstDataArg; 2309 const unsigned NumDataArgs; 2310 const char *Beg; // Start of format string. 2311 const bool HasVAListArg; 2312 ArrayRef<const Expr *> Args; 2313 unsigned FormatIdx; 2314 llvm::SmallBitVector CoveredArgs; 2315 bool usesPositionalArgs; 2316 bool atFirstArg; 2317 bool inFunctionCall; 2318 Sema::VariadicCallType CallType; 2319 llvm::SmallBitVector &CheckedVarArgs; 2320 public: 2321 CheckFormatHandler(Sema &s, const StringLiteral *fexpr, 2322 const Expr *origFormatExpr, unsigned firstDataArg, 2323 unsigned numDataArgs, const char *beg, bool hasVAListArg, 2324 ArrayRef<const Expr *> Args, 2325 unsigned formatIdx, bool inFunctionCall, 2326 Sema::VariadicCallType callType, 2327 llvm::SmallBitVector &CheckedVarArgs) 2328 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 2329 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), 2330 Beg(beg), HasVAListArg(hasVAListArg), 2331 Args(Args), FormatIdx(formatIdx), 2332 usesPositionalArgs(false), atFirstArg(true), 2333 inFunctionCall(inFunctionCall), CallType(callType), 2334 CheckedVarArgs(CheckedVarArgs) { 2335 CoveredArgs.resize(numDataArgs); 2336 CoveredArgs.reset(); 2337 } 2338 2339 void DoneProcessing(); 2340 2341 void HandleIncompleteSpecifier(const char *startSpecifier, 2342 unsigned specifierLen); 2343 2344 void HandleInvalidLengthModifier( 2345 const analyze_format_string::FormatSpecifier &FS, 2346 const analyze_format_string::ConversionSpecifier &CS, 2347 const char *startSpecifier, unsigned specifierLen, unsigned DiagID); 2348 2349 void HandleNonStandardLengthModifier( 2350 const analyze_format_string::FormatSpecifier &FS, 2351 const char *startSpecifier, unsigned specifierLen); 2352 2353 void HandleNonStandardConversionSpecifier( 2354 const analyze_format_string::ConversionSpecifier &CS, 2355 const char *startSpecifier, unsigned specifierLen); 2356 2357 virtual void HandlePosition(const char *startPos, unsigned posLen); 2358 2359 virtual void HandleInvalidPosition(const char *startSpecifier, 2360 unsigned specifierLen, 2361 analyze_format_string::PositionContext p); 2362 2363 virtual void HandleZeroPosition(const char *startPos, unsigned posLen); 2364 2365 void HandleNullChar(const char *nullCharacter); 2366 2367 template <typename Range> 2368 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall, 2369 const Expr *ArgumentExpr, 2370 PartialDiagnostic PDiag, 2371 SourceLocation StringLoc, 2372 bool IsStringLocation, Range StringRange, 2373 ArrayRef<FixItHint> Fixit = None); 2374 2375 protected: 2376 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 2377 const char *startSpec, 2378 unsigned specifierLen, 2379 const char *csStart, unsigned csLen); 2380 2381 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 2382 const char *startSpec, 2383 unsigned specifierLen); 2384 2385 SourceRange getFormatStringRange(); 2386 CharSourceRange getSpecifierRange(const char *startSpecifier, 2387 unsigned specifierLen); 2388 SourceLocation getLocationOfByte(const char *x); 2389 2390 const Expr *getDataArg(unsigned i) const; 2391 2392 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 2393 const analyze_format_string::ConversionSpecifier &CS, 2394 const char *startSpecifier, unsigned specifierLen, 2395 unsigned argIndex); 2396 2397 template <typename Range> 2398 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 2399 bool IsStringLocation, Range StringRange, 2400 ArrayRef<FixItHint> Fixit = None); 2401 2402 void CheckPositionalAndNonpositionalArgs( 2403 const analyze_format_string::FormatSpecifier *FS); 2404 }; 2405 } 2406 2407 SourceRange CheckFormatHandler::getFormatStringRange() { 2408 return OrigFormatExpr->getSourceRange(); 2409 } 2410 2411 CharSourceRange CheckFormatHandler:: 2412 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 2413 SourceLocation Start = getLocationOfByte(startSpecifier); 2414 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 2415 2416 // Advance the end SourceLocation by one due to half-open ranges. 2417 End = End.getLocWithOffset(1); 2418 2419 return CharSourceRange::getCharRange(Start, End); 2420 } 2421 2422 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 2423 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 2424 } 2425 2426 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 2427 unsigned specifierLen){ 2428 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 2429 getLocationOfByte(startSpecifier), 2430 /*IsStringLocation*/true, 2431 getSpecifierRange(startSpecifier, specifierLen)); 2432 } 2433 2434 void CheckFormatHandler::HandleInvalidLengthModifier( 2435 const analyze_format_string::FormatSpecifier &FS, 2436 const analyze_format_string::ConversionSpecifier &CS, 2437 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 2438 using namespace analyze_format_string; 2439 2440 const LengthModifier &LM = FS.getLengthModifier(); 2441 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 2442 2443 // See if we know how to fix this length modifier. 2444 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 2445 if (FixedLM) { 2446 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 2447 getLocationOfByte(LM.getStart()), 2448 /*IsStringLocation*/true, 2449 getSpecifierRange(startSpecifier, specifierLen)); 2450 2451 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 2452 << FixedLM->toString() 2453 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 2454 2455 } else { 2456 FixItHint Hint; 2457 if (DiagID == diag::warn_format_nonsensical_length) 2458 Hint = FixItHint::CreateRemoval(LMRange); 2459 2460 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 2461 getLocationOfByte(LM.getStart()), 2462 /*IsStringLocation*/true, 2463 getSpecifierRange(startSpecifier, specifierLen), 2464 Hint); 2465 } 2466 } 2467 2468 void CheckFormatHandler::HandleNonStandardLengthModifier( 2469 const analyze_format_string::FormatSpecifier &FS, 2470 const char *startSpecifier, unsigned specifierLen) { 2471 using namespace analyze_format_string; 2472 2473 const LengthModifier &LM = FS.getLengthModifier(); 2474 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 2475 2476 // See if we know how to fix this length modifier. 2477 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 2478 if (FixedLM) { 2479 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2480 << LM.toString() << 0, 2481 getLocationOfByte(LM.getStart()), 2482 /*IsStringLocation*/true, 2483 getSpecifierRange(startSpecifier, specifierLen)); 2484 2485 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 2486 << FixedLM->toString() 2487 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 2488 2489 } else { 2490 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2491 << LM.toString() << 0, 2492 getLocationOfByte(LM.getStart()), 2493 /*IsStringLocation*/true, 2494 getSpecifierRange(startSpecifier, specifierLen)); 2495 } 2496 } 2497 2498 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 2499 const analyze_format_string::ConversionSpecifier &CS, 2500 const char *startSpecifier, unsigned specifierLen) { 2501 using namespace analyze_format_string; 2502 2503 // See if we know how to fix this conversion specifier. 2504 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 2505 if (FixedCS) { 2506 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2507 << CS.toString() << /*conversion specifier*/1, 2508 getLocationOfByte(CS.getStart()), 2509 /*IsStringLocation*/true, 2510 getSpecifierRange(startSpecifier, specifierLen)); 2511 2512 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 2513 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 2514 << FixedCS->toString() 2515 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 2516 } else { 2517 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2518 << CS.toString() << /*conversion specifier*/1, 2519 getLocationOfByte(CS.getStart()), 2520 /*IsStringLocation*/true, 2521 getSpecifierRange(startSpecifier, specifierLen)); 2522 } 2523 } 2524 2525 void CheckFormatHandler::HandlePosition(const char *startPos, 2526 unsigned posLen) { 2527 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 2528 getLocationOfByte(startPos), 2529 /*IsStringLocation*/true, 2530 getSpecifierRange(startPos, posLen)); 2531 } 2532 2533 void 2534 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 2535 analyze_format_string::PositionContext p) { 2536 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 2537 << (unsigned) p, 2538 getLocationOfByte(startPos), /*IsStringLocation*/true, 2539 getSpecifierRange(startPos, posLen)); 2540 } 2541 2542 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 2543 unsigned posLen) { 2544 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 2545 getLocationOfByte(startPos), 2546 /*IsStringLocation*/true, 2547 getSpecifierRange(startPos, posLen)); 2548 } 2549 2550 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 2551 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 2552 // The presence of a null character is likely an error. 2553 EmitFormatDiagnostic( 2554 S.PDiag(diag::warn_printf_format_string_contains_null_char), 2555 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 2556 getFormatStringRange()); 2557 } 2558 } 2559 2560 // Note that this may return NULL if there was an error parsing or building 2561 // one of the argument expressions. 2562 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 2563 return Args[FirstDataArg + i]; 2564 } 2565 2566 void CheckFormatHandler::DoneProcessing() { 2567 // Does the number of data arguments exceed the number of 2568 // format conversions in the format string? 2569 if (!HasVAListArg) { 2570 // Find any arguments that weren't covered. 2571 CoveredArgs.flip(); 2572 signed notCoveredArg = CoveredArgs.find_first(); 2573 if (notCoveredArg >= 0) { 2574 assert((unsigned)notCoveredArg < NumDataArgs); 2575 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) { 2576 SourceLocation Loc = E->getLocStart(); 2577 if (!S.getSourceManager().isInSystemMacro(Loc)) { 2578 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used), 2579 Loc, /*IsStringLocation*/false, 2580 getFormatStringRange()); 2581 } 2582 } 2583 } 2584 } 2585 } 2586 2587 bool 2588 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 2589 SourceLocation Loc, 2590 const char *startSpec, 2591 unsigned specifierLen, 2592 const char *csStart, 2593 unsigned csLen) { 2594 2595 bool keepGoing = true; 2596 if (argIndex < NumDataArgs) { 2597 // Consider the argument coverered, even though the specifier doesn't 2598 // make sense. 2599 CoveredArgs.set(argIndex); 2600 } 2601 else { 2602 // If argIndex exceeds the number of data arguments we 2603 // don't issue a warning because that is just a cascade of warnings (and 2604 // they may have intended '%%' anyway). We don't want to continue processing 2605 // the format string after this point, however, as we will like just get 2606 // gibberish when trying to match arguments. 2607 keepGoing = false; 2608 } 2609 2610 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion) 2611 << StringRef(csStart, csLen), 2612 Loc, /*IsStringLocation*/true, 2613 getSpecifierRange(startSpec, specifierLen)); 2614 2615 return keepGoing; 2616 } 2617 2618 void 2619 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 2620 const char *startSpec, 2621 unsigned specifierLen) { 2622 EmitFormatDiagnostic( 2623 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 2624 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 2625 } 2626 2627 bool 2628 CheckFormatHandler::CheckNumArgs( 2629 const analyze_format_string::FormatSpecifier &FS, 2630 const analyze_format_string::ConversionSpecifier &CS, 2631 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 2632 2633 if (argIndex >= NumDataArgs) { 2634 PartialDiagnostic PDiag = FS.usesPositionalArg() 2635 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 2636 << (argIndex+1) << NumDataArgs) 2637 : S.PDiag(diag::warn_printf_insufficient_data_args); 2638 EmitFormatDiagnostic( 2639 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 2640 getSpecifierRange(startSpecifier, specifierLen)); 2641 return false; 2642 } 2643 return true; 2644 } 2645 2646 template<typename Range> 2647 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 2648 SourceLocation Loc, 2649 bool IsStringLocation, 2650 Range StringRange, 2651 ArrayRef<FixItHint> FixIt) { 2652 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 2653 Loc, IsStringLocation, StringRange, FixIt); 2654 } 2655 2656 /// \brief If the format string is not within the funcion call, emit a note 2657 /// so that the function call and string are in diagnostic messages. 2658 /// 2659 /// \param InFunctionCall if true, the format string is within the function 2660 /// call and only one diagnostic message will be produced. Otherwise, an 2661 /// extra note will be emitted pointing to location of the format string. 2662 /// 2663 /// \param ArgumentExpr the expression that is passed as the format string 2664 /// argument in the function call. Used for getting locations when two 2665 /// diagnostics are emitted. 2666 /// 2667 /// \param PDiag the callee should already have provided any strings for the 2668 /// diagnostic message. This function only adds locations and fixits 2669 /// to diagnostics. 2670 /// 2671 /// \param Loc primary location for diagnostic. If two diagnostics are 2672 /// required, one will be at Loc and a new SourceLocation will be created for 2673 /// the other one. 2674 /// 2675 /// \param IsStringLocation if true, Loc points to the format string should be 2676 /// used for the note. Otherwise, Loc points to the argument list and will 2677 /// be used with PDiag. 2678 /// 2679 /// \param StringRange some or all of the string to highlight. This is 2680 /// templated so it can accept either a CharSourceRange or a SourceRange. 2681 /// 2682 /// \param FixIt optional fix it hint for the format string. 2683 template<typename Range> 2684 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall, 2685 const Expr *ArgumentExpr, 2686 PartialDiagnostic PDiag, 2687 SourceLocation Loc, 2688 bool IsStringLocation, 2689 Range StringRange, 2690 ArrayRef<FixItHint> FixIt) { 2691 if (InFunctionCall) { 2692 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 2693 D << StringRange; 2694 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end(); 2695 I != E; ++I) { 2696 D << *I; 2697 } 2698 } else { 2699 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 2700 << ArgumentExpr->getSourceRange(); 2701 2702 const Sema::SemaDiagnosticBuilder &Note = 2703 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 2704 diag::note_format_string_defined); 2705 2706 Note << StringRange; 2707 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end(); 2708 I != E; ++I) { 2709 Note << *I; 2710 } 2711 } 2712 } 2713 2714 //===--- CHECK: Printf format string checking ------------------------------===// 2715 2716 namespace { 2717 class CheckPrintfHandler : public CheckFormatHandler { 2718 bool ObjCContext; 2719 public: 2720 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 2721 const Expr *origFormatExpr, unsigned firstDataArg, 2722 unsigned numDataArgs, bool isObjC, 2723 const char *beg, bool hasVAListArg, 2724 ArrayRef<const Expr *> Args, 2725 unsigned formatIdx, bool inFunctionCall, 2726 Sema::VariadicCallType CallType, 2727 llvm::SmallBitVector &CheckedVarArgs) 2728 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 2729 numDataArgs, beg, hasVAListArg, Args, 2730 formatIdx, inFunctionCall, CallType, CheckedVarArgs), 2731 ObjCContext(isObjC) 2732 {} 2733 2734 2735 bool HandleInvalidPrintfConversionSpecifier( 2736 const analyze_printf::PrintfSpecifier &FS, 2737 const char *startSpecifier, 2738 unsigned specifierLen); 2739 2740 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 2741 const char *startSpecifier, 2742 unsigned specifierLen); 2743 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 2744 const char *StartSpecifier, 2745 unsigned SpecifierLen, 2746 const Expr *E); 2747 2748 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 2749 const char *startSpecifier, unsigned specifierLen); 2750 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 2751 const analyze_printf::OptionalAmount &Amt, 2752 unsigned type, 2753 const char *startSpecifier, unsigned specifierLen); 2754 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 2755 const analyze_printf::OptionalFlag &flag, 2756 const char *startSpecifier, unsigned specifierLen); 2757 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 2758 const analyze_printf::OptionalFlag &ignoredFlag, 2759 const analyze_printf::OptionalFlag &flag, 2760 const char *startSpecifier, unsigned specifierLen); 2761 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 2762 const Expr *E, const CharSourceRange &CSR); 2763 2764 }; 2765 } 2766 2767 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 2768 const analyze_printf::PrintfSpecifier &FS, 2769 const char *startSpecifier, 2770 unsigned specifierLen) { 2771 const analyze_printf::PrintfConversionSpecifier &CS = 2772 FS.getConversionSpecifier(); 2773 2774 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 2775 getLocationOfByte(CS.getStart()), 2776 startSpecifier, specifierLen, 2777 CS.getStart(), CS.getLength()); 2778 } 2779 2780 bool CheckPrintfHandler::HandleAmount( 2781 const analyze_format_string::OptionalAmount &Amt, 2782 unsigned k, const char *startSpecifier, 2783 unsigned specifierLen) { 2784 2785 if (Amt.hasDataArgument()) { 2786 if (!HasVAListArg) { 2787 unsigned argIndex = Amt.getArgIndex(); 2788 if (argIndex >= NumDataArgs) { 2789 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 2790 << k, 2791 getLocationOfByte(Amt.getStart()), 2792 /*IsStringLocation*/true, 2793 getSpecifierRange(startSpecifier, specifierLen)); 2794 // Don't do any more checking. We will just emit 2795 // spurious errors. 2796 return false; 2797 } 2798 2799 // Type check the data argument. It should be an 'int'. 2800 // Although not in conformance with C99, we also allow the argument to be 2801 // an 'unsigned int' as that is a reasonably safe case. GCC also 2802 // doesn't emit a warning for that case. 2803 CoveredArgs.set(argIndex); 2804 const Expr *Arg = getDataArg(argIndex); 2805 if (!Arg) 2806 return false; 2807 2808 QualType T = Arg->getType(); 2809 2810 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 2811 assert(AT.isValid()); 2812 2813 if (!AT.matchesType(S.Context, T)) { 2814 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 2815 << k << AT.getRepresentativeTypeName(S.Context) 2816 << T << Arg->getSourceRange(), 2817 getLocationOfByte(Amt.getStart()), 2818 /*IsStringLocation*/true, 2819 getSpecifierRange(startSpecifier, specifierLen)); 2820 // Don't do any more checking. We will just emit 2821 // spurious errors. 2822 return false; 2823 } 2824 } 2825 } 2826 return true; 2827 } 2828 2829 void CheckPrintfHandler::HandleInvalidAmount( 2830 const analyze_printf::PrintfSpecifier &FS, 2831 const analyze_printf::OptionalAmount &Amt, 2832 unsigned type, 2833 const char *startSpecifier, 2834 unsigned specifierLen) { 2835 const analyze_printf::PrintfConversionSpecifier &CS = 2836 FS.getConversionSpecifier(); 2837 2838 FixItHint fixit = 2839 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 2840 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 2841 Amt.getConstantLength())) 2842 : FixItHint(); 2843 2844 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 2845 << type << CS.toString(), 2846 getLocationOfByte(Amt.getStart()), 2847 /*IsStringLocation*/true, 2848 getSpecifierRange(startSpecifier, specifierLen), 2849 fixit); 2850 } 2851 2852 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 2853 const analyze_printf::OptionalFlag &flag, 2854 const char *startSpecifier, 2855 unsigned specifierLen) { 2856 // Warn about pointless flag with a fixit removal. 2857 const analyze_printf::PrintfConversionSpecifier &CS = 2858 FS.getConversionSpecifier(); 2859 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 2860 << flag.toString() << CS.toString(), 2861 getLocationOfByte(flag.getPosition()), 2862 /*IsStringLocation*/true, 2863 getSpecifierRange(startSpecifier, specifierLen), 2864 FixItHint::CreateRemoval( 2865 getSpecifierRange(flag.getPosition(), 1))); 2866 } 2867 2868 void CheckPrintfHandler::HandleIgnoredFlag( 2869 const analyze_printf::PrintfSpecifier &FS, 2870 const analyze_printf::OptionalFlag &ignoredFlag, 2871 const analyze_printf::OptionalFlag &flag, 2872 const char *startSpecifier, 2873 unsigned specifierLen) { 2874 // Warn about ignored flag with a fixit removal. 2875 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 2876 << ignoredFlag.toString() << flag.toString(), 2877 getLocationOfByte(ignoredFlag.getPosition()), 2878 /*IsStringLocation*/true, 2879 getSpecifierRange(startSpecifier, specifierLen), 2880 FixItHint::CreateRemoval( 2881 getSpecifierRange(ignoredFlag.getPosition(), 1))); 2882 } 2883 2884 // Determines if the specified is a C++ class or struct containing 2885 // a member with the specified name and kind (e.g. a CXXMethodDecl named 2886 // "c_str()"). 2887 template<typename MemberKind> 2888 static llvm::SmallPtrSet<MemberKind*, 1> 2889 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 2890 const RecordType *RT = Ty->getAs<RecordType>(); 2891 llvm::SmallPtrSet<MemberKind*, 1> Results; 2892 2893 if (!RT) 2894 return Results; 2895 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 2896 if (!RD) 2897 return Results; 2898 2899 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(), 2900 Sema::LookupMemberName); 2901 2902 // We just need to include all members of the right kind turned up by the 2903 // filter, at this point. 2904 if (S.LookupQualifiedName(R, RT->getDecl())) 2905 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2906 NamedDecl *decl = (*I)->getUnderlyingDecl(); 2907 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 2908 Results.insert(FK); 2909 } 2910 return Results; 2911 } 2912 2913 // Check if a (w)string was passed when a (w)char* was needed, and offer a 2914 // better diagnostic if so. AT is assumed to be valid. 2915 // Returns true when a c_str() conversion method is found. 2916 bool CheckPrintfHandler::checkForCStrMembers( 2917 const analyze_printf::ArgType &AT, const Expr *E, 2918 const CharSourceRange &CSR) { 2919 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 2920 2921 MethodSet Results = 2922 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 2923 2924 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 2925 MI != ME; ++MI) { 2926 const CXXMethodDecl *Method = *MI; 2927 if (Method->getNumParams() == 0 && 2928 AT.matchesType(S.Context, Method->getReturnType())) { 2929 // FIXME: Suggest parens if the expression needs them. 2930 SourceLocation EndLoc = 2931 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()); 2932 S.Diag(E->getLocStart(), diag::note_printf_c_str) 2933 << "c_str()" 2934 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 2935 return true; 2936 } 2937 } 2938 2939 return false; 2940 } 2941 2942 bool 2943 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 2944 &FS, 2945 const char *startSpecifier, 2946 unsigned specifierLen) { 2947 2948 using namespace analyze_format_string; 2949 using namespace analyze_printf; 2950 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 2951 2952 if (FS.consumesDataArgument()) { 2953 if (atFirstArg) { 2954 atFirstArg = false; 2955 usesPositionalArgs = FS.usesPositionalArg(); 2956 } 2957 else if (usesPositionalArgs != FS.usesPositionalArg()) { 2958 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 2959 startSpecifier, specifierLen); 2960 return false; 2961 } 2962 } 2963 2964 // First check if the field width, precision, and conversion specifier 2965 // have matching data arguments. 2966 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 2967 startSpecifier, specifierLen)) { 2968 return false; 2969 } 2970 2971 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 2972 startSpecifier, specifierLen)) { 2973 return false; 2974 } 2975 2976 if (!CS.consumesDataArgument()) { 2977 // FIXME: Technically specifying a precision or field width here 2978 // makes no sense. Worth issuing a warning at some point. 2979 return true; 2980 } 2981 2982 // Consume the argument. 2983 unsigned argIndex = FS.getArgIndex(); 2984 if (argIndex < NumDataArgs) { 2985 // The check to see if the argIndex is valid will come later. 2986 // We set the bit here because we may exit early from this 2987 // function if we encounter some other error. 2988 CoveredArgs.set(argIndex); 2989 } 2990 2991 // Check for using an Objective-C specific conversion specifier 2992 // in a non-ObjC literal. 2993 if (!ObjCContext && CS.isObjCArg()) { 2994 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 2995 specifierLen); 2996 } 2997 2998 // Check for invalid use of field width 2999 if (!FS.hasValidFieldWidth()) { 3000 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 3001 startSpecifier, specifierLen); 3002 } 3003 3004 // Check for invalid use of precision 3005 if (!FS.hasValidPrecision()) { 3006 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 3007 startSpecifier, specifierLen); 3008 } 3009 3010 // Check each flag does not conflict with any other component. 3011 if (!FS.hasValidThousandsGroupingPrefix()) 3012 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 3013 if (!FS.hasValidLeadingZeros()) 3014 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 3015 if (!FS.hasValidPlusPrefix()) 3016 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 3017 if (!FS.hasValidSpacePrefix()) 3018 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 3019 if (!FS.hasValidAlternativeForm()) 3020 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 3021 if (!FS.hasValidLeftJustified()) 3022 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 3023 3024 // Check that flags are not ignored by another flag 3025 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 3026 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 3027 startSpecifier, specifierLen); 3028 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 3029 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 3030 startSpecifier, specifierLen); 3031 3032 // Check the length modifier is valid with the given conversion specifier. 3033 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 3034 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 3035 diag::warn_format_nonsensical_length); 3036 else if (!FS.hasStandardLengthModifier()) 3037 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 3038 else if (!FS.hasStandardLengthConversionCombination()) 3039 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 3040 diag::warn_format_non_standard_conversion_spec); 3041 3042 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 3043 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 3044 3045 // The remaining checks depend on the data arguments. 3046 if (HasVAListArg) 3047 return true; 3048 3049 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 3050 return false; 3051 3052 const Expr *Arg = getDataArg(argIndex); 3053 if (!Arg) 3054 return true; 3055 3056 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 3057 } 3058 3059 static bool requiresParensToAddCast(const Expr *E) { 3060 // FIXME: We should have a general way to reason about operator 3061 // precedence and whether parens are actually needed here. 3062 // Take care of a few common cases where they aren't. 3063 const Expr *Inside = E->IgnoreImpCasts(); 3064 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 3065 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 3066 3067 switch (Inside->getStmtClass()) { 3068 case Stmt::ArraySubscriptExprClass: 3069 case Stmt::CallExprClass: 3070 case Stmt::CharacterLiteralClass: 3071 case Stmt::CXXBoolLiteralExprClass: 3072 case Stmt::DeclRefExprClass: 3073 case Stmt::FloatingLiteralClass: 3074 case Stmt::IntegerLiteralClass: 3075 case Stmt::MemberExprClass: 3076 case Stmt::ObjCArrayLiteralClass: 3077 case Stmt::ObjCBoolLiteralExprClass: 3078 case Stmt::ObjCBoxedExprClass: 3079 case Stmt::ObjCDictionaryLiteralClass: 3080 case Stmt::ObjCEncodeExprClass: 3081 case Stmt::ObjCIvarRefExprClass: 3082 case Stmt::ObjCMessageExprClass: 3083 case Stmt::ObjCPropertyRefExprClass: 3084 case Stmt::ObjCStringLiteralClass: 3085 case Stmt::ObjCSubscriptRefExprClass: 3086 case Stmt::ParenExprClass: 3087 case Stmt::StringLiteralClass: 3088 case Stmt::UnaryOperatorClass: 3089 return false; 3090 default: 3091 return true; 3092 } 3093 } 3094 3095 bool 3096 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 3097 const char *StartSpecifier, 3098 unsigned SpecifierLen, 3099 const Expr *E) { 3100 using namespace analyze_format_string; 3101 using namespace analyze_printf; 3102 // Now type check the data expression that matches the 3103 // format specifier. 3104 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, 3105 ObjCContext); 3106 if (!AT.isValid()) 3107 return true; 3108 3109 QualType ExprTy = E->getType(); 3110 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 3111 ExprTy = TET->getUnderlyingExpr()->getType(); 3112 } 3113 3114 if (AT.matchesType(S.Context, ExprTy)) 3115 return true; 3116 3117 // Look through argument promotions for our error message's reported type. 3118 // This includes the integral and floating promotions, but excludes array 3119 // and function pointer decay; seeing that an argument intended to be a 3120 // string has type 'char [6]' is probably more confusing than 'char *'. 3121 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 3122 if (ICE->getCastKind() == CK_IntegralCast || 3123 ICE->getCastKind() == CK_FloatingCast) { 3124 E = ICE->getSubExpr(); 3125 ExprTy = E->getType(); 3126 3127 // Check if we didn't match because of an implicit cast from a 'char' 3128 // or 'short' to an 'int'. This is done because printf is a varargs 3129 // function. 3130 if (ICE->getType() == S.Context.IntTy || 3131 ICE->getType() == S.Context.UnsignedIntTy) { 3132 // All further checking is done on the subexpression. 3133 if (AT.matchesType(S.Context, ExprTy)) 3134 return true; 3135 } 3136 } 3137 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 3138 // Special case for 'a', which has type 'int' in C. 3139 // Note, however, that we do /not/ want to treat multibyte constants like 3140 // 'MooV' as characters! This form is deprecated but still exists. 3141 if (ExprTy == S.Context.IntTy) 3142 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 3143 ExprTy = S.Context.CharTy; 3144 } 3145 3146 // %C in an Objective-C context prints a unichar, not a wchar_t. 3147 // If the argument is an integer of some kind, believe the %C and suggest 3148 // a cast instead of changing the conversion specifier. 3149 QualType IntendedTy = ExprTy; 3150 if (ObjCContext && 3151 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 3152 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 3153 !ExprTy->isCharType()) { 3154 // 'unichar' is defined as a typedef of unsigned short, but we should 3155 // prefer using the typedef if it is visible. 3156 IntendedTy = S.Context.UnsignedShortTy; 3157 3158 // While we are here, check if the value is an IntegerLiteral that happens 3159 // to be within the valid range. 3160 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 3161 const llvm::APInt &V = IL->getValue(); 3162 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 3163 return true; 3164 } 3165 3166 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 3167 Sema::LookupOrdinaryName); 3168 if (S.LookupName(Result, S.getCurScope())) { 3169 NamedDecl *ND = Result.getFoundDecl(); 3170 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 3171 if (TD->getUnderlyingType() == IntendedTy) 3172 IntendedTy = S.Context.getTypedefType(TD); 3173 } 3174 } 3175 } 3176 3177 // Special-case some of Darwin's platform-independence types by suggesting 3178 // casts to primitive types that are known to be large enough. 3179 bool ShouldNotPrintDirectly = false; 3180 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 3181 // Use a 'while' to peel off layers of typedefs. 3182 QualType TyTy = IntendedTy; 3183 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 3184 StringRef Name = UserTy->getDecl()->getName(); 3185 QualType CastTy = llvm::StringSwitch<QualType>(Name) 3186 .Case("NSInteger", S.Context.LongTy) 3187 .Case("NSUInteger", S.Context.UnsignedLongTy) 3188 .Case("SInt32", S.Context.IntTy) 3189 .Case("UInt32", S.Context.UnsignedIntTy) 3190 .Default(QualType()); 3191 3192 if (!CastTy.isNull()) { 3193 ShouldNotPrintDirectly = true; 3194 IntendedTy = CastTy; 3195 break; 3196 } 3197 TyTy = UserTy->desugar(); 3198 } 3199 } 3200 3201 // We may be able to offer a FixItHint if it is a supported type. 3202 PrintfSpecifier fixedFS = FS; 3203 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(), 3204 S.Context, ObjCContext); 3205 3206 if (success) { 3207 // Get the fix string from the fixed format specifier 3208 SmallString<16> buf; 3209 llvm::raw_svector_ostream os(buf); 3210 fixedFS.toString(os); 3211 3212 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 3213 3214 if (IntendedTy == ExprTy) { 3215 // In this case, the specifier is wrong and should be changed to match 3216 // the argument. 3217 EmitFormatDiagnostic( 3218 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 3219 << AT.getRepresentativeTypeName(S.Context) << IntendedTy 3220 << E->getSourceRange(), 3221 E->getLocStart(), 3222 /*IsStringLocation*/false, 3223 SpecRange, 3224 FixItHint::CreateReplacement(SpecRange, os.str())); 3225 3226 } else { 3227 // The canonical type for formatting this value is different from the 3228 // actual type of the expression. (This occurs, for example, with Darwin's 3229 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 3230 // should be printed as 'long' for 64-bit compatibility.) 3231 // Rather than emitting a normal format/argument mismatch, we want to 3232 // add a cast to the recommended type (and correct the format string 3233 // if necessary). 3234 SmallString<16> CastBuf; 3235 llvm::raw_svector_ostream CastFix(CastBuf); 3236 CastFix << "("; 3237 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 3238 CastFix << ")"; 3239 3240 SmallVector<FixItHint,4> Hints; 3241 if (!AT.matchesType(S.Context, IntendedTy)) 3242 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 3243 3244 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 3245 // If there's already a cast present, just replace it. 3246 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 3247 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 3248 3249 } else if (!requiresParensToAddCast(E)) { 3250 // If the expression has high enough precedence, 3251 // just write the C-style cast. 3252 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 3253 CastFix.str())); 3254 } else { 3255 // Otherwise, add parens around the expression as well as the cast. 3256 CastFix << "("; 3257 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 3258 CastFix.str())); 3259 3260 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd()); 3261 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 3262 } 3263 3264 if (ShouldNotPrintDirectly) { 3265 // The expression has a type that should not be printed directly. 3266 // We extract the name from the typedef because we don't want to show 3267 // the underlying type in the diagnostic. 3268 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName(); 3269 3270 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 3271 << Name << IntendedTy 3272 << E->getSourceRange(), 3273 E->getLocStart(), /*IsStringLocation=*/false, 3274 SpecRange, Hints); 3275 } else { 3276 // In this case, the expression could be printed using a different 3277 // specifier, but we've decided that the specifier is probably correct 3278 // and we should cast instead. Just use the normal warning message. 3279 EmitFormatDiagnostic( 3280 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 3281 << AT.getRepresentativeTypeName(S.Context) << ExprTy 3282 << E->getSourceRange(), 3283 E->getLocStart(), /*IsStringLocation*/false, 3284 SpecRange, Hints); 3285 } 3286 } 3287 } else { 3288 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 3289 SpecifierLen); 3290 // Since the warning for passing non-POD types to variadic functions 3291 // was deferred until now, we emit a warning for non-POD 3292 // arguments here. 3293 switch (S.isValidVarArgType(ExprTy)) { 3294 case Sema::VAK_Valid: 3295 case Sema::VAK_ValidInCXX11: 3296 EmitFormatDiagnostic( 3297 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 3298 << AT.getRepresentativeTypeName(S.Context) << ExprTy 3299 << CSR 3300 << E->getSourceRange(), 3301 E->getLocStart(), /*IsStringLocation*/false, CSR); 3302 break; 3303 3304 case Sema::VAK_Undefined: 3305 EmitFormatDiagnostic( 3306 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 3307 << S.getLangOpts().CPlusPlus11 3308 << ExprTy 3309 << CallType 3310 << AT.getRepresentativeTypeName(S.Context) 3311 << CSR 3312 << E->getSourceRange(), 3313 E->getLocStart(), /*IsStringLocation*/false, CSR); 3314 checkForCStrMembers(AT, E, CSR); 3315 break; 3316 3317 case Sema::VAK_Invalid: 3318 if (ExprTy->isObjCObjectType()) 3319 EmitFormatDiagnostic( 3320 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 3321 << S.getLangOpts().CPlusPlus11 3322 << ExprTy 3323 << CallType 3324 << AT.getRepresentativeTypeName(S.Context) 3325 << CSR 3326 << E->getSourceRange(), 3327 E->getLocStart(), /*IsStringLocation*/false, CSR); 3328 else 3329 // FIXME: If this is an initializer list, suggest removing the braces 3330 // or inserting a cast to the target type. 3331 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 3332 << isa<InitListExpr>(E) << ExprTy << CallType 3333 << AT.getRepresentativeTypeName(S.Context) 3334 << E->getSourceRange(); 3335 break; 3336 } 3337 3338 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 3339 "format string specifier index out of range"); 3340 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 3341 } 3342 3343 return true; 3344 } 3345 3346 //===--- CHECK: Scanf format string checking ------------------------------===// 3347 3348 namespace { 3349 class CheckScanfHandler : public CheckFormatHandler { 3350 public: 3351 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 3352 const Expr *origFormatExpr, unsigned firstDataArg, 3353 unsigned numDataArgs, const char *beg, bool hasVAListArg, 3354 ArrayRef<const Expr *> Args, 3355 unsigned formatIdx, bool inFunctionCall, 3356 Sema::VariadicCallType CallType, 3357 llvm::SmallBitVector &CheckedVarArgs) 3358 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 3359 numDataArgs, beg, hasVAListArg, 3360 Args, formatIdx, inFunctionCall, CallType, 3361 CheckedVarArgs) 3362 {} 3363 3364 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 3365 const char *startSpecifier, 3366 unsigned specifierLen); 3367 3368 bool HandleInvalidScanfConversionSpecifier( 3369 const analyze_scanf::ScanfSpecifier &FS, 3370 const char *startSpecifier, 3371 unsigned specifierLen); 3372 3373 void HandleIncompleteScanList(const char *start, const char *end); 3374 }; 3375 } 3376 3377 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 3378 const char *end) { 3379 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 3380 getLocationOfByte(end), /*IsStringLocation*/true, 3381 getSpecifierRange(start, end - start)); 3382 } 3383 3384 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 3385 const analyze_scanf::ScanfSpecifier &FS, 3386 const char *startSpecifier, 3387 unsigned specifierLen) { 3388 3389 const analyze_scanf::ScanfConversionSpecifier &CS = 3390 FS.getConversionSpecifier(); 3391 3392 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 3393 getLocationOfByte(CS.getStart()), 3394 startSpecifier, specifierLen, 3395 CS.getStart(), CS.getLength()); 3396 } 3397 3398 bool CheckScanfHandler::HandleScanfSpecifier( 3399 const analyze_scanf::ScanfSpecifier &FS, 3400 const char *startSpecifier, 3401 unsigned specifierLen) { 3402 3403 using namespace analyze_scanf; 3404 using namespace analyze_format_string; 3405 3406 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 3407 3408 // Handle case where '%' and '*' don't consume an argument. These shouldn't 3409 // be used to decide if we are using positional arguments consistently. 3410 if (FS.consumesDataArgument()) { 3411 if (atFirstArg) { 3412 atFirstArg = false; 3413 usesPositionalArgs = FS.usesPositionalArg(); 3414 } 3415 else if (usesPositionalArgs != FS.usesPositionalArg()) { 3416 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 3417 startSpecifier, specifierLen); 3418 return false; 3419 } 3420 } 3421 3422 // Check if the field with is non-zero. 3423 const OptionalAmount &Amt = FS.getFieldWidth(); 3424 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 3425 if (Amt.getConstantAmount() == 0) { 3426 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 3427 Amt.getConstantLength()); 3428 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 3429 getLocationOfByte(Amt.getStart()), 3430 /*IsStringLocation*/true, R, 3431 FixItHint::CreateRemoval(R)); 3432 } 3433 } 3434 3435 if (!FS.consumesDataArgument()) { 3436 // FIXME: Technically specifying a precision or field width here 3437 // makes no sense. Worth issuing a warning at some point. 3438 return true; 3439 } 3440 3441 // Consume the argument. 3442 unsigned argIndex = FS.getArgIndex(); 3443 if (argIndex < NumDataArgs) { 3444 // The check to see if the argIndex is valid will come later. 3445 // We set the bit here because we may exit early from this 3446 // function if we encounter some other error. 3447 CoveredArgs.set(argIndex); 3448 } 3449 3450 // Check the length modifier is valid with the given conversion specifier. 3451 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 3452 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 3453 diag::warn_format_nonsensical_length); 3454 else if (!FS.hasStandardLengthModifier()) 3455 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 3456 else if (!FS.hasStandardLengthConversionCombination()) 3457 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 3458 diag::warn_format_non_standard_conversion_spec); 3459 3460 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 3461 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 3462 3463 // The remaining checks depend on the data arguments. 3464 if (HasVAListArg) 3465 return true; 3466 3467 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 3468 return false; 3469 3470 // Check that the argument type matches the format specifier. 3471 const Expr *Ex = getDataArg(argIndex); 3472 if (!Ex) 3473 return true; 3474 3475 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 3476 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) { 3477 ScanfSpecifier fixedFS = FS; 3478 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(), 3479 S.Context); 3480 3481 if (success) { 3482 // Get the fix string from the fixed format specifier. 3483 SmallString<128> buf; 3484 llvm::raw_svector_ostream os(buf); 3485 fixedFS.toString(os); 3486 3487 EmitFormatDiagnostic( 3488 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 3489 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 3490 << Ex->getSourceRange(), 3491 Ex->getLocStart(), 3492 /*IsStringLocation*/false, 3493 getSpecifierRange(startSpecifier, specifierLen), 3494 FixItHint::CreateReplacement( 3495 getSpecifierRange(startSpecifier, specifierLen), 3496 os.str())); 3497 } else { 3498 EmitFormatDiagnostic( 3499 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 3500 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 3501 << Ex->getSourceRange(), 3502 Ex->getLocStart(), 3503 /*IsStringLocation*/false, 3504 getSpecifierRange(startSpecifier, specifierLen)); 3505 } 3506 } 3507 3508 return true; 3509 } 3510 3511 void Sema::CheckFormatString(const StringLiteral *FExpr, 3512 const Expr *OrigFormatExpr, 3513 ArrayRef<const Expr *> Args, 3514 bool HasVAListArg, unsigned format_idx, 3515 unsigned firstDataArg, FormatStringType Type, 3516 bool inFunctionCall, VariadicCallType CallType, 3517 llvm::SmallBitVector &CheckedVarArgs) { 3518 3519 // CHECK: is the format string a wide literal? 3520 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 3521 CheckFormatHandler::EmitFormatDiagnostic( 3522 *this, inFunctionCall, Args[format_idx], 3523 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 3524 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 3525 return; 3526 } 3527 3528 // Str - The format string. NOTE: this is NOT null-terminated! 3529 StringRef StrRef = FExpr->getString(); 3530 const char *Str = StrRef.data(); 3531 unsigned StrLen = StrRef.size(); 3532 const unsigned numDataArgs = Args.size() - firstDataArg; 3533 3534 // CHECK: empty format string? 3535 if (StrLen == 0 && numDataArgs > 0) { 3536 CheckFormatHandler::EmitFormatDiagnostic( 3537 *this, inFunctionCall, Args[format_idx], 3538 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 3539 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 3540 return; 3541 } 3542 3543 if (Type == FST_Printf || Type == FST_NSString) { 3544 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 3545 numDataArgs, (Type == FST_NSString), 3546 Str, HasVAListArg, Args, format_idx, 3547 inFunctionCall, CallType, CheckedVarArgs); 3548 3549 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 3550 getLangOpts(), 3551 Context.getTargetInfo())) 3552 H.DoneProcessing(); 3553 } else if (Type == FST_Scanf) { 3554 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs, 3555 Str, HasVAListArg, Args, format_idx, 3556 inFunctionCall, CallType, CheckedVarArgs); 3557 3558 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 3559 getLangOpts(), 3560 Context.getTargetInfo())) 3561 H.DoneProcessing(); 3562 } // TODO: handle other formats 3563 } 3564 3565 //===--- CHECK: Standard memory functions ---------------------------------===// 3566 3567 /// \brief Takes the expression passed to the size_t parameter of functions 3568 /// such as memcmp, strncat, etc and warns if it's a comparison. 3569 /// 3570 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 3571 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 3572 IdentifierInfo *FnName, 3573 SourceLocation FnLoc, 3574 SourceLocation RParenLoc) { 3575 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 3576 if (!Size) 3577 return false; 3578 3579 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 3580 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 3581 return false; 3582 3583 Preprocessor &PP = S.getPreprocessor(); 3584 SourceRange SizeRange = Size->getSourceRange(); 3585 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 3586 << SizeRange << FnName; 3587 S.Diag(FnLoc, diag::warn_memsize_comparison_paren_note) 3588 << FnName 3589 << FixItHint::CreateInsertion( 3590 PP.getLocForEndOfToken(Size->getLHS()->getLocEnd()), 3591 ")") 3592 << FixItHint::CreateRemoval(RParenLoc); 3593 S.Diag(SizeRange.getBegin(), diag::warn_memsize_comparison_cast_note) 3594 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 3595 << FixItHint::CreateInsertion( 3596 PP.getLocForEndOfToken(SizeRange.getEnd()), ")"); 3597 3598 return true; 3599 } 3600 3601 /// \brief Determine whether the given type is a dynamic class type (e.g., 3602 /// whether it has a vtable). 3603 static bool isDynamicClassType(QualType T) { 3604 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3605 if (CXXRecordDecl *Definition = Record->getDefinition()) 3606 if (Definition->isDynamicClass()) 3607 return true; 3608 3609 return false; 3610 } 3611 3612 /// \brief If E is a sizeof expression, returns its argument expression, 3613 /// otherwise returns NULL. 3614 static const Expr *getSizeOfExprArg(const Expr* E) { 3615 if (const UnaryExprOrTypeTraitExpr *SizeOf = 3616 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 3617 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 3618 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 3619 3620 return 0; 3621 } 3622 3623 /// \brief If E is a sizeof expression, returns its argument type. 3624 static QualType getSizeOfArgType(const Expr* E) { 3625 if (const UnaryExprOrTypeTraitExpr *SizeOf = 3626 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 3627 if (SizeOf->getKind() == clang::UETT_SizeOf) 3628 return SizeOf->getTypeOfArgument(); 3629 3630 return QualType(); 3631 } 3632 3633 /// \brief Check for dangerous or invalid arguments to memset(). 3634 /// 3635 /// This issues warnings on known problematic, dangerous or unspecified 3636 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 3637 /// function calls. 3638 /// 3639 /// \param Call The call expression to diagnose. 3640 void Sema::CheckMemaccessArguments(const CallExpr *Call, 3641 unsigned BId, 3642 IdentifierInfo *FnName) { 3643 assert(BId != 0); 3644 3645 // It is possible to have a non-standard definition of memset. Validate 3646 // we have enough arguments, and if not, abort further checking. 3647 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3); 3648 if (Call->getNumArgs() < ExpectedNumArgs) 3649 return; 3650 3651 unsigned LastArg = (BId == Builtin::BImemset || 3652 BId == Builtin::BIstrndup ? 1 : 2); 3653 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2); 3654 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 3655 3656 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 3657 Call->getLocStart(), Call->getRParenLoc())) 3658 return; 3659 3660 // We have special checking when the length is a sizeof expression. 3661 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 3662 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 3663 llvm::FoldingSetNodeID SizeOfArgID; 3664 3665 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 3666 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 3667 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 3668 3669 QualType DestTy = Dest->getType(); 3670 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 3671 QualType PointeeTy = DestPtrTy->getPointeeType(); 3672 3673 // Never warn about void type pointers. This can be used to suppress 3674 // false positives. 3675 if (PointeeTy->isVoidType()) 3676 continue; 3677 3678 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 3679 // actually comparing the expressions for equality. Because computing the 3680 // expression IDs can be expensive, we only do this if the diagnostic is 3681 // enabled. 3682 if (SizeOfArg && 3683 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess, 3684 SizeOfArg->getExprLoc())) { 3685 // We only compute IDs for expressions if the warning is enabled, and 3686 // cache the sizeof arg's ID. 3687 if (SizeOfArgID == llvm::FoldingSetNodeID()) 3688 SizeOfArg->Profile(SizeOfArgID, Context, true); 3689 llvm::FoldingSetNodeID DestID; 3690 Dest->Profile(DestID, Context, true); 3691 if (DestID == SizeOfArgID) { 3692 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 3693 // over sizeof(src) as well. 3694 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 3695 StringRef ReadableName = FnName->getName(); 3696 3697 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 3698 if (UnaryOp->getOpcode() == UO_AddrOf) 3699 ActionIdx = 1; // If its an address-of operator, just remove it. 3700 if (!PointeeTy->isIncompleteType() && 3701 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 3702 ActionIdx = 2; // If the pointee's size is sizeof(char), 3703 // suggest an explicit length. 3704 3705 // If the function is defined as a builtin macro, do not show macro 3706 // expansion. 3707 SourceLocation SL = SizeOfArg->getExprLoc(); 3708 SourceRange DSR = Dest->getSourceRange(); 3709 SourceRange SSR = SizeOfArg->getSourceRange(); 3710 SourceManager &SM = PP.getSourceManager(); 3711 3712 if (SM.isMacroArgExpansion(SL)) { 3713 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 3714 SL = SM.getSpellingLoc(SL); 3715 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 3716 SM.getSpellingLoc(DSR.getEnd())); 3717 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 3718 SM.getSpellingLoc(SSR.getEnd())); 3719 } 3720 3721 DiagRuntimeBehavior(SL, SizeOfArg, 3722 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 3723 << ReadableName 3724 << PointeeTy 3725 << DestTy 3726 << DSR 3727 << SSR); 3728 DiagRuntimeBehavior(SL, SizeOfArg, 3729 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 3730 << ActionIdx 3731 << SSR); 3732 3733 break; 3734 } 3735 } 3736 3737 // Also check for cases where the sizeof argument is the exact same 3738 // type as the memory argument, and where it points to a user-defined 3739 // record type. 3740 if (SizeOfArgTy != QualType()) { 3741 if (PointeeTy->isRecordType() && 3742 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 3743 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 3744 PDiag(diag::warn_sizeof_pointer_type_memaccess) 3745 << FnName << SizeOfArgTy << ArgIdx 3746 << PointeeTy << Dest->getSourceRange() 3747 << LenExpr->getSourceRange()); 3748 break; 3749 } 3750 } 3751 3752 // Always complain about dynamic classes. 3753 if (isDynamicClassType(PointeeTy)) { 3754 3755 unsigned OperationType = 0; 3756 // "overwritten" if we're warning about the destination for any call 3757 // but memcmp; otherwise a verb appropriate to the call. 3758 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 3759 if (BId == Builtin::BImemcpy) 3760 OperationType = 1; 3761 else if(BId == Builtin::BImemmove) 3762 OperationType = 2; 3763 else if (BId == Builtin::BImemcmp) 3764 OperationType = 3; 3765 } 3766 3767 DiagRuntimeBehavior( 3768 Dest->getExprLoc(), Dest, 3769 PDiag(diag::warn_dyn_class_memaccess) 3770 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 3771 << FnName << PointeeTy 3772 << OperationType 3773 << Call->getCallee()->getSourceRange()); 3774 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 3775 BId != Builtin::BImemset) 3776 DiagRuntimeBehavior( 3777 Dest->getExprLoc(), Dest, 3778 PDiag(diag::warn_arc_object_memaccess) 3779 << ArgIdx << FnName << PointeeTy 3780 << Call->getCallee()->getSourceRange()); 3781 else 3782 continue; 3783 3784 DiagRuntimeBehavior( 3785 Dest->getExprLoc(), Dest, 3786 PDiag(diag::note_bad_memaccess_silence) 3787 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 3788 break; 3789 } 3790 } 3791 } 3792 3793 // A little helper routine: ignore addition and subtraction of integer literals. 3794 // This intentionally does not ignore all integer constant expressions because 3795 // we don't want to remove sizeof(). 3796 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 3797 Ex = Ex->IgnoreParenCasts(); 3798 3799 for (;;) { 3800 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 3801 if (!BO || !BO->isAdditiveOp()) 3802 break; 3803 3804 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 3805 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 3806 3807 if (isa<IntegerLiteral>(RHS)) 3808 Ex = LHS; 3809 else if (isa<IntegerLiteral>(LHS)) 3810 Ex = RHS; 3811 else 3812 break; 3813 } 3814 3815 return Ex; 3816 } 3817 3818 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 3819 ASTContext &Context) { 3820 // Only handle constant-sized or VLAs, but not flexible members. 3821 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 3822 // Only issue the FIXIT for arrays of size > 1. 3823 if (CAT->getSize().getSExtValue() <= 1) 3824 return false; 3825 } else if (!Ty->isVariableArrayType()) { 3826 return false; 3827 } 3828 return true; 3829 } 3830 3831 // Warn if the user has made the 'size' argument to strlcpy or strlcat 3832 // be the size of the source, instead of the destination. 3833 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 3834 IdentifierInfo *FnName) { 3835 3836 // Don't crash if the user has the wrong number of arguments 3837 if (Call->getNumArgs() != 3) 3838 return; 3839 3840 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 3841 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 3842 const Expr *CompareWithSrc = NULL; 3843 3844 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 3845 Call->getLocStart(), Call->getRParenLoc())) 3846 return; 3847 3848 // Look for 'strlcpy(dst, x, sizeof(x))' 3849 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 3850 CompareWithSrc = Ex; 3851 else { 3852 // Look for 'strlcpy(dst, x, strlen(x))' 3853 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 3854 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 3855 SizeCall->getNumArgs() == 1) 3856 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 3857 } 3858 } 3859 3860 if (!CompareWithSrc) 3861 return; 3862 3863 // Determine if the argument to sizeof/strlen is equal to the source 3864 // argument. In principle there's all kinds of things you could do 3865 // here, for instance creating an == expression and evaluating it with 3866 // EvaluateAsBooleanCondition, but this uses a more direct technique: 3867 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 3868 if (!SrcArgDRE) 3869 return; 3870 3871 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 3872 if (!CompareWithSrcDRE || 3873 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 3874 return; 3875 3876 const Expr *OriginalSizeArg = Call->getArg(2); 3877 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 3878 << OriginalSizeArg->getSourceRange() << FnName; 3879 3880 // Output a FIXIT hint if the destination is an array (rather than a 3881 // pointer to an array). This could be enhanced to handle some 3882 // pointers if we know the actual size, like if DstArg is 'array+2' 3883 // we could say 'sizeof(array)-2'. 3884 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 3885 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 3886 return; 3887 3888 SmallString<128> sizeString; 3889 llvm::raw_svector_ostream OS(sizeString); 3890 OS << "sizeof("; 3891 DstArg->printPretty(OS, 0, getPrintingPolicy()); 3892 OS << ")"; 3893 3894 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 3895 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 3896 OS.str()); 3897 } 3898 3899 /// Check if two expressions refer to the same declaration. 3900 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 3901 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 3902 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 3903 return D1->getDecl() == D2->getDecl(); 3904 return false; 3905 } 3906 3907 static const Expr *getStrlenExprArg(const Expr *E) { 3908 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 3909 const FunctionDecl *FD = CE->getDirectCallee(); 3910 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 3911 return 0; 3912 return CE->getArg(0)->IgnoreParenCasts(); 3913 } 3914 return 0; 3915 } 3916 3917 // Warn on anti-patterns as the 'size' argument to strncat. 3918 // The correct size argument should look like following: 3919 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 3920 void Sema::CheckStrncatArguments(const CallExpr *CE, 3921 IdentifierInfo *FnName) { 3922 // Don't crash if the user has the wrong number of arguments. 3923 if (CE->getNumArgs() < 3) 3924 return; 3925 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 3926 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 3927 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 3928 3929 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 3930 CE->getRParenLoc())) 3931 return; 3932 3933 // Identify common expressions, which are wrongly used as the size argument 3934 // to strncat and may lead to buffer overflows. 3935 unsigned PatternType = 0; 3936 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 3937 // - sizeof(dst) 3938 if (referToTheSameDecl(SizeOfArg, DstArg)) 3939 PatternType = 1; 3940 // - sizeof(src) 3941 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 3942 PatternType = 2; 3943 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 3944 if (BE->getOpcode() == BO_Sub) { 3945 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 3946 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 3947 // - sizeof(dst) - strlen(dst) 3948 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 3949 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 3950 PatternType = 1; 3951 // - sizeof(src) - (anything) 3952 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 3953 PatternType = 2; 3954 } 3955 } 3956 3957 if (PatternType == 0) 3958 return; 3959 3960 // Generate the diagnostic. 3961 SourceLocation SL = LenArg->getLocStart(); 3962 SourceRange SR = LenArg->getSourceRange(); 3963 SourceManager &SM = PP.getSourceManager(); 3964 3965 // If the function is defined as a builtin macro, do not show macro expansion. 3966 if (SM.isMacroArgExpansion(SL)) { 3967 SL = SM.getSpellingLoc(SL); 3968 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 3969 SM.getSpellingLoc(SR.getEnd())); 3970 } 3971 3972 // Check if the destination is an array (rather than a pointer to an array). 3973 QualType DstTy = DstArg->getType(); 3974 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 3975 Context); 3976 if (!isKnownSizeArray) { 3977 if (PatternType == 1) 3978 Diag(SL, diag::warn_strncat_wrong_size) << SR; 3979 else 3980 Diag(SL, diag::warn_strncat_src_size) << SR; 3981 return; 3982 } 3983 3984 if (PatternType == 1) 3985 Diag(SL, diag::warn_strncat_large_size) << SR; 3986 else 3987 Diag(SL, diag::warn_strncat_src_size) << SR; 3988 3989 SmallString<128> sizeString; 3990 llvm::raw_svector_ostream OS(sizeString); 3991 OS << "sizeof("; 3992 DstArg->printPretty(OS, 0, getPrintingPolicy()); 3993 OS << ") - "; 3994 OS << "strlen("; 3995 DstArg->printPretty(OS, 0, getPrintingPolicy()); 3996 OS << ") - 1"; 3997 3998 Diag(SL, diag::note_strncat_wrong_size) 3999 << FixItHint::CreateReplacement(SR, OS.str()); 4000 } 4001 4002 //===--- CHECK: Return Address of Stack Variable --------------------------===// 4003 4004 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 4005 Decl *ParentDecl); 4006 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars, 4007 Decl *ParentDecl); 4008 4009 /// CheckReturnStackAddr - Check if a return statement returns the address 4010 /// of a stack variable. 4011 static void 4012 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 4013 SourceLocation ReturnLoc) { 4014 4015 Expr *stackE = 0; 4016 SmallVector<DeclRefExpr *, 8> refVars; 4017 4018 // Perform checking for returned stack addresses, local blocks, 4019 // label addresses or references to temporaries. 4020 if (lhsType->isPointerType() || 4021 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 4022 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0); 4023 } else if (lhsType->isReferenceType()) { 4024 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0); 4025 } 4026 4027 if (stackE == 0) 4028 return; // Nothing suspicious was found. 4029 4030 SourceLocation diagLoc; 4031 SourceRange diagRange; 4032 if (refVars.empty()) { 4033 diagLoc = stackE->getLocStart(); 4034 diagRange = stackE->getSourceRange(); 4035 } else { 4036 // We followed through a reference variable. 'stackE' contains the 4037 // problematic expression but we will warn at the return statement pointing 4038 // at the reference variable. We will later display the "trail" of 4039 // reference variables using notes. 4040 diagLoc = refVars[0]->getLocStart(); 4041 diagRange = refVars[0]->getSourceRange(); 4042 } 4043 4044 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var. 4045 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref 4046 : diag::warn_ret_stack_addr) 4047 << DR->getDecl()->getDeclName() << diagRange; 4048 } else if (isa<BlockExpr>(stackE)) { // local block. 4049 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 4050 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 4051 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 4052 } else { // local temporary. 4053 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref 4054 : diag::warn_ret_local_temp_addr) 4055 << diagRange; 4056 } 4057 4058 // Display the "trail" of reference variables that we followed until we 4059 // found the problematic expression using notes. 4060 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 4061 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 4062 // If this var binds to another reference var, show the range of the next 4063 // var, otherwise the var binds to the problematic expression, in which case 4064 // show the range of the expression. 4065 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange() 4066 : stackE->getSourceRange(); 4067 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 4068 << VD->getDeclName() << range; 4069 } 4070 } 4071 4072 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 4073 /// check if the expression in a return statement evaluates to an address 4074 /// to a location on the stack, a local block, an address of a label, or a 4075 /// reference to local temporary. The recursion is used to traverse the 4076 /// AST of the return expression, with recursion backtracking when we 4077 /// encounter a subexpression that (1) clearly does not lead to one of the 4078 /// above problematic expressions (2) is something we cannot determine leads to 4079 /// a problematic expression based on such local checking. 4080 /// 4081 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 4082 /// the expression that they point to. Such variables are added to the 4083 /// 'refVars' vector so that we know what the reference variable "trail" was. 4084 /// 4085 /// EvalAddr processes expressions that are pointers that are used as 4086 /// references (and not L-values). EvalVal handles all other values. 4087 /// At the base case of the recursion is a check for the above problematic 4088 /// expressions. 4089 /// 4090 /// This implementation handles: 4091 /// 4092 /// * pointer-to-pointer casts 4093 /// * implicit conversions from array references to pointers 4094 /// * taking the address of fields 4095 /// * arbitrary interplay between "&" and "*" operators 4096 /// * pointer arithmetic from an address of a stack variable 4097 /// * taking the address of an array element where the array is on the stack 4098 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 4099 Decl *ParentDecl) { 4100 if (E->isTypeDependent()) 4101 return NULL; 4102 4103 // We should only be called for evaluating pointer expressions. 4104 assert((E->getType()->isAnyPointerType() || 4105 E->getType()->isBlockPointerType() || 4106 E->getType()->isObjCQualifiedIdType()) && 4107 "EvalAddr only works on pointers"); 4108 4109 E = E->IgnoreParens(); 4110 4111 // Our "symbolic interpreter" is just a dispatch off the currently 4112 // viewed AST node. We then recursively traverse the AST by calling 4113 // EvalAddr and EvalVal appropriately. 4114 switch (E->getStmtClass()) { 4115 case Stmt::DeclRefExprClass: { 4116 DeclRefExpr *DR = cast<DeclRefExpr>(E); 4117 4118 // If we leave the immediate function, the lifetime isn't about to end. 4119 if (DR->refersToEnclosingLocal()) 4120 return 0; 4121 4122 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 4123 // If this is a reference variable, follow through to the expression that 4124 // it points to. 4125 if (V->hasLocalStorage() && 4126 V->getType()->isReferenceType() && V->hasInit()) { 4127 // Add the reference variable to the "trail". 4128 refVars.push_back(DR); 4129 return EvalAddr(V->getInit(), refVars, ParentDecl); 4130 } 4131 4132 return NULL; 4133 } 4134 4135 case Stmt::UnaryOperatorClass: { 4136 // The only unary operator that make sense to handle here 4137 // is AddrOf. All others don't make sense as pointers. 4138 UnaryOperator *U = cast<UnaryOperator>(E); 4139 4140 if (U->getOpcode() == UO_AddrOf) 4141 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 4142 else 4143 return NULL; 4144 } 4145 4146 case Stmt::BinaryOperatorClass: { 4147 // Handle pointer arithmetic. All other binary operators are not valid 4148 // in this context. 4149 BinaryOperator *B = cast<BinaryOperator>(E); 4150 BinaryOperatorKind op = B->getOpcode(); 4151 4152 if (op != BO_Add && op != BO_Sub) 4153 return NULL; 4154 4155 Expr *Base = B->getLHS(); 4156 4157 // Determine which argument is the real pointer base. It could be 4158 // the RHS argument instead of the LHS. 4159 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 4160 4161 assert (Base->getType()->isPointerType()); 4162 return EvalAddr(Base, refVars, ParentDecl); 4163 } 4164 4165 // For conditional operators we need to see if either the LHS or RHS are 4166 // valid DeclRefExpr*s. If one of them is valid, we return it. 4167 case Stmt::ConditionalOperatorClass: { 4168 ConditionalOperator *C = cast<ConditionalOperator>(E); 4169 4170 // Handle the GNU extension for missing LHS. 4171 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 4172 if (Expr *LHSExpr = C->getLHS()) { 4173 // In C++, we can have a throw-expression, which has 'void' type. 4174 if (!LHSExpr->getType()->isVoidType()) 4175 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 4176 return LHS; 4177 } 4178 4179 // In C++, we can have a throw-expression, which has 'void' type. 4180 if (C->getRHS()->getType()->isVoidType()) 4181 return 0; 4182 4183 return EvalAddr(C->getRHS(), refVars, ParentDecl); 4184 } 4185 4186 case Stmt::BlockExprClass: 4187 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 4188 return E; // local block. 4189 return NULL; 4190 4191 case Stmt::AddrLabelExprClass: 4192 return E; // address of label. 4193 4194 case Stmt::ExprWithCleanupsClass: 4195 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 4196 ParentDecl); 4197 4198 // For casts, we need to handle conversions from arrays to 4199 // pointer values, and pointer-to-pointer conversions. 4200 case Stmt::ImplicitCastExprClass: 4201 case Stmt::CStyleCastExprClass: 4202 case Stmt::CXXFunctionalCastExprClass: 4203 case Stmt::ObjCBridgedCastExprClass: 4204 case Stmt::CXXStaticCastExprClass: 4205 case Stmt::CXXDynamicCastExprClass: 4206 case Stmt::CXXConstCastExprClass: 4207 case Stmt::CXXReinterpretCastExprClass: { 4208 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 4209 switch (cast<CastExpr>(E)->getCastKind()) { 4210 case CK_BitCast: 4211 case CK_LValueToRValue: 4212 case CK_NoOp: 4213 case CK_BaseToDerived: 4214 case CK_DerivedToBase: 4215 case CK_UncheckedDerivedToBase: 4216 case CK_Dynamic: 4217 case CK_CPointerToObjCPointerCast: 4218 case CK_BlockPointerToObjCPointerCast: 4219 case CK_AnyPointerToBlockPointerCast: 4220 return EvalAddr(SubExpr, refVars, ParentDecl); 4221 4222 case CK_ArrayToPointerDecay: 4223 return EvalVal(SubExpr, refVars, ParentDecl); 4224 4225 default: 4226 return 0; 4227 } 4228 } 4229 4230 case Stmt::MaterializeTemporaryExprClass: 4231 if (Expr *Result = EvalAddr( 4232 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 4233 refVars, ParentDecl)) 4234 return Result; 4235 4236 return E; 4237 4238 // Everything else: we simply don't reason about them. 4239 default: 4240 return NULL; 4241 } 4242 } 4243 4244 4245 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 4246 /// See the comments for EvalAddr for more details. 4247 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 4248 Decl *ParentDecl) { 4249 do { 4250 // We should only be called for evaluating non-pointer expressions, or 4251 // expressions with a pointer type that are not used as references but instead 4252 // are l-values (e.g., DeclRefExpr with a pointer type). 4253 4254 // Our "symbolic interpreter" is just a dispatch off the currently 4255 // viewed AST node. We then recursively traverse the AST by calling 4256 // EvalAddr and EvalVal appropriately. 4257 4258 E = E->IgnoreParens(); 4259 switch (E->getStmtClass()) { 4260 case Stmt::ImplicitCastExprClass: { 4261 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 4262 if (IE->getValueKind() == VK_LValue) { 4263 E = IE->getSubExpr(); 4264 continue; 4265 } 4266 return NULL; 4267 } 4268 4269 case Stmt::ExprWithCleanupsClass: 4270 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl); 4271 4272 case Stmt::DeclRefExprClass: { 4273 // When we hit a DeclRefExpr we are looking at code that refers to a 4274 // variable's name. If it's not a reference variable we check if it has 4275 // local storage within the function, and if so, return the expression. 4276 DeclRefExpr *DR = cast<DeclRefExpr>(E); 4277 4278 // If we leave the immediate function, the lifetime isn't about to end. 4279 if (DR->refersToEnclosingLocal()) 4280 return 0; 4281 4282 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 4283 // Check if it refers to itself, e.g. "int& i = i;". 4284 if (V == ParentDecl) 4285 return DR; 4286 4287 if (V->hasLocalStorage()) { 4288 if (!V->getType()->isReferenceType()) 4289 return DR; 4290 4291 // Reference variable, follow through to the expression that 4292 // it points to. 4293 if (V->hasInit()) { 4294 // Add the reference variable to the "trail". 4295 refVars.push_back(DR); 4296 return EvalVal(V->getInit(), refVars, V); 4297 } 4298 } 4299 } 4300 4301 return NULL; 4302 } 4303 4304 case Stmt::UnaryOperatorClass: { 4305 // The only unary operator that make sense to handle here 4306 // is Deref. All others don't resolve to a "name." This includes 4307 // handling all sorts of rvalues passed to a unary operator. 4308 UnaryOperator *U = cast<UnaryOperator>(E); 4309 4310 if (U->getOpcode() == UO_Deref) 4311 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 4312 4313 return NULL; 4314 } 4315 4316 case Stmt::ArraySubscriptExprClass: { 4317 // Array subscripts are potential references to data on the stack. We 4318 // retrieve the DeclRefExpr* for the array variable if it indeed 4319 // has local storage. 4320 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl); 4321 } 4322 4323 case Stmt::ConditionalOperatorClass: { 4324 // For conditional operators we need to see if either the LHS or RHS are 4325 // non-NULL Expr's. If one is non-NULL, we return it. 4326 ConditionalOperator *C = cast<ConditionalOperator>(E); 4327 4328 // Handle the GNU extension for missing LHS. 4329 if (Expr *LHSExpr = C->getLHS()) { 4330 // In C++, we can have a throw-expression, which has 'void' type. 4331 if (!LHSExpr->getType()->isVoidType()) 4332 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 4333 return LHS; 4334 } 4335 4336 // In C++, we can have a throw-expression, which has 'void' type. 4337 if (C->getRHS()->getType()->isVoidType()) 4338 return 0; 4339 4340 return EvalVal(C->getRHS(), refVars, ParentDecl); 4341 } 4342 4343 // Accesses to members are potential references to data on the stack. 4344 case Stmt::MemberExprClass: { 4345 MemberExpr *M = cast<MemberExpr>(E); 4346 4347 // Check for indirect access. We only want direct field accesses. 4348 if (M->isArrow()) 4349 return NULL; 4350 4351 // Check whether the member type is itself a reference, in which case 4352 // we're not going to refer to the member, but to what the member refers to. 4353 if (M->getMemberDecl()->getType()->isReferenceType()) 4354 return NULL; 4355 4356 return EvalVal(M->getBase(), refVars, ParentDecl); 4357 } 4358 4359 case Stmt::MaterializeTemporaryExprClass: 4360 if (Expr *Result = EvalVal( 4361 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 4362 refVars, ParentDecl)) 4363 return Result; 4364 4365 return E; 4366 4367 default: 4368 // Check that we don't return or take the address of a reference to a 4369 // temporary. This is only useful in C++. 4370 if (!E->isTypeDependent() && E->isRValue()) 4371 return E; 4372 4373 // Everything else: we simply don't reason about them. 4374 return NULL; 4375 } 4376 } while (true); 4377 } 4378 4379 void 4380 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 4381 SourceLocation ReturnLoc, 4382 bool isObjCMethod, 4383 const AttrVec *Attrs, 4384 const FunctionDecl *FD) { 4385 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 4386 4387 // Check if the return value is null but should not be. 4388 if (Attrs) 4389 for (specific_attr_iterator<ReturnsNonNullAttr> 4390 I = specific_attr_iterator<ReturnsNonNullAttr>(Attrs->begin()), 4391 E = specific_attr_iterator<ReturnsNonNullAttr>(Attrs->end()); 4392 I != E; ++I) { 4393 if (CheckNonNullExpr(*this, RetValExp)) 4394 Diag(ReturnLoc, diag::warn_null_ret) 4395 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 4396 break; 4397 } 4398 4399 // C++11 [basic.stc.dynamic.allocation]p4: 4400 // If an allocation function declared with a non-throwing 4401 // exception-specification fails to allocate storage, it shall return 4402 // a null pointer. Any other allocation function that fails to allocate 4403 // storage shall indicate failure only by throwing an exception [...] 4404 if (FD) { 4405 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 4406 if (Op == OO_New || Op == OO_Array_New) { 4407 const FunctionProtoType *Proto 4408 = FD->getType()->castAs<FunctionProtoType>(); 4409 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 4410 CheckNonNullExpr(*this, RetValExp)) 4411 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 4412 << FD << getLangOpts().CPlusPlus11; 4413 } 4414 } 4415 } 4416 4417 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 4418 4419 /// Check for comparisons of floating point operands using != and ==. 4420 /// Issue a warning if these are no self-comparisons, as they are not likely 4421 /// to do what the programmer intended. 4422 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 4423 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 4424 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 4425 4426 // Special case: check for x == x (which is OK). 4427 // Do not emit warnings for such cases. 4428 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 4429 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 4430 if (DRL->getDecl() == DRR->getDecl()) 4431 return; 4432 4433 4434 // Special case: check for comparisons against literals that can be exactly 4435 // represented by APFloat. In such cases, do not emit a warning. This 4436 // is a heuristic: often comparison against such literals are used to 4437 // detect if a value in a variable has not changed. This clearly can 4438 // lead to false negatives. 4439 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 4440 if (FLL->isExact()) 4441 return; 4442 } else 4443 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 4444 if (FLR->isExact()) 4445 return; 4446 4447 // Check for comparisons with builtin types. 4448 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 4449 if (CL->getBuiltinCallee()) 4450 return; 4451 4452 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 4453 if (CR->getBuiltinCallee()) 4454 return; 4455 4456 // Emit the diagnostic. 4457 Diag(Loc, diag::warn_floatingpoint_eq) 4458 << LHS->getSourceRange() << RHS->getSourceRange(); 4459 } 4460 4461 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 4462 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 4463 4464 namespace { 4465 4466 /// Structure recording the 'active' range of an integer-valued 4467 /// expression. 4468 struct IntRange { 4469 /// The number of bits active in the int. 4470 unsigned Width; 4471 4472 /// True if the int is known not to have negative values. 4473 bool NonNegative; 4474 4475 IntRange(unsigned Width, bool NonNegative) 4476 : Width(Width), NonNegative(NonNegative) 4477 {} 4478 4479 /// Returns the range of the bool type. 4480 static IntRange forBoolType() { 4481 return IntRange(1, true); 4482 } 4483 4484 /// Returns the range of an opaque value of the given integral type. 4485 static IntRange forValueOfType(ASTContext &C, QualType T) { 4486 return forValueOfCanonicalType(C, 4487 T->getCanonicalTypeInternal().getTypePtr()); 4488 } 4489 4490 /// Returns the range of an opaque value of a canonical integral type. 4491 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 4492 assert(T->isCanonicalUnqualified()); 4493 4494 if (const VectorType *VT = dyn_cast<VectorType>(T)) 4495 T = VT->getElementType().getTypePtr(); 4496 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 4497 T = CT->getElementType().getTypePtr(); 4498 4499 // For enum types, use the known bit width of the enumerators. 4500 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 4501 EnumDecl *Enum = ET->getDecl(); 4502 if (!Enum->isCompleteDefinition()) 4503 return IntRange(C.getIntWidth(QualType(T, 0)), false); 4504 4505 unsigned NumPositive = Enum->getNumPositiveBits(); 4506 unsigned NumNegative = Enum->getNumNegativeBits(); 4507 4508 if (NumNegative == 0) 4509 return IntRange(NumPositive, true/*NonNegative*/); 4510 else 4511 return IntRange(std::max(NumPositive + 1, NumNegative), 4512 false/*NonNegative*/); 4513 } 4514 4515 const BuiltinType *BT = cast<BuiltinType>(T); 4516 assert(BT->isInteger()); 4517 4518 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 4519 } 4520 4521 /// Returns the "target" range of a canonical integral type, i.e. 4522 /// the range of values expressible in the type. 4523 /// 4524 /// This matches forValueOfCanonicalType except that enums have the 4525 /// full range of their type, not the range of their enumerators. 4526 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 4527 assert(T->isCanonicalUnqualified()); 4528 4529 if (const VectorType *VT = dyn_cast<VectorType>(T)) 4530 T = VT->getElementType().getTypePtr(); 4531 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 4532 T = CT->getElementType().getTypePtr(); 4533 if (const EnumType *ET = dyn_cast<EnumType>(T)) 4534 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 4535 4536 const BuiltinType *BT = cast<BuiltinType>(T); 4537 assert(BT->isInteger()); 4538 4539 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 4540 } 4541 4542 /// Returns the supremum of two ranges: i.e. their conservative merge. 4543 static IntRange join(IntRange L, IntRange R) { 4544 return IntRange(std::max(L.Width, R.Width), 4545 L.NonNegative && R.NonNegative); 4546 } 4547 4548 /// Returns the infinum of two ranges: i.e. their aggressive merge. 4549 static IntRange meet(IntRange L, IntRange R) { 4550 return IntRange(std::min(L.Width, R.Width), 4551 L.NonNegative || R.NonNegative); 4552 } 4553 }; 4554 4555 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 4556 unsigned MaxWidth) { 4557 if (value.isSigned() && value.isNegative()) 4558 return IntRange(value.getMinSignedBits(), false); 4559 4560 if (value.getBitWidth() > MaxWidth) 4561 value = value.trunc(MaxWidth); 4562 4563 // isNonNegative() just checks the sign bit without considering 4564 // signedness. 4565 return IntRange(value.getActiveBits(), true); 4566 } 4567 4568 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 4569 unsigned MaxWidth) { 4570 if (result.isInt()) 4571 return GetValueRange(C, result.getInt(), MaxWidth); 4572 4573 if (result.isVector()) { 4574 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 4575 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 4576 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 4577 R = IntRange::join(R, El); 4578 } 4579 return R; 4580 } 4581 4582 if (result.isComplexInt()) { 4583 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 4584 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 4585 return IntRange::join(R, I); 4586 } 4587 4588 // This can happen with lossless casts to intptr_t of "based" lvalues. 4589 // Assume it might use arbitrary bits. 4590 // FIXME: The only reason we need to pass the type in here is to get 4591 // the sign right on this one case. It would be nice if APValue 4592 // preserved this. 4593 assert(result.isLValue() || result.isAddrLabelDiff()); 4594 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 4595 } 4596 4597 static QualType GetExprType(Expr *E) { 4598 QualType Ty = E->getType(); 4599 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 4600 Ty = AtomicRHS->getValueType(); 4601 return Ty; 4602 } 4603 4604 /// Pseudo-evaluate the given integer expression, estimating the 4605 /// range of values it might take. 4606 /// 4607 /// \param MaxWidth - the width to which the value will be truncated 4608 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { 4609 E = E->IgnoreParens(); 4610 4611 // Try a full evaluation first. 4612 Expr::EvalResult result; 4613 if (E->EvaluateAsRValue(result, C)) 4614 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 4615 4616 // I think we only want to look through implicit casts here; if the 4617 // user has an explicit widening cast, we should treat the value as 4618 // being of the new, wider type. 4619 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 4620 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 4621 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 4622 4623 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 4624 4625 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast); 4626 4627 // Assume that non-integer casts can span the full range of the type. 4628 if (!isIntegerCast) 4629 return OutputTypeRange; 4630 4631 IntRange SubRange 4632 = GetExprRange(C, CE->getSubExpr(), 4633 std::min(MaxWidth, OutputTypeRange.Width)); 4634 4635 // Bail out if the subexpr's range is as wide as the cast type. 4636 if (SubRange.Width >= OutputTypeRange.Width) 4637 return OutputTypeRange; 4638 4639 // Otherwise, we take the smaller width, and we're non-negative if 4640 // either the output type or the subexpr is. 4641 return IntRange(SubRange.Width, 4642 SubRange.NonNegative || OutputTypeRange.NonNegative); 4643 } 4644 4645 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 4646 // If we can fold the condition, just take that operand. 4647 bool CondResult; 4648 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 4649 return GetExprRange(C, CondResult ? CO->getTrueExpr() 4650 : CO->getFalseExpr(), 4651 MaxWidth); 4652 4653 // Otherwise, conservatively merge. 4654 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 4655 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 4656 return IntRange::join(L, R); 4657 } 4658 4659 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 4660 switch (BO->getOpcode()) { 4661 4662 // Boolean-valued operations are single-bit and positive. 4663 case BO_LAnd: 4664 case BO_LOr: 4665 case BO_LT: 4666 case BO_GT: 4667 case BO_LE: 4668 case BO_GE: 4669 case BO_EQ: 4670 case BO_NE: 4671 return IntRange::forBoolType(); 4672 4673 // The type of the assignments is the type of the LHS, so the RHS 4674 // is not necessarily the same type. 4675 case BO_MulAssign: 4676 case BO_DivAssign: 4677 case BO_RemAssign: 4678 case BO_AddAssign: 4679 case BO_SubAssign: 4680 case BO_XorAssign: 4681 case BO_OrAssign: 4682 // TODO: bitfields? 4683 return IntRange::forValueOfType(C, GetExprType(E)); 4684 4685 // Simple assignments just pass through the RHS, which will have 4686 // been coerced to the LHS type. 4687 case BO_Assign: 4688 // TODO: bitfields? 4689 return GetExprRange(C, BO->getRHS(), MaxWidth); 4690 4691 // Operations with opaque sources are black-listed. 4692 case BO_PtrMemD: 4693 case BO_PtrMemI: 4694 return IntRange::forValueOfType(C, GetExprType(E)); 4695 4696 // Bitwise-and uses the *infinum* of the two source ranges. 4697 case BO_And: 4698 case BO_AndAssign: 4699 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 4700 GetExprRange(C, BO->getRHS(), MaxWidth)); 4701 4702 // Left shift gets black-listed based on a judgement call. 4703 case BO_Shl: 4704 // ...except that we want to treat '1 << (blah)' as logically 4705 // positive. It's an important idiom. 4706 if (IntegerLiteral *I 4707 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 4708 if (I->getValue() == 1) { 4709 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 4710 return IntRange(R.Width, /*NonNegative*/ true); 4711 } 4712 } 4713 // fallthrough 4714 4715 case BO_ShlAssign: 4716 return IntRange::forValueOfType(C, GetExprType(E)); 4717 4718 // Right shift by a constant can narrow its left argument. 4719 case BO_Shr: 4720 case BO_ShrAssign: { 4721 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 4722 4723 // If the shift amount is a positive constant, drop the width by 4724 // that much. 4725 llvm::APSInt shift; 4726 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 4727 shift.isNonNegative()) { 4728 unsigned zext = shift.getZExtValue(); 4729 if (zext >= L.Width) 4730 L.Width = (L.NonNegative ? 0 : 1); 4731 else 4732 L.Width -= zext; 4733 } 4734 4735 return L; 4736 } 4737 4738 // Comma acts as its right operand. 4739 case BO_Comma: 4740 return GetExprRange(C, BO->getRHS(), MaxWidth); 4741 4742 // Black-list pointer subtractions. 4743 case BO_Sub: 4744 if (BO->getLHS()->getType()->isPointerType()) 4745 return IntRange::forValueOfType(C, GetExprType(E)); 4746 break; 4747 4748 // The width of a division result is mostly determined by the size 4749 // of the LHS. 4750 case BO_Div: { 4751 // Don't 'pre-truncate' the operands. 4752 unsigned opWidth = C.getIntWidth(GetExprType(E)); 4753 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 4754 4755 // If the divisor is constant, use that. 4756 llvm::APSInt divisor; 4757 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 4758 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 4759 if (log2 >= L.Width) 4760 L.Width = (L.NonNegative ? 0 : 1); 4761 else 4762 L.Width = std::min(L.Width - log2, MaxWidth); 4763 return L; 4764 } 4765 4766 // Otherwise, just use the LHS's width. 4767 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 4768 return IntRange(L.Width, L.NonNegative && R.NonNegative); 4769 } 4770 4771 // The result of a remainder can't be larger than the result of 4772 // either side. 4773 case BO_Rem: { 4774 // Don't 'pre-truncate' the operands. 4775 unsigned opWidth = C.getIntWidth(GetExprType(E)); 4776 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 4777 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 4778 4779 IntRange meet = IntRange::meet(L, R); 4780 meet.Width = std::min(meet.Width, MaxWidth); 4781 return meet; 4782 } 4783 4784 // The default behavior is okay for these. 4785 case BO_Mul: 4786 case BO_Add: 4787 case BO_Xor: 4788 case BO_Or: 4789 break; 4790 } 4791 4792 // The default case is to treat the operation as if it were closed 4793 // on the narrowest type that encompasses both operands. 4794 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 4795 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 4796 return IntRange::join(L, R); 4797 } 4798 4799 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 4800 switch (UO->getOpcode()) { 4801 // Boolean-valued operations are white-listed. 4802 case UO_LNot: 4803 return IntRange::forBoolType(); 4804 4805 // Operations with opaque sources are black-listed. 4806 case UO_Deref: 4807 case UO_AddrOf: // should be impossible 4808 return IntRange::forValueOfType(C, GetExprType(E)); 4809 4810 default: 4811 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 4812 } 4813 } 4814 4815 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) 4816 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 4817 4818 if (FieldDecl *BitField = E->getSourceBitField()) 4819 return IntRange(BitField->getBitWidthValue(C), 4820 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 4821 4822 return IntRange::forValueOfType(C, GetExprType(E)); 4823 } 4824 4825 static IntRange GetExprRange(ASTContext &C, Expr *E) { 4826 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 4827 } 4828 4829 /// Checks whether the given value, which currently has the given 4830 /// source semantics, has the same value when coerced through the 4831 /// target semantics. 4832 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 4833 const llvm::fltSemantics &Src, 4834 const llvm::fltSemantics &Tgt) { 4835 llvm::APFloat truncated = value; 4836 4837 bool ignored; 4838 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 4839 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 4840 4841 return truncated.bitwiseIsEqual(value); 4842 } 4843 4844 /// Checks whether the given value, which currently has the given 4845 /// source semantics, has the same value when coerced through the 4846 /// target semantics. 4847 /// 4848 /// The value might be a vector of floats (or a complex number). 4849 static bool IsSameFloatAfterCast(const APValue &value, 4850 const llvm::fltSemantics &Src, 4851 const llvm::fltSemantics &Tgt) { 4852 if (value.isFloat()) 4853 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 4854 4855 if (value.isVector()) { 4856 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 4857 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 4858 return false; 4859 return true; 4860 } 4861 4862 assert(value.isComplexFloat()); 4863 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 4864 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 4865 } 4866 4867 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 4868 4869 static bool IsZero(Sema &S, Expr *E) { 4870 // Suppress cases where we are comparing against an enum constant. 4871 if (const DeclRefExpr *DR = 4872 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 4873 if (isa<EnumConstantDecl>(DR->getDecl())) 4874 return false; 4875 4876 // Suppress cases where the '0' value is expanded from a macro. 4877 if (E->getLocStart().isMacroID()) 4878 return false; 4879 4880 llvm::APSInt Value; 4881 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 4882 } 4883 4884 static bool HasEnumType(Expr *E) { 4885 // Strip off implicit integral promotions. 4886 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 4887 if (ICE->getCastKind() != CK_IntegralCast && 4888 ICE->getCastKind() != CK_NoOp) 4889 break; 4890 E = ICE->getSubExpr(); 4891 } 4892 4893 return E->getType()->isEnumeralType(); 4894 } 4895 4896 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 4897 // Disable warning in template instantiations. 4898 if (!S.ActiveTemplateInstantiations.empty()) 4899 return; 4900 4901 BinaryOperatorKind op = E->getOpcode(); 4902 if (E->isValueDependent()) 4903 return; 4904 4905 if (op == BO_LT && IsZero(S, E->getRHS())) { 4906 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 4907 << "< 0" << "false" << HasEnumType(E->getLHS()) 4908 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 4909 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 4910 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 4911 << ">= 0" << "true" << HasEnumType(E->getLHS()) 4912 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 4913 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 4914 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 4915 << "0 >" << "false" << HasEnumType(E->getRHS()) 4916 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 4917 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 4918 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 4919 << "0 <=" << "true" << HasEnumType(E->getRHS()) 4920 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 4921 } 4922 } 4923 4924 static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, 4925 Expr *Constant, Expr *Other, 4926 llvm::APSInt Value, 4927 bool RhsConstant) { 4928 // Disable warning in template instantiations. 4929 if (!S.ActiveTemplateInstantiations.empty()) 4930 return; 4931 4932 // 0 values are handled later by CheckTrivialUnsignedComparison(). 4933 if (Value == 0) 4934 return; 4935 4936 BinaryOperatorKind op = E->getOpcode(); 4937 QualType OtherT = Other->getType(); 4938 QualType ConstantT = Constant->getType(); 4939 QualType CommonT = E->getLHS()->getType(); 4940 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 4941 return; 4942 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) 4943 && "comparison with non-integer type"); 4944 4945 bool ConstantSigned = ConstantT->isSignedIntegerType(); 4946 bool CommonSigned = CommonT->isSignedIntegerType(); 4947 4948 bool EqualityOnly = false; 4949 4950 // TODO: Investigate using GetExprRange() to get tighter bounds on 4951 // on the bit ranges. 4952 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 4953 unsigned OtherWidth = OtherRange.Width; 4954 4955 if (CommonSigned) { 4956 // The common type is signed, therefore no signed to unsigned conversion. 4957 if (!OtherRange.NonNegative) { 4958 // Check that the constant is representable in type OtherT. 4959 if (ConstantSigned) { 4960 if (OtherWidth >= Value.getMinSignedBits()) 4961 return; 4962 } else { // !ConstantSigned 4963 if (OtherWidth >= Value.getActiveBits() + 1) 4964 return; 4965 } 4966 } else { // !OtherSigned 4967 // Check that the constant is representable in type OtherT. 4968 // Negative values are out of range. 4969 if (ConstantSigned) { 4970 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 4971 return; 4972 } else { // !ConstantSigned 4973 if (OtherWidth >= Value.getActiveBits()) 4974 return; 4975 } 4976 } 4977 } else { // !CommonSigned 4978 if (OtherRange.NonNegative) { 4979 if (OtherWidth >= Value.getActiveBits()) 4980 return; 4981 } else if (!OtherRange.NonNegative && !ConstantSigned) { 4982 // Check to see if the constant is representable in OtherT. 4983 if (OtherWidth > Value.getActiveBits()) 4984 return; 4985 // Check to see if the constant is equivalent to a negative value 4986 // cast to CommonT. 4987 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) && 4988 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 4989 return; 4990 // The constant value rests between values that OtherT can represent after 4991 // conversion. Relational comparison still works, but equality 4992 // comparisons will be tautological. 4993 EqualityOnly = true; 4994 } else { // OtherSigned && ConstantSigned 4995 assert(0 && "Two signed types converted to unsigned types."); 4996 } 4997 } 4998 4999 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 5000 5001 bool IsTrue = true; 5002 if (op == BO_EQ || op == BO_NE) { 5003 IsTrue = op == BO_NE; 5004 } else if (EqualityOnly) { 5005 return; 5006 } else if (RhsConstant) { 5007 if (op == BO_GT || op == BO_GE) 5008 IsTrue = !PositiveConstant; 5009 else // op == BO_LT || op == BO_LE 5010 IsTrue = PositiveConstant; 5011 } else { 5012 if (op == BO_LT || op == BO_LE) 5013 IsTrue = !PositiveConstant; 5014 else // op == BO_GT || op == BO_GE 5015 IsTrue = PositiveConstant; 5016 } 5017 5018 // If this is a comparison to an enum constant, include that 5019 // constant in the diagnostic. 5020 const EnumConstantDecl *ED = 0; 5021 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 5022 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 5023 5024 SmallString<64> PrettySourceValue; 5025 llvm::raw_svector_ostream OS(PrettySourceValue); 5026 if (ED) 5027 OS << '\'' << *ED << "' (" << Value << ")"; 5028 else 5029 OS << Value; 5030 5031 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 5032 S.PDiag(diag::warn_out_of_range_compare) 5033 << OS.str() << OtherT << IsTrue 5034 << E->getLHS()->getSourceRange() 5035 << E->getRHS()->getSourceRange()); 5036 } 5037 5038 /// Analyze the operands of the given comparison. Implements the 5039 /// fallback case from AnalyzeComparison. 5040 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 5041 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 5042 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 5043 } 5044 5045 /// \brief Implements -Wsign-compare. 5046 /// 5047 /// \param E the binary operator to check for warnings 5048 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 5049 // The type the comparison is being performed in. 5050 QualType T = E->getLHS()->getType(); 5051 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()) 5052 && "comparison with mismatched types"); 5053 if (E->isValueDependent()) 5054 return AnalyzeImpConvsInComparison(S, E); 5055 5056 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 5057 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 5058 5059 bool IsComparisonConstant = false; 5060 5061 // Check whether an integer constant comparison results in a value 5062 // of 'true' or 'false'. 5063 if (T->isIntegralType(S.Context)) { 5064 llvm::APSInt RHSValue; 5065 bool IsRHSIntegralLiteral = 5066 RHS->isIntegerConstantExpr(RHSValue, S.Context); 5067 llvm::APSInt LHSValue; 5068 bool IsLHSIntegralLiteral = 5069 LHS->isIntegerConstantExpr(LHSValue, S.Context); 5070 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 5071 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 5072 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 5073 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 5074 else 5075 IsComparisonConstant = 5076 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 5077 } else if (!T->hasUnsignedIntegerRepresentation()) 5078 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 5079 5080 // We don't do anything special if this isn't an unsigned integral 5081 // comparison: we're only interested in integral comparisons, and 5082 // signed comparisons only happen in cases we don't care to warn about. 5083 // 5084 // We also don't care about value-dependent expressions or expressions 5085 // whose result is a constant. 5086 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 5087 return AnalyzeImpConvsInComparison(S, E); 5088 5089 // Check to see if one of the (unmodified) operands is of different 5090 // signedness. 5091 Expr *signedOperand, *unsignedOperand; 5092 if (LHS->getType()->hasSignedIntegerRepresentation()) { 5093 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 5094 "unsigned comparison between two signed integer expressions?"); 5095 signedOperand = LHS; 5096 unsignedOperand = RHS; 5097 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 5098 signedOperand = RHS; 5099 unsignedOperand = LHS; 5100 } else { 5101 CheckTrivialUnsignedComparison(S, E); 5102 return AnalyzeImpConvsInComparison(S, E); 5103 } 5104 5105 // Otherwise, calculate the effective range of the signed operand. 5106 IntRange signedRange = GetExprRange(S.Context, signedOperand); 5107 5108 // Go ahead and analyze implicit conversions in the operands. Note 5109 // that we skip the implicit conversions on both sides. 5110 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 5111 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 5112 5113 // If the signed range is non-negative, -Wsign-compare won't fire, 5114 // but we should still check for comparisons which are always true 5115 // or false. 5116 if (signedRange.NonNegative) 5117 return CheckTrivialUnsignedComparison(S, E); 5118 5119 // For (in)equality comparisons, if the unsigned operand is a 5120 // constant which cannot collide with a overflowed signed operand, 5121 // then reinterpreting the signed operand as unsigned will not 5122 // change the result of the comparison. 5123 if (E->isEqualityOp()) { 5124 unsigned comparisonWidth = S.Context.getIntWidth(T); 5125 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 5126 5127 // We should never be unable to prove that the unsigned operand is 5128 // non-negative. 5129 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 5130 5131 if (unsignedRange.Width < comparisonWidth) 5132 return; 5133 } 5134 5135 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 5136 S.PDiag(diag::warn_mixed_sign_comparison) 5137 << LHS->getType() << RHS->getType() 5138 << LHS->getSourceRange() << RHS->getSourceRange()); 5139 } 5140 5141 /// Analyzes an attempt to assign the given value to a bitfield. 5142 /// 5143 /// Returns true if there was something fishy about the attempt. 5144 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 5145 SourceLocation InitLoc) { 5146 assert(Bitfield->isBitField()); 5147 if (Bitfield->isInvalidDecl()) 5148 return false; 5149 5150 // White-list bool bitfields. 5151 if (Bitfield->getType()->isBooleanType()) 5152 return false; 5153 5154 // Ignore value- or type-dependent expressions. 5155 if (Bitfield->getBitWidth()->isValueDependent() || 5156 Bitfield->getBitWidth()->isTypeDependent() || 5157 Init->isValueDependent() || 5158 Init->isTypeDependent()) 5159 return false; 5160 5161 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 5162 5163 llvm::APSInt Value; 5164 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 5165 return false; 5166 5167 unsigned OriginalWidth = Value.getBitWidth(); 5168 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 5169 5170 if (OriginalWidth <= FieldWidth) 5171 return false; 5172 5173 // Compute the value which the bitfield will contain. 5174 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 5175 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType()); 5176 5177 // Check whether the stored value is equal to the original value. 5178 TruncatedValue = TruncatedValue.extend(OriginalWidth); 5179 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 5180 return false; 5181 5182 // Special-case bitfields of width 1: booleans are naturally 0/1, and 5183 // therefore don't strictly fit into a signed bitfield of width 1. 5184 if (FieldWidth == 1 && Value == 1) 5185 return false; 5186 5187 std::string PrettyValue = Value.toString(10); 5188 std::string PrettyTrunc = TruncatedValue.toString(10); 5189 5190 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 5191 << PrettyValue << PrettyTrunc << OriginalInit->getType() 5192 << Init->getSourceRange(); 5193 5194 return true; 5195 } 5196 5197 /// Analyze the given simple or compound assignment for warning-worthy 5198 /// operations. 5199 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 5200 // Just recurse on the LHS. 5201 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 5202 5203 // We want to recurse on the RHS as normal unless we're assigning to 5204 // a bitfield. 5205 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 5206 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 5207 E->getOperatorLoc())) { 5208 // Recurse, ignoring any implicit conversions on the RHS. 5209 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 5210 E->getOperatorLoc()); 5211 } 5212 } 5213 5214 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 5215 } 5216 5217 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 5218 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 5219 SourceLocation CContext, unsigned diag, 5220 bool pruneControlFlow = false) { 5221 if (pruneControlFlow) { 5222 S.DiagRuntimeBehavior(E->getExprLoc(), E, 5223 S.PDiag(diag) 5224 << SourceType << T << E->getSourceRange() 5225 << SourceRange(CContext)); 5226 return; 5227 } 5228 S.Diag(E->getExprLoc(), diag) 5229 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 5230 } 5231 5232 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 5233 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 5234 SourceLocation CContext, unsigned diag, 5235 bool pruneControlFlow = false) { 5236 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 5237 } 5238 5239 /// Diagnose an implicit cast from a literal expression. Does not warn when the 5240 /// cast wouldn't lose information. 5241 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T, 5242 SourceLocation CContext) { 5243 // Try to convert the literal exactly to an integer. If we can, don't warn. 5244 bool isExact = false; 5245 const llvm::APFloat &Value = FL->getValue(); 5246 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 5247 T->hasUnsignedIntegerRepresentation()); 5248 if (Value.convertToInteger(IntegerValue, 5249 llvm::APFloat::rmTowardZero, &isExact) 5250 == llvm::APFloat::opOK && isExact) 5251 return; 5252 5253 // FIXME: Force the precision of the source value down so we don't print 5254 // digits which are usually useless (we don't really care here if we 5255 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 5256 // would automatically print the shortest representation, but it's a bit 5257 // tricky to implement. 5258 SmallString<16> PrettySourceValue; 5259 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 5260 precision = (precision * 59 + 195) / 196; 5261 Value.toString(PrettySourceValue, precision); 5262 5263 SmallString<16> PrettyTargetValue; 5264 if (T->isSpecificBuiltinType(BuiltinType::Bool)) 5265 PrettyTargetValue = IntegerValue == 0 ? "false" : "true"; 5266 else 5267 IntegerValue.toString(PrettyTargetValue); 5268 5269 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer) 5270 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue 5271 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext); 5272 } 5273 5274 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 5275 if (!Range.Width) return "0"; 5276 5277 llvm::APSInt ValueInRange = Value; 5278 ValueInRange.setIsSigned(!Range.NonNegative); 5279 ValueInRange = ValueInRange.trunc(Range.Width); 5280 return ValueInRange.toString(10); 5281 } 5282 5283 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 5284 if (!isa<ImplicitCastExpr>(Ex)) 5285 return false; 5286 5287 Expr *InnerE = Ex->IgnoreParenImpCasts(); 5288 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 5289 const Type *Source = 5290 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 5291 if (Target->isDependentType()) 5292 return false; 5293 5294 const BuiltinType *FloatCandidateBT = 5295 dyn_cast<BuiltinType>(ToBool ? Source : Target); 5296 const Type *BoolCandidateType = ToBool ? Target : Source; 5297 5298 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 5299 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 5300 } 5301 5302 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 5303 SourceLocation CC) { 5304 unsigned NumArgs = TheCall->getNumArgs(); 5305 for (unsigned i = 0; i < NumArgs; ++i) { 5306 Expr *CurrA = TheCall->getArg(i); 5307 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 5308 continue; 5309 5310 bool IsSwapped = ((i > 0) && 5311 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 5312 IsSwapped |= ((i < (NumArgs - 1)) && 5313 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 5314 if (IsSwapped) { 5315 // Warn on this floating-point to bool conversion. 5316 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 5317 CurrA->getType(), CC, 5318 diag::warn_impcast_floating_point_to_bool); 5319 } 5320 } 5321 } 5322 5323 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 5324 SourceLocation CC, bool *ICContext = 0) { 5325 if (E->isTypeDependent() || E->isValueDependent()) return; 5326 5327 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 5328 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 5329 if (Source == Target) return; 5330 if (Target->isDependentType()) return; 5331 5332 // If the conversion context location is invalid don't complain. We also 5333 // don't want to emit a warning if the issue occurs from the expansion of 5334 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 5335 // delay this check as long as possible. Once we detect we are in that 5336 // scenario, we just return. 5337 if (CC.isInvalid()) 5338 return; 5339 5340 // Diagnose implicit casts to bool. 5341 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 5342 if (isa<StringLiteral>(E)) 5343 // Warn on string literal to bool. Checks for string literals in logical 5344 // and expressions, for instance, assert(0 && "error here"), are 5345 // prevented by a check in AnalyzeImplicitConversions(). 5346 return DiagnoseImpCast(S, E, T, CC, 5347 diag::warn_impcast_string_literal_to_bool); 5348 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 5349 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 5350 // This covers the literal expressions that evaluate to Objective-C 5351 // objects. 5352 return DiagnoseImpCast(S, E, T, CC, 5353 diag::warn_impcast_objective_c_literal_to_bool); 5354 } 5355 if (Source->isFunctionType()) { 5356 // Warn on function to bool. Checks free functions and static member 5357 // functions. Weakly imported functions are excluded from the check, 5358 // since it's common to test their value to check whether the linker 5359 // found a definition for them. 5360 ValueDecl *D = 0; 5361 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) { 5362 D = R->getDecl(); 5363 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 5364 D = M->getMemberDecl(); 5365 } 5366 5367 if (D && !D->isWeak()) { 5368 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) { 5369 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool) 5370 << F << E->getSourceRange() << SourceRange(CC); 5371 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence) 5372 << FixItHint::CreateInsertion(E->getExprLoc(), "&"); 5373 QualType ReturnType; 5374 UnresolvedSet<4> NonTemplateOverloads; 5375 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 5376 if (!ReturnType.isNull() 5377 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 5378 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call) 5379 << FixItHint::CreateInsertion( 5380 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()"); 5381 return; 5382 } 5383 } 5384 } 5385 } 5386 5387 // Strip vector types. 5388 if (isa<VectorType>(Source)) { 5389 if (!isa<VectorType>(Target)) { 5390 if (S.SourceMgr.isInSystemMacro(CC)) 5391 return; 5392 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 5393 } 5394 5395 // If the vector cast is cast between two vectors of the same size, it is 5396 // a bitcast, not a conversion. 5397 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 5398 return; 5399 5400 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 5401 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 5402 } 5403 5404 // Strip complex types. 5405 if (isa<ComplexType>(Source)) { 5406 if (!isa<ComplexType>(Target)) { 5407 if (S.SourceMgr.isInSystemMacro(CC)) 5408 return; 5409 5410 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 5411 } 5412 5413 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 5414 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 5415 } 5416 5417 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 5418 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 5419 5420 // If the source is floating point... 5421 if (SourceBT && SourceBT->isFloatingPoint()) { 5422 // ...and the target is floating point... 5423 if (TargetBT && TargetBT->isFloatingPoint()) { 5424 // ...then warn if we're dropping FP rank. 5425 5426 // Builtin FP kinds are ordered by increasing FP rank. 5427 if (SourceBT->getKind() > TargetBT->getKind()) { 5428 // Don't warn about float constants that are precisely 5429 // representable in the target type. 5430 Expr::EvalResult result; 5431 if (E->EvaluateAsRValue(result, S.Context)) { 5432 // Value might be a float, a float vector, or a float complex. 5433 if (IsSameFloatAfterCast(result.Val, 5434 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 5435 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 5436 return; 5437 } 5438 5439 if (S.SourceMgr.isInSystemMacro(CC)) 5440 return; 5441 5442 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 5443 } 5444 return; 5445 } 5446 5447 // If the target is integral, always warn. 5448 if (TargetBT && TargetBT->isInteger()) { 5449 if (S.SourceMgr.isInSystemMacro(CC)) 5450 return; 5451 5452 Expr *InnerE = E->IgnoreParenImpCasts(); 5453 // We also want to warn on, e.g., "int i = -1.234" 5454 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 5455 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 5456 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 5457 5458 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) { 5459 DiagnoseFloatingLiteralImpCast(S, FL, T, CC); 5460 } else { 5461 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer); 5462 } 5463 } 5464 5465 // If the target is bool, warn if expr is a function or method call. 5466 if (Target->isSpecificBuiltinType(BuiltinType::Bool) && 5467 isa<CallExpr>(E)) { 5468 // Check last argument of function call to see if it is an 5469 // implicit cast from a type matching the type the result 5470 // is being cast to. 5471 CallExpr *CEx = cast<CallExpr>(E); 5472 unsigned NumArgs = CEx->getNumArgs(); 5473 if (NumArgs > 0) { 5474 Expr *LastA = CEx->getArg(NumArgs - 1); 5475 Expr *InnerE = LastA->IgnoreParenImpCasts(); 5476 const Type *InnerType = 5477 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 5478 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) { 5479 // Warn on this floating-point to bool conversion 5480 DiagnoseImpCast(S, E, T, CC, 5481 diag::warn_impcast_floating_point_to_bool); 5482 } 5483 } 5484 } 5485 return; 5486 } 5487 5488 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) 5489 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType() 5490 && !Target->isBlockPointerType() && !Target->isMemberPointerType() 5491 && Target->isScalarType() && !Target->isNullPtrType()) { 5492 SourceLocation Loc = E->getSourceRange().getBegin(); 5493 if (Loc.isMacroID()) 5494 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 5495 if (!Loc.isMacroID() || CC.isMacroID()) 5496 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 5497 << T << clang::SourceRange(CC) 5498 << FixItHint::CreateReplacement(Loc, 5499 S.getFixItZeroLiteralForType(T, Loc)); 5500 } 5501 5502 if (!Source->isIntegerType() || !Target->isIntegerType()) 5503 return; 5504 5505 // TODO: remove this early return once the false positives for constant->bool 5506 // in templates, macros, etc, are reduced or removed. 5507 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 5508 return; 5509 5510 IntRange SourceRange = GetExprRange(S.Context, E); 5511 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 5512 5513 if (SourceRange.Width > TargetRange.Width) { 5514 // If the source is a constant, use a default-on diagnostic. 5515 // TODO: this should happen for bitfield stores, too. 5516 llvm::APSInt Value(32); 5517 if (E->isIntegerConstantExpr(Value, S.Context)) { 5518 if (S.SourceMgr.isInSystemMacro(CC)) 5519 return; 5520 5521 std::string PrettySourceValue = Value.toString(10); 5522 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 5523 5524 S.DiagRuntimeBehavior(E->getExprLoc(), E, 5525 S.PDiag(diag::warn_impcast_integer_precision_constant) 5526 << PrettySourceValue << PrettyTargetValue 5527 << E->getType() << T << E->getSourceRange() 5528 << clang::SourceRange(CC)); 5529 return; 5530 } 5531 5532 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 5533 if (S.SourceMgr.isInSystemMacro(CC)) 5534 return; 5535 5536 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 5537 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 5538 /* pruneControlFlow */ true); 5539 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 5540 } 5541 5542 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 5543 (!TargetRange.NonNegative && SourceRange.NonNegative && 5544 SourceRange.Width == TargetRange.Width)) { 5545 5546 if (S.SourceMgr.isInSystemMacro(CC)) 5547 return; 5548 5549 unsigned DiagID = diag::warn_impcast_integer_sign; 5550 5551 // Traditionally, gcc has warned about this under -Wsign-compare. 5552 // We also want to warn about it in -Wconversion. 5553 // So if -Wconversion is off, use a completely identical diagnostic 5554 // in the sign-compare group. 5555 // The conditional-checking code will 5556 if (ICContext) { 5557 DiagID = diag::warn_impcast_integer_sign_conditional; 5558 *ICContext = true; 5559 } 5560 5561 return DiagnoseImpCast(S, E, T, CC, DiagID); 5562 } 5563 5564 // Diagnose conversions between different enumeration types. 5565 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 5566 // type, to give us better diagnostics. 5567 QualType SourceType = E->getType(); 5568 if (!S.getLangOpts().CPlusPlus) { 5569 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 5570 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 5571 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 5572 SourceType = S.Context.getTypeDeclType(Enum); 5573 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 5574 } 5575 } 5576 5577 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 5578 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 5579 if (SourceEnum->getDecl()->hasNameForLinkage() && 5580 TargetEnum->getDecl()->hasNameForLinkage() && 5581 SourceEnum != TargetEnum) { 5582 if (S.SourceMgr.isInSystemMacro(CC)) 5583 return; 5584 5585 return DiagnoseImpCast(S, E, SourceType, T, CC, 5586 diag::warn_impcast_different_enum_types); 5587 } 5588 5589 return; 5590 } 5591 5592 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 5593 SourceLocation CC, QualType T); 5594 5595 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 5596 SourceLocation CC, bool &ICContext) { 5597 E = E->IgnoreParenImpCasts(); 5598 5599 if (isa<ConditionalOperator>(E)) 5600 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 5601 5602 AnalyzeImplicitConversions(S, E, CC); 5603 if (E->getType() != T) 5604 return CheckImplicitConversion(S, E, T, CC, &ICContext); 5605 return; 5606 } 5607 5608 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 5609 SourceLocation CC, QualType T) { 5610 AnalyzeImplicitConversions(S, E->getCond(), CC); 5611 5612 bool Suspicious = false; 5613 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 5614 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 5615 5616 // If -Wconversion would have warned about either of the candidates 5617 // for a signedness conversion to the context type... 5618 if (!Suspicious) return; 5619 5620 // ...but it's currently ignored... 5621 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional, 5622 CC)) 5623 return; 5624 5625 // ...then check whether it would have warned about either of the 5626 // candidates for a signedness conversion to the condition type. 5627 if (E->getType() == T) return; 5628 5629 Suspicious = false; 5630 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 5631 E->getType(), CC, &Suspicious); 5632 if (!Suspicious) 5633 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 5634 E->getType(), CC, &Suspicious); 5635 } 5636 5637 /// AnalyzeImplicitConversions - Find and report any interesting 5638 /// implicit conversions in the given expression. There are a couple 5639 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 5640 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 5641 QualType T = OrigE->getType(); 5642 Expr *E = OrigE->IgnoreParenImpCasts(); 5643 5644 if (E->isTypeDependent() || E->isValueDependent()) 5645 return; 5646 5647 // For conditional operators, we analyze the arguments as if they 5648 // were being fed directly into the output. 5649 if (isa<ConditionalOperator>(E)) { 5650 ConditionalOperator *CO = cast<ConditionalOperator>(E); 5651 CheckConditionalOperator(S, CO, CC, T); 5652 return; 5653 } 5654 5655 // Check implicit argument conversions for function calls. 5656 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 5657 CheckImplicitArgumentConversions(S, Call, CC); 5658 5659 // Go ahead and check any implicit conversions we might have skipped. 5660 // The non-canonical typecheck is just an optimization; 5661 // CheckImplicitConversion will filter out dead implicit conversions. 5662 if (E->getType() != T) 5663 CheckImplicitConversion(S, E, T, CC); 5664 5665 // Now continue drilling into this expression. 5666 5667 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) { 5668 if (POE->getResultExpr()) 5669 E = POE->getResultExpr(); 5670 } 5671 5672 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) 5673 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 5674 5675 // Skip past explicit casts. 5676 if (isa<ExplicitCastExpr>(E)) { 5677 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 5678 return AnalyzeImplicitConversions(S, E, CC); 5679 } 5680 5681 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 5682 // Do a somewhat different check with comparison operators. 5683 if (BO->isComparisonOp()) 5684 return AnalyzeComparison(S, BO); 5685 5686 // And with simple assignments. 5687 if (BO->getOpcode() == BO_Assign) 5688 return AnalyzeAssignment(S, BO); 5689 } 5690 5691 // These break the otherwise-useful invariant below. Fortunately, 5692 // we don't really need to recurse into them, because any internal 5693 // expressions should have been analyzed already when they were 5694 // built into statements. 5695 if (isa<StmtExpr>(E)) return; 5696 5697 // Don't descend into unevaluated contexts. 5698 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 5699 5700 // Now just recurse over the expression's children. 5701 CC = E->getExprLoc(); 5702 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 5703 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 5704 for (Stmt::child_range I = E->children(); I; ++I) { 5705 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I); 5706 if (!ChildExpr) 5707 continue; 5708 5709 if (IsLogicalAndOperator && 5710 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 5711 // Ignore checking string literals that are in logical and operators. 5712 // This is a common pattern for asserts. 5713 continue; 5714 AnalyzeImplicitConversions(S, ChildExpr, CC); 5715 } 5716 } 5717 5718 } // end anonymous namespace 5719 5720 /// Diagnoses "dangerous" implicit conversions within the given 5721 /// expression (which is a full expression). Implements -Wconversion 5722 /// and -Wsign-compare. 5723 /// 5724 /// \param CC the "context" location of the implicit conversion, i.e. 5725 /// the most location of the syntactic entity requiring the implicit 5726 /// conversion 5727 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 5728 // Don't diagnose in unevaluated contexts. 5729 if (isUnevaluatedContext()) 5730 return; 5731 5732 // Don't diagnose for value- or type-dependent expressions. 5733 if (E->isTypeDependent() || E->isValueDependent()) 5734 return; 5735 5736 // Check for array bounds violations in cases where the check isn't triggered 5737 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 5738 // ArraySubscriptExpr is on the RHS of a variable initialization. 5739 CheckArrayAccess(E); 5740 5741 // This is not the right CC for (e.g.) a variable initialization. 5742 AnalyzeImplicitConversions(*this, E, CC); 5743 } 5744 5745 /// Diagnose when expression is an integer constant expression and its evaluation 5746 /// results in integer overflow 5747 void Sema::CheckForIntOverflow (Expr *E) { 5748 if (isa<BinaryOperator>(E->IgnoreParens())) 5749 E->EvaluateForOverflow(Context); 5750 } 5751 5752 namespace { 5753 /// \brief Visitor for expressions which looks for unsequenced operations on the 5754 /// same object. 5755 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 5756 typedef EvaluatedExprVisitor<SequenceChecker> Base; 5757 5758 /// \brief A tree of sequenced regions within an expression. Two regions are 5759 /// unsequenced if one is an ancestor or a descendent of the other. When we 5760 /// finish processing an expression with sequencing, such as a comma 5761 /// expression, we fold its tree nodes into its parent, since they are 5762 /// unsequenced with respect to nodes we will visit later. 5763 class SequenceTree { 5764 struct Value { 5765 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 5766 unsigned Parent : 31; 5767 bool Merged : 1; 5768 }; 5769 SmallVector<Value, 8> Values; 5770 5771 public: 5772 /// \brief A region within an expression which may be sequenced with respect 5773 /// to some other region. 5774 class Seq { 5775 explicit Seq(unsigned N) : Index(N) {} 5776 unsigned Index; 5777 friend class SequenceTree; 5778 public: 5779 Seq() : Index(0) {} 5780 }; 5781 5782 SequenceTree() { Values.push_back(Value(0)); } 5783 Seq root() const { return Seq(0); } 5784 5785 /// \brief Create a new sequence of operations, which is an unsequenced 5786 /// subset of \p Parent. This sequence of operations is sequenced with 5787 /// respect to other children of \p Parent. 5788 Seq allocate(Seq Parent) { 5789 Values.push_back(Value(Parent.Index)); 5790 return Seq(Values.size() - 1); 5791 } 5792 5793 /// \brief Merge a sequence of operations into its parent. 5794 void merge(Seq S) { 5795 Values[S.Index].Merged = true; 5796 } 5797 5798 /// \brief Determine whether two operations are unsequenced. This operation 5799 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 5800 /// should have been merged into its parent as appropriate. 5801 bool isUnsequenced(Seq Cur, Seq Old) { 5802 unsigned C = representative(Cur.Index); 5803 unsigned Target = representative(Old.Index); 5804 while (C >= Target) { 5805 if (C == Target) 5806 return true; 5807 C = Values[C].Parent; 5808 } 5809 return false; 5810 } 5811 5812 private: 5813 /// \brief Pick a representative for a sequence. 5814 unsigned representative(unsigned K) { 5815 if (Values[K].Merged) 5816 // Perform path compression as we go. 5817 return Values[K].Parent = representative(Values[K].Parent); 5818 return K; 5819 } 5820 }; 5821 5822 /// An object for which we can track unsequenced uses. 5823 typedef NamedDecl *Object; 5824 5825 /// Different flavors of object usage which we track. We only track the 5826 /// least-sequenced usage of each kind. 5827 enum UsageKind { 5828 /// A read of an object. Multiple unsequenced reads are OK. 5829 UK_Use, 5830 /// A modification of an object which is sequenced before the value 5831 /// computation of the expression, such as ++n in C++. 5832 UK_ModAsValue, 5833 /// A modification of an object which is not sequenced before the value 5834 /// computation of the expression, such as n++. 5835 UK_ModAsSideEffect, 5836 5837 UK_Count = UK_ModAsSideEffect + 1 5838 }; 5839 5840 struct Usage { 5841 Usage() : Use(0), Seq() {} 5842 Expr *Use; 5843 SequenceTree::Seq Seq; 5844 }; 5845 5846 struct UsageInfo { 5847 UsageInfo() : Diagnosed(false) {} 5848 Usage Uses[UK_Count]; 5849 /// Have we issued a diagnostic for this variable already? 5850 bool Diagnosed; 5851 }; 5852 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 5853 5854 Sema &SemaRef; 5855 /// Sequenced regions within the expression. 5856 SequenceTree Tree; 5857 /// Declaration modifications and references which we have seen. 5858 UsageInfoMap UsageMap; 5859 /// The region we are currently within. 5860 SequenceTree::Seq Region; 5861 /// Filled in with declarations which were modified as a side-effect 5862 /// (that is, post-increment operations). 5863 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 5864 /// Expressions to check later. We defer checking these to reduce 5865 /// stack usage. 5866 SmallVectorImpl<Expr *> &WorkList; 5867 5868 /// RAII object wrapping the visitation of a sequenced subexpression of an 5869 /// expression. At the end of this process, the side-effects of the evaluation 5870 /// become sequenced with respect to the value computation of the result, so 5871 /// we downgrade any UK_ModAsSideEffect within the evaluation to 5872 /// UK_ModAsValue. 5873 struct SequencedSubexpression { 5874 SequencedSubexpression(SequenceChecker &Self) 5875 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 5876 Self.ModAsSideEffect = &ModAsSideEffect; 5877 } 5878 ~SequencedSubexpression() { 5879 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) { 5880 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first]; 5881 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second; 5882 Self.addUsage(U, ModAsSideEffect[I].first, 5883 ModAsSideEffect[I].second.Use, UK_ModAsValue); 5884 } 5885 Self.ModAsSideEffect = OldModAsSideEffect; 5886 } 5887 5888 SequenceChecker &Self; 5889 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 5890 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 5891 }; 5892 5893 /// RAII object wrapping the visitation of a subexpression which we might 5894 /// choose to evaluate as a constant. If any subexpression is evaluated and 5895 /// found to be non-constant, this allows us to suppress the evaluation of 5896 /// the outer expression. 5897 class EvaluationTracker { 5898 public: 5899 EvaluationTracker(SequenceChecker &Self) 5900 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 5901 Self.EvalTracker = this; 5902 } 5903 ~EvaluationTracker() { 5904 Self.EvalTracker = Prev; 5905 if (Prev) 5906 Prev->EvalOK &= EvalOK; 5907 } 5908 5909 bool evaluate(const Expr *E, bool &Result) { 5910 if (!EvalOK || E->isValueDependent()) 5911 return false; 5912 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 5913 return EvalOK; 5914 } 5915 5916 private: 5917 SequenceChecker &Self; 5918 EvaluationTracker *Prev; 5919 bool EvalOK; 5920 } *EvalTracker; 5921 5922 /// \brief Find the object which is produced by the specified expression, 5923 /// if any. 5924 Object getObject(Expr *E, bool Mod) const { 5925 E = E->IgnoreParenCasts(); 5926 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 5927 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 5928 return getObject(UO->getSubExpr(), Mod); 5929 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 5930 if (BO->getOpcode() == BO_Comma) 5931 return getObject(BO->getRHS(), Mod); 5932 if (Mod && BO->isAssignmentOp()) 5933 return getObject(BO->getLHS(), Mod); 5934 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 5935 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 5936 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 5937 return ME->getMemberDecl(); 5938 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 5939 // FIXME: If this is a reference, map through to its value. 5940 return DRE->getDecl(); 5941 return 0; 5942 } 5943 5944 /// \brief Note that an object was modified or used by an expression. 5945 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 5946 Usage &U = UI.Uses[UK]; 5947 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 5948 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 5949 ModAsSideEffect->push_back(std::make_pair(O, U)); 5950 U.Use = Ref; 5951 U.Seq = Region; 5952 } 5953 } 5954 /// \brief Check whether a modification or use conflicts with a prior usage. 5955 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 5956 bool IsModMod) { 5957 if (UI.Diagnosed) 5958 return; 5959 5960 const Usage &U = UI.Uses[OtherKind]; 5961 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 5962 return; 5963 5964 Expr *Mod = U.Use; 5965 Expr *ModOrUse = Ref; 5966 if (OtherKind == UK_Use) 5967 std::swap(Mod, ModOrUse); 5968 5969 SemaRef.Diag(Mod->getExprLoc(), 5970 IsModMod ? diag::warn_unsequenced_mod_mod 5971 : diag::warn_unsequenced_mod_use) 5972 << O << SourceRange(ModOrUse->getExprLoc()); 5973 UI.Diagnosed = true; 5974 } 5975 5976 void notePreUse(Object O, Expr *Use) { 5977 UsageInfo &U = UsageMap[O]; 5978 // Uses conflict with other modifications. 5979 checkUsage(O, U, Use, UK_ModAsValue, false); 5980 } 5981 void notePostUse(Object O, Expr *Use) { 5982 UsageInfo &U = UsageMap[O]; 5983 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 5984 addUsage(U, O, Use, UK_Use); 5985 } 5986 5987 void notePreMod(Object O, Expr *Mod) { 5988 UsageInfo &U = UsageMap[O]; 5989 // Modifications conflict with other modifications and with uses. 5990 checkUsage(O, U, Mod, UK_ModAsValue, true); 5991 checkUsage(O, U, Mod, UK_Use, false); 5992 } 5993 void notePostMod(Object O, Expr *Use, UsageKind UK) { 5994 UsageInfo &U = UsageMap[O]; 5995 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 5996 addUsage(U, O, Use, UK); 5997 } 5998 5999 public: 6000 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 6001 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0), 6002 WorkList(WorkList), EvalTracker(0) { 6003 Visit(E); 6004 } 6005 6006 void VisitStmt(Stmt *S) { 6007 // Skip all statements which aren't expressions for now. 6008 } 6009 6010 void VisitExpr(Expr *E) { 6011 // By default, just recurse to evaluated subexpressions. 6012 Base::VisitStmt(E); 6013 } 6014 6015 void VisitCastExpr(CastExpr *E) { 6016 Object O = Object(); 6017 if (E->getCastKind() == CK_LValueToRValue) 6018 O = getObject(E->getSubExpr(), false); 6019 6020 if (O) 6021 notePreUse(O, E); 6022 VisitExpr(E); 6023 if (O) 6024 notePostUse(O, E); 6025 } 6026 6027 void VisitBinComma(BinaryOperator *BO) { 6028 // C++11 [expr.comma]p1: 6029 // Every value computation and side effect associated with the left 6030 // expression is sequenced before every value computation and side 6031 // effect associated with the right expression. 6032 SequenceTree::Seq LHS = Tree.allocate(Region); 6033 SequenceTree::Seq RHS = Tree.allocate(Region); 6034 SequenceTree::Seq OldRegion = Region; 6035 6036 { 6037 SequencedSubexpression SeqLHS(*this); 6038 Region = LHS; 6039 Visit(BO->getLHS()); 6040 } 6041 6042 Region = RHS; 6043 Visit(BO->getRHS()); 6044 6045 Region = OldRegion; 6046 6047 // Forget that LHS and RHS are sequenced. They are both unsequenced 6048 // with respect to other stuff. 6049 Tree.merge(LHS); 6050 Tree.merge(RHS); 6051 } 6052 6053 void VisitBinAssign(BinaryOperator *BO) { 6054 // The modification is sequenced after the value computation of the LHS 6055 // and RHS, so check it before inspecting the operands and update the 6056 // map afterwards. 6057 Object O = getObject(BO->getLHS(), true); 6058 if (!O) 6059 return VisitExpr(BO); 6060 6061 notePreMod(O, BO); 6062 6063 // C++11 [expr.ass]p7: 6064 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 6065 // only once. 6066 // 6067 // Therefore, for a compound assignment operator, O is considered used 6068 // everywhere except within the evaluation of E1 itself. 6069 if (isa<CompoundAssignOperator>(BO)) 6070 notePreUse(O, BO); 6071 6072 Visit(BO->getLHS()); 6073 6074 if (isa<CompoundAssignOperator>(BO)) 6075 notePostUse(O, BO); 6076 6077 Visit(BO->getRHS()); 6078 6079 // C++11 [expr.ass]p1: 6080 // the assignment is sequenced [...] before the value computation of the 6081 // assignment expression. 6082 // C11 6.5.16/3 has no such rule. 6083 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 6084 : UK_ModAsSideEffect); 6085 } 6086 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 6087 VisitBinAssign(CAO); 6088 } 6089 6090 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 6091 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 6092 void VisitUnaryPreIncDec(UnaryOperator *UO) { 6093 Object O = getObject(UO->getSubExpr(), true); 6094 if (!O) 6095 return VisitExpr(UO); 6096 6097 notePreMod(O, UO); 6098 Visit(UO->getSubExpr()); 6099 // C++11 [expr.pre.incr]p1: 6100 // the expression ++x is equivalent to x+=1 6101 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 6102 : UK_ModAsSideEffect); 6103 } 6104 6105 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 6106 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 6107 void VisitUnaryPostIncDec(UnaryOperator *UO) { 6108 Object O = getObject(UO->getSubExpr(), true); 6109 if (!O) 6110 return VisitExpr(UO); 6111 6112 notePreMod(O, UO); 6113 Visit(UO->getSubExpr()); 6114 notePostMod(O, UO, UK_ModAsSideEffect); 6115 } 6116 6117 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 6118 void VisitBinLOr(BinaryOperator *BO) { 6119 // The side-effects of the LHS of an '&&' are sequenced before the 6120 // value computation of the RHS, and hence before the value computation 6121 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 6122 // as if they were unconditionally sequenced. 6123 EvaluationTracker Eval(*this); 6124 { 6125 SequencedSubexpression Sequenced(*this); 6126 Visit(BO->getLHS()); 6127 } 6128 6129 bool Result; 6130 if (Eval.evaluate(BO->getLHS(), Result)) { 6131 if (!Result) 6132 Visit(BO->getRHS()); 6133 } else { 6134 // Check for unsequenced operations in the RHS, treating it as an 6135 // entirely separate evaluation. 6136 // 6137 // FIXME: If there are operations in the RHS which are unsequenced 6138 // with respect to operations outside the RHS, and those operations 6139 // are unconditionally evaluated, diagnose them. 6140 WorkList.push_back(BO->getRHS()); 6141 } 6142 } 6143 void VisitBinLAnd(BinaryOperator *BO) { 6144 EvaluationTracker Eval(*this); 6145 { 6146 SequencedSubexpression Sequenced(*this); 6147 Visit(BO->getLHS()); 6148 } 6149 6150 bool Result; 6151 if (Eval.evaluate(BO->getLHS(), Result)) { 6152 if (Result) 6153 Visit(BO->getRHS()); 6154 } else { 6155 WorkList.push_back(BO->getRHS()); 6156 } 6157 } 6158 6159 // Only visit the condition, unless we can be sure which subexpression will 6160 // be chosen. 6161 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 6162 EvaluationTracker Eval(*this); 6163 { 6164 SequencedSubexpression Sequenced(*this); 6165 Visit(CO->getCond()); 6166 } 6167 6168 bool Result; 6169 if (Eval.evaluate(CO->getCond(), Result)) 6170 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 6171 else { 6172 WorkList.push_back(CO->getTrueExpr()); 6173 WorkList.push_back(CO->getFalseExpr()); 6174 } 6175 } 6176 6177 void VisitCallExpr(CallExpr *CE) { 6178 // C++11 [intro.execution]p15: 6179 // When calling a function [...], every value computation and side effect 6180 // associated with any argument expression, or with the postfix expression 6181 // designating the called function, is sequenced before execution of every 6182 // expression or statement in the body of the function [and thus before 6183 // the value computation of its result]. 6184 SequencedSubexpression Sequenced(*this); 6185 Base::VisitCallExpr(CE); 6186 6187 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 6188 } 6189 6190 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 6191 // This is a call, so all subexpressions are sequenced before the result. 6192 SequencedSubexpression Sequenced(*this); 6193 6194 if (!CCE->isListInitialization()) 6195 return VisitExpr(CCE); 6196 6197 // In C++11, list initializations are sequenced. 6198 SmallVector<SequenceTree::Seq, 32> Elts; 6199 SequenceTree::Seq Parent = Region; 6200 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 6201 E = CCE->arg_end(); 6202 I != E; ++I) { 6203 Region = Tree.allocate(Parent); 6204 Elts.push_back(Region); 6205 Visit(*I); 6206 } 6207 6208 // Forget that the initializers are sequenced. 6209 Region = Parent; 6210 for (unsigned I = 0; I < Elts.size(); ++I) 6211 Tree.merge(Elts[I]); 6212 } 6213 6214 void VisitInitListExpr(InitListExpr *ILE) { 6215 if (!SemaRef.getLangOpts().CPlusPlus11) 6216 return VisitExpr(ILE); 6217 6218 // In C++11, list initializations are sequenced. 6219 SmallVector<SequenceTree::Seq, 32> Elts; 6220 SequenceTree::Seq Parent = Region; 6221 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 6222 Expr *E = ILE->getInit(I); 6223 if (!E) continue; 6224 Region = Tree.allocate(Parent); 6225 Elts.push_back(Region); 6226 Visit(E); 6227 } 6228 6229 // Forget that the initializers are sequenced. 6230 Region = Parent; 6231 for (unsigned I = 0; I < Elts.size(); ++I) 6232 Tree.merge(Elts[I]); 6233 } 6234 }; 6235 } 6236 6237 void Sema::CheckUnsequencedOperations(Expr *E) { 6238 SmallVector<Expr *, 8> WorkList; 6239 WorkList.push_back(E); 6240 while (!WorkList.empty()) { 6241 Expr *Item = WorkList.pop_back_val(); 6242 SequenceChecker(*this, Item, WorkList); 6243 } 6244 } 6245 6246 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 6247 bool IsConstexpr) { 6248 CheckImplicitConversions(E, CheckLoc); 6249 CheckUnsequencedOperations(E); 6250 if (!IsConstexpr && !E->isValueDependent()) 6251 CheckForIntOverflow(E); 6252 } 6253 6254 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 6255 FieldDecl *BitField, 6256 Expr *Init) { 6257 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 6258 } 6259 6260 /// CheckParmsForFunctionDef - Check that the parameters of the given 6261 /// function are appropriate for the definition of a function. This 6262 /// takes care of any checks that cannot be performed on the 6263 /// declaration itself, e.g., that the types of each of the function 6264 /// parameters are complete. 6265 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P, 6266 ParmVarDecl *const *PEnd, 6267 bool CheckParameterNames) { 6268 bool HasInvalidParm = false; 6269 for (; P != PEnd; ++P) { 6270 ParmVarDecl *Param = *P; 6271 6272 // C99 6.7.5.3p4: the parameters in a parameter type list in a 6273 // function declarator that is part of a function definition of 6274 // that function shall not have incomplete type. 6275 // 6276 // This is also C++ [dcl.fct]p6. 6277 if (!Param->isInvalidDecl() && 6278 RequireCompleteType(Param->getLocation(), Param->getType(), 6279 diag::err_typecheck_decl_incomplete_type)) { 6280 Param->setInvalidDecl(); 6281 HasInvalidParm = true; 6282 } 6283 6284 // C99 6.9.1p5: If the declarator includes a parameter type list, the 6285 // declaration of each parameter shall include an identifier. 6286 if (CheckParameterNames && 6287 Param->getIdentifier() == 0 && 6288 !Param->isImplicit() && 6289 !getLangOpts().CPlusPlus) 6290 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 6291 6292 // C99 6.7.5.3p12: 6293 // If the function declarator is not part of a definition of that 6294 // function, parameters may have incomplete type and may use the [*] 6295 // notation in their sequences of declarator specifiers to specify 6296 // variable length array types. 6297 QualType PType = Param->getOriginalType(); 6298 while (const ArrayType *AT = Context.getAsArrayType(PType)) { 6299 if (AT->getSizeModifier() == ArrayType::Star) { 6300 // FIXME: This diagnostic should point the '[*]' if source-location 6301 // information is added for it. 6302 Diag(Param->getLocation(), diag::err_array_star_in_function_definition); 6303 break; 6304 } 6305 PType= AT->getElementType(); 6306 } 6307 6308 // MSVC destroys objects passed by value in the callee. Therefore a 6309 // function definition which takes such a parameter must be able to call the 6310 // object's destructor. However, we don't perform any direct access check 6311 // on the dtor. 6312 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 6313 .getCXXABI() 6314 .areArgsDestroyedLeftToRightInCallee()) { 6315 if (!Param->isInvalidDecl()) { 6316 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 6317 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 6318 if (!ClassDecl->isInvalidDecl() && 6319 !ClassDecl->hasIrrelevantDestructor() && 6320 !ClassDecl->isDependentContext()) { 6321 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 6322 MarkFunctionReferenced(Param->getLocation(), Destructor); 6323 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 6324 } 6325 } 6326 } 6327 } 6328 } 6329 6330 return HasInvalidParm; 6331 } 6332 6333 /// CheckCastAlign - Implements -Wcast-align, which warns when a 6334 /// pointer cast increases the alignment requirements. 6335 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 6336 // This is actually a lot of work to potentially be doing on every 6337 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 6338 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align, 6339 TRange.getBegin()) 6340 == DiagnosticsEngine::Ignored) 6341 return; 6342 6343 // Ignore dependent types. 6344 if (T->isDependentType() || Op->getType()->isDependentType()) 6345 return; 6346 6347 // Require that the destination be a pointer type. 6348 const PointerType *DestPtr = T->getAs<PointerType>(); 6349 if (!DestPtr) return; 6350 6351 // If the destination has alignment 1, we're done. 6352 QualType DestPointee = DestPtr->getPointeeType(); 6353 if (DestPointee->isIncompleteType()) return; 6354 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 6355 if (DestAlign.isOne()) return; 6356 6357 // Require that the source be a pointer type. 6358 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 6359 if (!SrcPtr) return; 6360 QualType SrcPointee = SrcPtr->getPointeeType(); 6361 6362 // Whitelist casts from cv void*. We already implicitly 6363 // whitelisted casts to cv void*, since they have alignment 1. 6364 // Also whitelist casts involving incomplete types, which implicitly 6365 // includes 'void'. 6366 if (SrcPointee->isIncompleteType()) return; 6367 6368 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 6369 if (SrcAlign >= DestAlign) return; 6370 6371 Diag(TRange.getBegin(), diag::warn_cast_align) 6372 << Op->getType() << T 6373 << static_cast<unsigned>(SrcAlign.getQuantity()) 6374 << static_cast<unsigned>(DestAlign.getQuantity()) 6375 << TRange << Op->getSourceRange(); 6376 } 6377 6378 static const Type* getElementType(const Expr *BaseExpr) { 6379 const Type* EltType = BaseExpr->getType().getTypePtr(); 6380 if (EltType->isAnyPointerType()) 6381 return EltType->getPointeeType().getTypePtr(); 6382 else if (EltType->isArrayType()) 6383 return EltType->getBaseElementTypeUnsafe(); 6384 return EltType; 6385 } 6386 6387 /// \brief Check whether this array fits the idiom of a size-one tail padded 6388 /// array member of a struct. 6389 /// 6390 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 6391 /// commonly used to emulate flexible arrays in C89 code. 6392 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size, 6393 const NamedDecl *ND) { 6394 if (Size != 1 || !ND) return false; 6395 6396 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 6397 if (!FD) return false; 6398 6399 // Don't consider sizes resulting from macro expansions or template argument 6400 // substitution to form C89 tail-padded arrays. 6401 6402 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 6403 while (TInfo) { 6404 TypeLoc TL = TInfo->getTypeLoc(); 6405 // Look through typedefs. 6406 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 6407 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 6408 TInfo = TDL->getTypeSourceInfo(); 6409 continue; 6410 } 6411 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 6412 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 6413 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 6414 return false; 6415 } 6416 break; 6417 } 6418 6419 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 6420 if (!RD) return false; 6421 if (RD->isUnion()) return false; 6422 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 6423 if (!CRD->isStandardLayout()) return false; 6424 } 6425 6426 // See if this is the last field decl in the record. 6427 const Decl *D = FD; 6428 while ((D = D->getNextDeclInContext())) 6429 if (isa<FieldDecl>(D)) 6430 return false; 6431 return true; 6432 } 6433 6434 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 6435 const ArraySubscriptExpr *ASE, 6436 bool AllowOnePastEnd, bool IndexNegated) { 6437 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 6438 if (IndexExpr->isValueDependent()) 6439 return; 6440 6441 const Type *EffectiveType = getElementType(BaseExpr); 6442 BaseExpr = BaseExpr->IgnoreParenCasts(); 6443 const ConstantArrayType *ArrayTy = 6444 Context.getAsConstantArrayType(BaseExpr->getType()); 6445 if (!ArrayTy) 6446 return; 6447 6448 llvm::APSInt index; 6449 if (!IndexExpr->EvaluateAsInt(index, Context)) 6450 return; 6451 if (IndexNegated) 6452 index = -index; 6453 6454 const NamedDecl *ND = NULL; 6455 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 6456 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 6457 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 6458 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 6459 6460 if (index.isUnsigned() || !index.isNegative()) { 6461 llvm::APInt size = ArrayTy->getSize(); 6462 if (!size.isStrictlyPositive()) 6463 return; 6464 6465 const Type* BaseType = getElementType(BaseExpr); 6466 if (BaseType != EffectiveType) { 6467 // Make sure we're comparing apples to apples when comparing index to size 6468 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 6469 uint64_t array_typesize = Context.getTypeSize(BaseType); 6470 // Handle ptrarith_typesize being zero, such as when casting to void* 6471 if (!ptrarith_typesize) ptrarith_typesize = 1; 6472 if (ptrarith_typesize != array_typesize) { 6473 // There's a cast to a different size type involved 6474 uint64_t ratio = array_typesize / ptrarith_typesize; 6475 // TODO: Be smarter about handling cases where array_typesize is not a 6476 // multiple of ptrarith_typesize 6477 if (ptrarith_typesize * ratio == array_typesize) 6478 size *= llvm::APInt(size.getBitWidth(), ratio); 6479 } 6480 } 6481 6482 if (size.getBitWidth() > index.getBitWidth()) 6483 index = index.zext(size.getBitWidth()); 6484 else if (size.getBitWidth() < index.getBitWidth()) 6485 size = size.zext(index.getBitWidth()); 6486 6487 // For array subscripting the index must be less than size, but for pointer 6488 // arithmetic also allow the index (offset) to be equal to size since 6489 // computing the next address after the end of the array is legal and 6490 // commonly done e.g. in C++ iterators and range-based for loops. 6491 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 6492 return; 6493 6494 // Also don't warn for arrays of size 1 which are members of some 6495 // structure. These are often used to approximate flexible arrays in C89 6496 // code. 6497 if (IsTailPaddedMemberArray(*this, size, ND)) 6498 return; 6499 6500 // Suppress the warning if the subscript expression (as identified by the 6501 // ']' location) and the index expression are both from macro expansions 6502 // within a system header. 6503 if (ASE) { 6504 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 6505 ASE->getRBracketLoc()); 6506 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 6507 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 6508 IndexExpr->getLocStart()); 6509 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 6510 return; 6511 } 6512 } 6513 6514 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 6515 if (ASE) 6516 DiagID = diag::warn_array_index_exceeds_bounds; 6517 6518 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 6519 PDiag(DiagID) << index.toString(10, true) 6520 << size.toString(10, true) 6521 << (unsigned)size.getLimitedValue(~0U) 6522 << IndexExpr->getSourceRange()); 6523 } else { 6524 unsigned DiagID = diag::warn_array_index_precedes_bounds; 6525 if (!ASE) { 6526 DiagID = diag::warn_ptr_arith_precedes_bounds; 6527 if (index.isNegative()) index = -index; 6528 } 6529 6530 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 6531 PDiag(DiagID) << index.toString(10, true) 6532 << IndexExpr->getSourceRange()); 6533 } 6534 6535 if (!ND) { 6536 // Try harder to find a NamedDecl to point at in the note. 6537 while (const ArraySubscriptExpr *ASE = 6538 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 6539 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 6540 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 6541 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 6542 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 6543 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 6544 } 6545 6546 if (ND) 6547 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 6548 PDiag(diag::note_array_index_out_of_bounds) 6549 << ND->getDeclName()); 6550 } 6551 6552 void Sema::CheckArrayAccess(const Expr *expr) { 6553 int AllowOnePastEnd = 0; 6554 while (expr) { 6555 expr = expr->IgnoreParenImpCasts(); 6556 switch (expr->getStmtClass()) { 6557 case Stmt::ArraySubscriptExprClass: { 6558 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 6559 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 6560 AllowOnePastEnd > 0); 6561 return; 6562 } 6563 case Stmt::UnaryOperatorClass: { 6564 // Only unwrap the * and & unary operators 6565 const UnaryOperator *UO = cast<UnaryOperator>(expr); 6566 expr = UO->getSubExpr(); 6567 switch (UO->getOpcode()) { 6568 case UO_AddrOf: 6569 AllowOnePastEnd++; 6570 break; 6571 case UO_Deref: 6572 AllowOnePastEnd--; 6573 break; 6574 default: 6575 return; 6576 } 6577 break; 6578 } 6579 case Stmt::ConditionalOperatorClass: { 6580 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 6581 if (const Expr *lhs = cond->getLHS()) 6582 CheckArrayAccess(lhs); 6583 if (const Expr *rhs = cond->getRHS()) 6584 CheckArrayAccess(rhs); 6585 return; 6586 } 6587 default: 6588 return; 6589 } 6590 } 6591 } 6592 6593 //===--- CHECK: Objective-C retain cycles ----------------------------------// 6594 6595 namespace { 6596 struct RetainCycleOwner { 6597 RetainCycleOwner() : Variable(0), Indirect(false) {} 6598 VarDecl *Variable; 6599 SourceRange Range; 6600 SourceLocation Loc; 6601 bool Indirect; 6602 6603 void setLocsFrom(Expr *e) { 6604 Loc = e->getExprLoc(); 6605 Range = e->getSourceRange(); 6606 } 6607 }; 6608 } 6609 6610 /// Consider whether capturing the given variable can possibly lead to 6611 /// a retain cycle. 6612 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 6613 // In ARC, it's captured strongly iff the variable has __strong 6614 // lifetime. In MRR, it's captured strongly if the variable is 6615 // __block and has an appropriate type. 6616 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 6617 return false; 6618 6619 owner.Variable = var; 6620 if (ref) 6621 owner.setLocsFrom(ref); 6622 return true; 6623 } 6624 6625 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 6626 while (true) { 6627 e = e->IgnoreParens(); 6628 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 6629 switch (cast->getCastKind()) { 6630 case CK_BitCast: 6631 case CK_LValueBitCast: 6632 case CK_LValueToRValue: 6633 case CK_ARCReclaimReturnedObject: 6634 e = cast->getSubExpr(); 6635 continue; 6636 6637 default: 6638 return false; 6639 } 6640 } 6641 6642 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 6643 ObjCIvarDecl *ivar = ref->getDecl(); 6644 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 6645 return false; 6646 6647 // Try to find a retain cycle in the base. 6648 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 6649 return false; 6650 6651 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 6652 owner.Indirect = true; 6653 return true; 6654 } 6655 6656 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 6657 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 6658 if (!var) return false; 6659 return considerVariable(var, ref, owner); 6660 } 6661 6662 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 6663 if (member->isArrow()) return false; 6664 6665 // Don't count this as an indirect ownership. 6666 e = member->getBase(); 6667 continue; 6668 } 6669 6670 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 6671 // Only pay attention to pseudo-objects on property references. 6672 ObjCPropertyRefExpr *pre 6673 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 6674 ->IgnoreParens()); 6675 if (!pre) return false; 6676 if (pre->isImplicitProperty()) return false; 6677 ObjCPropertyDecl *property = pre->getExplicitProperty(); 6678 if (!property->isRetaining() && 6679 !(property->getPropertyIvarDecl() && 6680 property->getPropertyIvarDecl()->getType() 6681 .getObjCLifetime() == Qualifiers::OCL_Strong)) 6682 return false; 6683 6684 owner.Indirect = true; 6685 if (pre->isSuperReceiver()) { 6686 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 6687 if (!owner.Variable) 6688 return false; 6689 owner.Loc = pre->getLocation(); 6690 owner.Range = pre->getSourceRange(); 6691 return true; 6692 } 6693 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 6694 ->getSourceExpr()); 6695 continue; 6696 } 6697 6698 // Array ivars? 6699 6700 return false; 6701 } 6702 } 6703 6704 namespace { 6705 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 6706 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 6707 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 6708 Variable(variable), Capturer(0) {} 6709 6710 VarDecl *Variable; 6711 Expr *Capturer; 6712 6713 void VisitDeclRefExpr(DeclRefExpr *ref) { 6714 if (ref->getDecl() == Variable && !Capturer) 6715 Capturer = ref; 6716 } 6717 6718 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 6719 if (Capturer) return; 6720 Visit(ref->getBase()); 6721 if (Capturer && ref->isFreeIvar()) 6722 Capturer = ref; 6723 } 6724 6725 void VisitBlockExpr(BlockExpr *block) { 6726 // Look inside nested blocks 6727 if (block->getBlockDecl()->capturesVariable(Variable)) 6728 Visit(block->getBlockDecl()->getBody()); 6729 } 6730 6731 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 6732 if (Capturer) return; 6733 if (OVE->getSourceExpr()) 6734 Visit(OVE->getSourceExpr()); 6735 } 6736 }; 6737 } 6738 6739 /// Check whether the given argument is a block which captures a 6740 /// variable. 6741 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 6742 assert(owner.Variable && owner.Loc.isValid()); 6743 6744 e = e->IgnoreParenCasts(); 6745 6746 // Look through [^{...} copy] and Block_copy(^{...}). 6747 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 6748 Selector Cmd = ME->getSelector(); 6749 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 6750 e = ME->getInstanceReceiver(); 6751 if (!e) 6752 return 0; 6753 e = e->IgnoreParenCasts(); 6754 } 6755 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 6756 if (CE->getNumArgs() == 1) { 6757 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 6758 if (Fn) { 6759 const IdentifierInfo *FnI = Fn->getIdentifier(); 6760 if (FnI && FnI->isStr("_Block_copy")) { 6761 e = CE->getArg(0)->IgnoreParenCasts(); 6762 } 6763 } 6764 } 6765 } 6766 6767 BlockExpr *block = dyn_cast<BlockExpr>(e); 6768 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 6769 return 0; 6770 6771 FindCaptureVisitor visitor(S.Context, owner.Variable); 6772 visitor.Visit(block->getBlockDecl()->getBody()); 6773 return visitor.Capturer; 6774 } 6775 6776 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 6777 RetainCycleOwner &owner) { 6778 assert(capturer); 6779 assert(owner.Variable && owner.Loc.isValid()); 6780 6781 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 6782 << owner.Variable << capturer->getSourceRange(); 6783 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 6784 << owner.Indirect << owner.Range; 6785 } 6786 6787 /// Check for a keyword selector that starts with the word 'add' or 6788 /// 'set'. 6789 static bool isSetterLikeSelector(Selector sel) { 6790 if (sel.isUnarySelector()) return false; 6791 6792 StringRef str = sel.getNameForSlot(0); 6793 while (!str.empty() && str.front() == '_') str = str.substr(1); 6794 if (str.startswith("set")) 6795 str = str.substr(3); 6796 else if (str.startswith("add")) { 6797 // Specially whitelist 'addOperationWithBlock:'. 6798 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 6799 return false; 6800 str = str.substr(3); 6801 } 6802 else 6803 return false; 6804 6805 if (str.empty()) return true; 6806 return !isLowercase(str.front()); 6807 } 6808 6809 /// Check a message send to see if it's likely to cause a retain cycle. 6810 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 6811 // Only check instance methods whose selector looks like a setter. 6812 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 6813 return; 6814 6815 // Try to find a variable that the receiver is strongly owned by. 6816 RetainCycleOwner owner; 6817 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 6818 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 6819 return; 6820 } else { 6821 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 6822 owner.Variable = getCurMethodDecl()->getSelfDecl(); 6823 owner.Loc = msg->getSuperLoc(); 6824 owner.Range = msg->getSuperLoc(); 6825 } 6826 6827 // Check whether the receiver is captured by any of the arguments. 6828 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 6829 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 6830 return diagnoseRetainCycle(*this, capturer, owner); 6831 } 6832 6833 /// Check a property assign to see if it's likely to cause a retain cycle. 6834 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 6835 RetainCycleOwner owner; 6836 if (!findRetainCycleOwner(*this, receiver, owner)) 6837 return; 6838 6839 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 6840 diagnoseRetainCycle(*this, capturer, owner); 6841 } 6842 6843 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 6844 RetainCycleOwner Owner; 6845 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner)) 6846 return; 6847 6848 // Because we don't have an expression for the variable, we have to set the 6849 // location explicitly here. 6850 Owner.Loc = Var->getLocation(); 6851 Owner.Range = Var->getSourceRange(); 6852 6853 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 6854 diagnoseRetainCycle(*this, Capturer, Owner); 6855 } 6856 6857 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 6858 Expr *RHS, bool isProperty) { 6859 // Check if RHS is an Objective-C object literal, which also can get 6860 // immediately zapped in a weak reference. Note that we explicitly 6861 // allow ObjCStringLiterals, since those are designed to never really die. 6862 RHS = RHS->IgnoreParenImpCasts(); 6863 6864 // This enum needs to match with the 'select' in 6865 // warn_objc_arc_literal_assign (off-by-1). 6866 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 6867 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 6868 return false; 6869 6870 S.Diag(Loc, diag::warn_arc_literal_assign) 6871 << (unsigned) Kind 6872 << (isProperty ? 0 : 1) 6873 << RHS->getSourceRange(); 6874 6875 return true; 6876 } 6877 6878 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 6879 Qualifiers::ObjCLifetime LT, 6880 Expr *RHS, bool isProperty) { 6881 // Strip off any implicit cast added to get to the one ARC-specific. 6882 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 6883 if (cast->getCastKind() == CK_ARCConsumeObject) { 6884 S.Diag(Loc, diag::warn_arc_retained_assign) 6885 << (LT == Qualifiers::OCL_ExplicitNone) 6886 << (isProperty ? 0 : 1) 6887 << RHS->getSourceRange(); 6888 return true; 6889 } 6890 RHS = cast->getSubExpr(); 6891 } 6892 6893 if (LT == Qualifiers::OCL_Weak && 6894 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 6895 return true; 6896 6897 return false; 6898 } 6899 6900 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 6901 QualType LHS, Expr *RHS) { 6902 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 6903 6904 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 6905 return false; 6906 6907 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 6908 return true; 6909 6910 return false; 6911 } 6912 6913 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 6914 Expr *LHS, Expr *RHS) { 6915 QualType LHSType; 6916 // PropertyRef on LHS type need be directly obtained from 6917 // its declaration as it has a PseudoType. 6918 ObjCPropertyRefExpr *PRE 6919 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 6920 if (PRE && !PRE->isImplicitProperty()) { 6921 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 6922 if (PD) 6923 LHSType = PD->getType(); 6924 } 6925 6926 if (LHSType.isNull()) 6927 LHSType = LHS->getType(); 6928 6929 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 6930 6931 if (LT == Qualifiers::OCL_Weak) { 6932 DiagnosticsEngine::Level Level = 6933 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc); 6934 if (Level != DiagnosticsEngine::Ignored) 6935 getCurFunction()->markSafeWeakUse(LHS); 6936 } 6937 6938 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 6939 return; 6940 6941 // FIXME. Check for other life times. 6942 if (LT != Qualifiers::OCL_None) 6943 return; 6944 6945 if (PRE) { 6946 if (PRE->isImplicitProperty()) 6947 return; 6948 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 6949 if (!PD) 6950 return; 6951 6952 unsigned Attributes = PD->getPropertyAttributes(); 6953 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 6954 // when 'assign' attribute was not explicitly specified 6955 // by user, ignore it and rely on property type itself 6956 // for lifetime info. 6957 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 6958 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 6959 LHSType->isObjCRetainableType()) 6960 return; 6961 6962 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 6963 if (cast->getCastKind() == CK_ARCConsumeObject) { 6964 Diag(Loc, diag::warn_arc_retained_property_assign) 6965 << RHS->getSourceRange(); 6966 return; 6967 } 6968 RHS = cast->getSubExpr(); 6969 } 6970 } 6971 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 6972 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 6973 return; 6974 } 6975 } 6976 } 6977 6978 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 6979 6980 namespace { 6981 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 6982 SourceLocation StmtLoc, 6983 const NullStmt *Body) { 6984 // Do not warn if the body is a macro that expands to nothing, e.g: 6985 // 6986 // #define CALL(x) 6987 // if (condition) 6988 // CALL(0); 6989 // 6990 if (Body->hasLeadingEmptyMacro()) 6991 return false; 6992 6993 // Get line numbers of statement and body. 6994 bool StmtLineInvalid; 6995 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc, 6996 &StmtLineInvalid); 6997 if (StmtLineInvalid) 6998 return false; 6999 7000 bool BodyLineInvalid; 7001 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 7002 &BodyLineInvalid); 7003 if (BodyLineInvalid) 7004 return false; 7005 7006 // Warn if null statement and body are on the same line. 7007 if (StmtLine != BodyLine) 7008 return false; 7009 7010 return true; 7011 } 7012 } // Unnamed namespace 7013 7014 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 7015 const Stmt *Body, 7016 unsigned DiagID) { 7017 // Since this is a syntactic check, don't emit diagnostic for template 7018 // instantiations, this just adds noise. 7019 if (CurrentInstantiationScope) 7020 return; 7021 7022 // The body should be a null statement. 7023 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 7024 if (!NBody) 7025 return; 7026 7027 // Do the usual checks. 7028 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 7029 return; 7030 7031 Diag(NBody->getSemiLoc(), DiagID); 7032 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 7033 } 7034 7035 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 7036 const Stmt *PossibleBody) { 7037 assert(!CurrentInstantiationScope); // Ensured by caller 7038 7039 SourceLocation StmtLoc; 7040 const Stmt *Body; 7041 unsigned DiagID; 7042 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 7043 StmtLoc = FS->getRParenLoc(); 7044 Body = FS->getBody(); 7045 DiagID = diag::warn_empty_for_body; 7046 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 7047 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 7048 Body = WS->getBody(); 7049 DiagID = diag::warn_empty_while_body; 7050 } else 7051 return; // Neither `for' nor `while'. 7052 7053 // The body should be a null statement. 7054 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 7055 if (!NBody) 7056 return; 7057 7058 // Skip expensive checks if diagnostic is disabled. 7059 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) == 7060 DiagnosticsEngine::Ignored) 7061 return; 7062 7063 // Do the usual checks. 7064 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 7065 return; 7066 7067 // `for(...);' and `while(...);' are popular idioms, so in order to keep 7068 // noise level low, emit diagnostics only if for/while is followed by a 7069 // CompoundStmt, e.g.: 7070 // for (int i = 0; i < n; i++); 7071 // { 7072 // a(i); 7073 // } 7074 // or if for/while is followed by a statement with more indentation 7075 // than for/while itself: 7076 // for (int i = 0; i < n; i++); 7077 // a(i); 7078 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 7079 if (!ProbableTypo) { 7080 bool BodyColInvalid; 7081 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 7082 PossibleBody->getLocStart(), 7083 &BodyColInvalid); 7084 if (BodyColInvalid) 7085 return; 7086 7087 bool StmtColInvalid; 7088 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 7089 S->getLocStart(), 7090 &StmtColInvalid); 7091 if (StmtColInvalid) 7092 return; 7093 7094 if (BodyCol > StmtCol) 7095 ProbableTypo = true; 7096 } 7097 7098 if (ProbableTypo) { 7099 Diag(NBody->getSemiLoc(), DiagID); 7100 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 7101 } 7102 } 7103 7104 //===--- Layout compatibility ----------------------------------------------// 7105 7106 namespace { 7107 7108 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 7109 7110 /// \brief Check if two enumeration types are layout-compatible. 7111 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 7112 // C++11 [dcl.enum] p8: 7113 // Two enumeration types are layout-compatible if they have the same 7114 // underlying type. 7115 return ED1->isComplete() && ED2->isComplete() && 7116 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 7117 } 7118 7119 /// \brief Check if two fields are layout-compatible. 7120 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 7121 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 7122 return false; 7123 7124 if (Field1->isBitField() != Field2->isBitField()) 7125 return false; 7126 7127 if (Field1->isBitField()) { 7128 // Make sure that the bit-fields are the same length. 7129 unsigned Bits1 = Field1->getBitWidthValue(C); 7130 unsigned Bits2 = Field2->getBitWidthValue(C); 7131 7132 if (Bits1 != Bits2) 7133 return false; 7134 } 7135 7136 return true; 7137 } 7138 7139 /// \brief Check if two standard-layout structs are layout-compatible. 7140 /// (C++11 [class.mem] p17) 7141 bool isLayoutCompatibleStruct(ASTContext &C, 7142 RecordDecl *RD1, 7143 RecordDecl *RD2) { 7144 // If both records are C++ classes, check that base classes match. 7145 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 7146 // If one of records is a CXXRecordDecl we are in C++ mode, 7147 // thus the other one is a CXXRecordDecl, too. 7148 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 7149 // Check number of base classes. 7150 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 7151 return false; 7152 7153 // Check the base classes. 7154 for (CXXRecordDecl::base_class_const_iterator 7155 Base1 = D1CXX->bases_begin(), 7156 BaseEnd1 = D1CXX->bases_end(), 7157 Base2 = D2CXX->bases_begin(); 7158 Base1 != BaseEnd1; 7159 ++Base1, ++Base2) { 7160 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 7161 return false; 7162 } 7163 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 7164 // If only RD2 is a C++ class, it should have zero base classes. 7165 if (D2CXX->getNumBases() > 0) 7166 return false; 7167 } 7168 7169 // Check the fields. 7170 RecordDecl::field_iterator Field2 = RD2->field_begin(), 7171 Field2End = RD2->field_end(), 7172 Field1 = RD1->field_begin(), 7173 Field1End = RD1->field_end(); 7174 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 7175 if (!isLayoutCompatible(C, *Field1, *Field2)) 7176 return false; 7177 } 7178 if (Field1 != Field1End || Field2 != Field2End) 7179 return false; 7180 7181 return true; 7182 } 7183 7184 /// \brief Check if two standard-layout unions are layout-compatible. 7185 /// (C++11 [class.mem] p18) 7186 bool isLayoutCompatibleUnion(ASTContext &C, 7187 RecordDecl *RD1, 7188 RecordDecl *RD2) { 7189 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 7190 for (RecordDecl::field_iterator Field2 = RD2->field_begin(), 7191 Field2End = RD2->field_end(); 7192 Field2 != Field2End; ++Field2) { 7193 UnmatchedFields.insert(*Field2); 7194 } 7195 7196 for (RecordDecl::field_iterator Field1 = RD1->field_begin(), 7197 Field1End = RD1->field_end(); 7198 Field1 != Field1End; ++Field1) { 7199 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 7200 I = UnmatchedFields.begin(), 7201 E = UnmatchedFields.end(); 7202 7203 for ( ; I != E; ++I) { 7204 if (isLayoutCompatible(C, *Field1, *I)) { 7205 bool Result = UnmatchedFields.erase(*I); 7206 (void) Result; 7207 assert(Result); 7208 break; 7209 } 7210 } 7211 if (I == E) 7212 return false; 7213 } 7214 7215 return UnmatchedFields.empty(); 7216 } 7217 7218 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 7219 if (RD1->isUnion() != RD2->isUnion()) 7220 return false; 7221 7222 if (RD1->isUnion()) 7223 return isLayoutCompatibleUnion(C, RD1, RD2); 7224 else 7225 return isLayoutCompatibleStruct(C, RD1, RD2); 7226 } 7227 7228 /// \brief Check if two types are layout-compatible in C++11 sense. 7229 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 7230 if (T1.isNull() || T2.isNull()) 7231 return false; 7232 7233 // C++11 [basic.types] p11: 7234 // If two types T1 and T2 are the same type, then T1 and T2 are 7235 // layout-compatible types. 7236 if (C.hasSameType(T1, T2)) 7237 return true; 7238 7239 T1 = T1.getCanonicalType().getUnqualifiedType(); 7240 T2 = T2.getCanonicalType().getUnqualifiedType(); 7241 7242 const Type::TypeClass TC1 = T1->getTypeClass(); 7243 const Type::TypeClass TC2 = T2->getTypeClass(); 7244 7245 if (TC1 != TC2) 7246 return false; 7247 7248 if (TC1 == Type::Enum) { 7249 return isLayoutCompatible(C, 7250 cast<EnumType>(T1)->getDecl(), 7251 cast<EnumType>(T2)->getDecl()); 7252 } else if (TC1 == Type::Record) { 7253 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 7254 return false; 7255 7256 return isLayoutCompatible(C, 7257 cast<RecordType>(T1)->getDecl(), 7258 cast<RecordType>(T2)->getDecl()); 7259 } 7260 7261 return false; 7262 } 7263 } 7264 7265 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 7266 7267 namespace { 7268 /// \brief Given a type tag expression find the type tag itself. 7269 /// 7270 /// \param TypeExpr Type tag expression, as it appears in user's code. 7271 /// 7272 /// \param VD Declaration of an identifier that appears in a type tag. 7273 /// 7274 /// \param MagicValue Type tag magic value. 7275 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 7276 const ValueDecl **VD, uint64_t *MagicValue) { 7277 while(true) { 7278 if (!TypeExpr) 7279 return false; 7280 7281 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 7282 7283 switch (TypeExpr->getStmtClass()) { 7284 case Stmt::UnaryOperatorClass: { 7285 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 7286 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 7287 TypeExpr = UO->getSubExpr(); 7288 continue; 7289 } 7290 return false; 7291 } 7292 7293 case Stmt::DeclRefExprClass: { 7294 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 7295 *VD = DRE->getDecl(); 7296 return true; 7297 } 7298 7299 case Stmt::IntegerLiteralClass: { 7300 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 7301 llvm::APInt MagicValueAPInt = IL->getValue(); 7302 if (MagicValueAPInt.getActiveBits() <= 64) { 7303 *MagicValue = MagicValueAPInt.getZExtValue(); 7304 return true; 7305 } else 7306 return false; 7307 } 7308 7309 case Stmt::BinaryConditionalOperatorClass: 7310 case Stmt::ConditionalOperatorClass: { 7311 const AbstractConditionalOperator *ACO = 7312 cast<AbstractConditionalOperator>(TypeExpr); 7313 bool Result; 7314 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 7315 if (Result) 7316 TypeExpr = ACO->getTrueExpr(); 7317 else 7318 TypeExpr = ACO->getFalseExpr(); 7319 continue; 7320 } 7321 return false; 7322 } 7323 7324 case Stmt::BinaryOperatorClass: { 7325 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 7326 if (BO->getOpcode() == BO_Comma) { 7327 TypeExpr = BO->getRHS(); 7328 continue; 7329 } 7330 return false; 7331 } 7332 7333 default: 7334 return false; 7335 } 7336 } 7337 } 7338 7339 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 7340 /// 7341 /// \param TypeExpr Expression that specifies a type tag. 7342 /// 7343 /// \param MagicValues Registered magic values. 7344 /// 7345 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 7346 /// kind. 7347 /// 7348 /// \param TypeInfo Information about the corresponding C type. 7349 /// 7350 /// \returns true if the corresponding C type was found. 7351 bool GetMatchingCType( 7352 const IdentifierInfo *ArgumentKind, 7353 const Expr *TypeExpr, const ASTContext &Ctx, 7354 const llvm::DenseMap<Sema::TypeTagMagicValue, 7355 Sema::TypeTagData> *MagicValues, 7356 bool &FoundWrongKind, 7357 Sema::TypeTagData &TypeInfo) { 7358 FoundWrongKind = false; 7359 7360 // Variable declaration that has type_tag_for_datatype attribute. 7361 const ValueDecl *VD = NULL; 7362 7363 uint64_t MagicValue; 7364 7365 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 7366 return false; 7367 7368 if (VD) { 7369 for (specific_attr_iterator<TypeTagForDatatypeAttr> 7370 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(), 7371 E = VD->specific_attr_end<TypeTagForDatatypeAttr>(); 7372 I != E; ++I) { 7373 if (I->getArgumentKind() != ArgumentKind) { 7374 FoundWrongKind = true; 7375 return false; 7376 } 7377 TypeInfo.Type = I->getMatchingCType(); 7378 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 7379 TypeInfo.MustBeNull = I->getMustBeNull(); 7380 return true; 7381 } 7382 return false; 7383 } 7384 7385 if (!MagicValues) 7386 return false; 7387 7388 llvm::DenseMap<Sema::TypeTagMagicValue, 7389 Sema::TypeTagData>::const_iterator I = 7390 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 7391 if (I == MagicValues->end()) 7392 return false; 7393 7394 TypeInfo = I->second; 7395 return true; 7396 } 7397 } // unnamed namespace 7398 7399 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 7400 uint64_t MagicValue, QualType Type, 7401 bool LayoutCompatible, 7402 bool MustBeNull) { 7403 if (!TypeTagForDatatypeMagicValues) 7404 TypeTagForDatatypeMagicValues.reset( 7405 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 7406 7407 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 7408 (*TypeTagForDatatypeMagicValues)[Magic] = 7409 TypeTagData(Type, LayoutCompatible, MustBeNull); 7410 } 7411 7412 namespace { 7413 bool IsSameCharType(QualType T1, QualType T2) { 7414 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 7415 if (!BT1) 7416 return false; 7417 7418 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 7419 if (!BT2) 7420 return false; 7421 7422 BuiltinType::Kind T1Kind = BT1->getKind(); 7423 BuiltinType::Kind T2Kind = BT2->getKind(); 7424 7425 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 7426 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 7427 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 7428 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 7429 } 7430 } // unnamed namespace 7431 7432 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 7433 const Expr * const *ExprArgs) { 7434 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 7435 bool IsPointerAttr = Attr->getIsPointer(); 7436 7437 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 7438 bool FoundWrongKind; 7439 TypeTagData TypeInfo; 7440 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 7441 TypeTagForDatatypeMagicValues.get(), 7442 FoundWrongKind, TypeInfo)) { 7443 if (FoundWrongKind) 7444 Diag(TypeTagExpr->getExprLoc(), 7445 diag::warn_type_tag_for_datatype_wrong_kind) 7446 << TypeTagExpr->getSourceRange(); 7447 return; 7448 } 7449 7450 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 7451 if (IsPointerAttr) { 7452 // Skip implicit cast of pointer to `void *' (as a function argument). 7453 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 7454 if (ICE->getType()->isVoidPointerType() && 7455 ICE->getCastKind() == CK_BitCast) 7456 ArgumentExpr = ICE->getSubExpr(); 7457 } 7458 QualType ArgumentType = ArgumentExpr->getType(); 7459 7460 // Passing a `void*' pointer shouldn't trigger a warning. 7461 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 7462 return; 7463 7464 if (TypeInfo.MustBeNull) { 7465 // Type tag with matching void type requires a null pointer. 7466 if (!ArgumentExpr->isNullPointerConstant(Context, 7467 Expr::NPC_ValueDependentIsNotNull)) { 7468 Diag(ArgumentExpr->getExprLoc(), 7469 diag::warn_type_safety_null_pointer_required) 7470 << ArgumentKind->getName() 7471 << ArgumentExpr->getSourceRange() 7472 << TypeTagExpr->getSourceRange(); 7473 } 7474 return; 7475 } 7476 7477 QualType RequiredType = TypeInfo.Type; 7478 if (IsPointerAttr) 7479 RequiredType = Context.getPointerType(RequiredType); 7480 7481 bool mismatch = false; 7482 if (!TypeInfo.LayoutCompatible) { 7483 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 7484 7485 // C++11 [basic.fundamental] p1: 7486 // Plain char, signed char, and unsigned char are three distinct types. 7487 // 7488 // But we treat plain `char' as equivalent to `signed char' or `unsigned 7489 // char' depending on the current char signedness mode. 7490 if (mismatch) 7491 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 7492 RequiredType->getPointeeType())) || 7493 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 7494 mismatch = false; 7495 } else 7496 if (IsPointerAttr) 7497 mismatch = !isLayoutCompatible(Context, 7498 ArgumentType->getPointeeType(), 7499 RequiredType->getPointeeType()); 7500 else 7501 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 7502 7503 if (mismatch) 7504 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 7505 << ArgumentType << ArgumentKind 7506 << TypeInfo.LayoutCompatible << RequiredType 7507 << ArgumentExpr->getSourceRange() 7508 << TypeTagExpr->getSourceRange(); 7509 } 7510