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