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