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