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