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