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