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