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/ExprOpenMP.h" 25#include "clang/AST/StmtCXX.h" 26#include "clang/AST/StmtObjC.h" 27#include "clang/Analysis/Analyses/FormatString.h" 28#include "clang/Basic/CharInfo.h" 29#include "clang/Basic/TargetBuiltins.h" 30#include "clang/Basic/TargetInfo.h" 31#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 32#include "clang/Sema/Initialization.h" 33#include "clang/Sema/Lookup.h" 34#include "clang/Sema/ScopeInfo.h" 35#include "clang/Sema/Sema.h" 36#include "llvm/ADT/STLExtras.h" 37#include "llvm/ADT/SmallBitVector.h" 38#include "llvm/ADT/SmallString.h" 39#include "llvm/Support/ConvertUTF.h" 40#include "llvm/Support/raw_ostream.h" 41#include <limits> 42using namespace clang; 43using namespace sema; 44 45SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 46 unsigned ByteNo) const { 47 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 48 Context.getTargetInfo()); 49} 50 51/// Checks that a call expression's argument count is the desired number. 52/// This is useful when doing custom type-checking. Returns true on error. 53static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 54 unsigned argCount = call->getNumArgs(); 55 if (argCount == desiredArgCount) return false; 56 57 if (argCount < desiredArgCount) 58 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 59 << 0 /*function call*/ << desiredArgCount << argCount 60 << call->getSourceRange(); 61 62 // Highlight all the excess arguments. 63 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 64 call->getArg(argCount - 1)->getLocEnd()); 65 66 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 67 << 0 /*function call*/ << desiredArgCount << argCount 68 << call->getArg(1)->getSourceRange(); 69} 70 71/// Check that the first argument to __builtin_annotation is an integer 72/// and the second argument is a non-wide string literal. 73static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 74 if (checkArgCount(S, TheCall, 2)) 75 return true; 76 77 // First argument should be an integer. 78 Expr *ValArg = TheCall->getArg(0); 79 QualType Ty = ValArg->getType(); 80 if (!Ty->isIntegerType()) { 81 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 82 << ValArg->getSourceRange(); 83 return true; 84 } 85 86 // Second argument should be a constant string. 87 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 88 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 89 if (!Literal || !Literal->isAscii()) { 90 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 91 << StrArg->getSourceRange(); 92 return true; 93 } 94 95 TheCall->setType(Ty); 96 return false; 97} 98 99/// Check that the argument to __builtin_addressof is a glvalue, and set the 100/// result type to the corresponding pointer type. 101static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 102 if (checkArgCount(S, TheCall, 1)) 103 return true; 104 105 ExprResult Arg(TheCall->getArg(0)); 106 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 107 if (ResultType.isNull()) 108 return true; 109 110 TheCall->setArg(0, Arg.get()); 111 TheCall->setType(ResultType); 112 return false; 113} 114 115static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 116 if (checkArgCount(S, TheCall, 3)) 117 return true; 118 119 // First two arguments should be integers. 120 for (unsigned I = 0; I < 2; ++I) { 121 Expr *Arg = TheCall->getArg(I); 122 QualType Ty = Arg->getType(); 123 if (!Ty->isIntegerType()) { 124 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int) 125 << Ty << Arg->getSourceRange(); 126 return true; 127 } 128 } 129 130 // Third argument should be a pointer to a non-const integer. 131 // IRGen correctly handles volatile, restrict, and address spaces, and 132 // the other qualifiers aren't possible. 133 { 134 Expr *Arg = TheCall->getArg(2); 135 QualType Ty = Arg->getType(); 136 const auto *PtrTy = Ty->getAs<PointerType>(); 137 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 138 !PtrTy->getPointeeType().isConstQualified())) { 139 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int) 140 << Ty << Arg->getSourceRange(); 141 return true; 142 } 143 } 144 145 return false; 146} 147 148static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 149 CallExpr *TheCall, unsigned SizeIdx, 150 unsigned DstSizeIdx) { 151 if (TheCall->getNumArgs() <= SizeIdx || 152 TheCall->getNumArgs() <= DstSizeIdx) 153 return; 154 155 const Expr *SizeArg = TheCall->getArg(SizeIdx); 156 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 157 158 llvm::APSInt Size, DstSize; 159 160 // find out if both sizes are known at compile time 161 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 162 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 163 return; 164 165 if (Size.ule(DstSize)) 166 return; 167 168 // confirmed overflow so generate the diagnostic. 169 IdentifierInfo *FnName = FDecl->getIdentifier(); 170 SourceLocation SL = TheCall->getLocStart(); 171 SourceRange SR = TheCall->getSourceRange(); 172 173 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; 174} 175 176static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 177 if (checkArgCount(S, BuiltinCall, 2)) 178 return true; 179 180 SourceLocation BuiltinLoc = BuiltinCall->getLocStart(); 181 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 182 Expr *Call = BuiltinCall->getArg(0); 183 Expr *Chain = BuiltinCall->getArg(1); 184 185 if (Call->getStmtClass() != Stmt::CallExprClass) { 186 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 187 << Call->getSourceRange(); 188 return true; 189 } 190 191 auto CE = cast<CallExpr>(Call); 192 if (CE->getCallee()->getType()->isBlockPointerType()) { 193 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 194 << Call->getSourceRange(); 195 return true; 196 } 197 198 const Decl *TargetDecl = CE->getCalleeDecl(); 199 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 200 if (FD->getBuiltinID()) { 201 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 202 << Call->getSourceRange(); 203 return true; 204 } 205 206 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 207 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 208 << Call->getSourceRange(); 209 return true; 210 } 211 212 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 213 if (ChainResult.isInvalid()) 214 return true; 215 if (!ChainResult.get()->getType()->isPointerType()) { 216 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 217 << Chain->getSourceRange(); 218 return true; 219 } 220 221 QualType ReturnTy = CE->getCallReturnType(S.Context); 222 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 223 QualType BuiltinTy = S.Context.getFunctionType( 224 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 225 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 226 227 Builtin = 228 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 229 230 BuiltinCall->setType(CE->getType()); 231 BuiltinCall->setValueKind(CE->getValueKind()); 232 BuiltinCall->setObjectKind(CE->getObjectKind()); 233 BuiltinCall->setCallee(Builtin); 234 BuiltinCall->setArg(1, ChainResult.get()); 235 236 return false; 237} 238 239static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 240 Scope::ScopeFlags NeededScopeFlags, 241 unsigned DiagID) { 242 // Scopes aren't available during instantiation. Fortunately, builtin 243 // functions cannot be template args so they cannot be formed through template 244 // instantiation. Therefore checking once during the parse is sufficient. 245 if (!SemaRef.ActiveTemplateInstantiations.empty()) 246 return false; 247 248 Scope *S = SemaRef.getCurScope(); 249 while (S && !S->isSEHExceptScope()) 250 S = S->getParent(); 251 if (!S || !(S->getFlags() & NeededScopeFlags)) { 252 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 253 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 254 << DRE->getDecl()->getIdentifier(); 255 return true; 256 } 257 258 return false; 259} 260 261ExprResult 262Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 263 CallExpr *TheCall) { 264 ExprResult TheCallResult(TheCall); 265 266 // Find out if any arguments are required to be integer constant expressions. 267 unsigned ICEArguments = 0; 268 ASTContext::GetBuiltinTypeError Error; 269 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 270 if (Error != ASTContext::GE_None) 271 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 272 273 // If any arguments are required to be ICE's, check and diagnose. 274 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 275 // Skip arguments not required to be ICE's. 276 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 277 278 llvm::APSInt Result; 279 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 280 return true; 281 ICEArguments &= ~(1 << ArgNo); 282 } 283 284 switch (BuiltinID) { 285 case Builtin::BI__builtin___CFStringMakeConstantString: 286 assert(TheCall->getNumArgs() == 1 && 287 "Wrong # arguments to builtin CFStringMakeConstantString"); 288 if (CheckObjCString(TheCall->getArg(0))) 289 return ExprError(); 290 break; 291 case Builtin::BI__builtin_stdarg_start: 292 case Builtin::BI__builtin_va_start: 293 if (SemaBuiltinVAStart(TheCall)) 294 return ExprError(); 295 break; 296 case Builtin::BI__va_start: { 297 switch (Context.getTargetInfo().getTriple().getArch()) { 298 case llvm::Triple::arm: 299 case llvm::Triple::thumb: 300 if (SemaBuiltinVAStartARM(TheCall)) 301 return ExprError(); 302 break; 303 default: 304 if (SemaBuiltinVAStart(TheCall)) 305 return ExprError(); 306 break; 307 } 308 break; 309 } 310 case Builtin::BI__builtin_isgreater: 311 case Builtin::BI__builtin_isgreaterequal: 312 case Builtin::BI__builtin_isless: 313 case Builtin::BI__builtin_islessequal: 314 case Builtin::BI__builtin_islessgreater: 315 case Builtin::BI__builtin_isunordered: 316 if (SemaBuiltinUnorderedCompare(TheCall)) 317 return ExprError(); 318 break; 319 case Builtin::BI__builtin_fpclassify: 320 if (SemaBuiltinFPClassification(TheCall, 6)) 321 return ExprError(); 322 break; 323 case Builtin::BI__builtin_isfinite: 324 case Builtin::BI__builtin_isinf: 325 case Builtin::BI__builtin_isinf_sign: 326 case Builtin::BI__builtin_isnan: 327 case Builtin::BI__builtin_isnormal: 328 if (SemaBuiltinFPClassification(TheCall, 1)) 329 return ExprError(); 330 break; 331 case Builtin::BI__builtin_shufflevector: 332 return SemaBuiltinShuffleVector(TheCall); 333 // TheCall will be freed by the smart pointer here, but that's fine, since 334 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 335 case Builtin::BI__builtin_prefetch: 336 if (SemaBuiltinPrefetch(TheCall)) 337 return ExprError(); 338 break; 339 case Builtin::BI__assume: 340 case Builtin::BI__builtin_assume: 341 if (SemaBuiltinAssume(TheCall)) 342 return ExprError(); 343 break; 344 case Builtin::BI__builtin_assume_aligned: 345 if (SemaBuiltinAssumeAligned(TheCall)) 346 return ExprError(); 347 break; 348 case Builtin::BI__builtin_object_size: 349 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 350 return ExprError(); 351 break; 352 case Builtin::BI__builtin_longjmp: 353 if (SemaBuiltinLongjmp(TheCall)) 354 return ExprError(); 355 break; 356 case Builtin::BI__builtin_setjmp: 357 if (SemaBuiltinSetjmp(TheCall)) 358 return ExprError(); 359 break; 360 case Builtin::BI_setjmp: 361 case Builtin::BI_setjmpex: 362 if (checkArgCount(*this, TheCall, 1)) 363 return true; 364 break; 365 366 case Builtin::BI__builtin_classify_type: 367 if (checkArgCount(*this, TheCall, 1)) return true; 368 TheCall->setType(Context.IntTy); 369 break; 370 case Builtin::BI__builtin_constant_p: 371 if (checkArgCount(*this, TheCall, 1)) return true; 372 TheCall->setType(Context.IntTy); 373 break; 374 case Builtin::BI__sync_fetch_and_add: 375 case Builtin::BI__sync_fetch_and_add_1: 376 case Builtin::BI__sync_fetch_and_add_2: 377 case Builtin::BI__sync_fetch_and_add_4: 378 case Builtin::BI__sync_fetch_and_add_8: 379 case Builtin::BI__sync_fetch_and_add_16: 380 case Builtin::BI__sync_fetch_and_sub: 381 case Builtin::BI__sync_fetch_and_sub_1: 382 case Builtin::BI__sync_fetch_and_sub_2: 383 case Builtin::BI__sync_fetch_and_sub_4: 384 case Builtin::BI__sync_fetch_and_sub_8: 385 case Builtin::BI__sync_fetch_and_sub_16: 386 case Builtin::BI__sync_fetch_and_or: 387 case Builtin::BI__sync_fetch_and_or_1: 388 case Builtin::BI__sync_fetch_and_or_2: 389 case Builtin::BI__sync_fetch_and_or_4: 390 case Builtin::BI__sync_fetch_and_or_8: 391 case Builtin::BI__sync_fetch_and_or_16: 392 case Builtin::BI__sync_fetch_and_and: 393 case Builtin::BI__sync_fetch_and_and_1: 394 case Builtin::BI__sync_fetch_and_and_2: 395 case Builtin::BI__sync_fetch_and_and_4: 396 case Builtin::BI__sync_fetch_and_and_8: 397 case Builtin::BI__sync_fetch_and_and_16: 398 case Builtin::BI__sync_fetch_and_xor: 399 case Builtin::BI__sync_fetch_and_xor_1: 400 case Builtin::BI__sync_fetch_and_xor_2: 401 case Builtin::BI__sync_fetch_and_xor_4: 402 case Builtin::BI__sync_fetch_and_xor_8: 403 case Builtin::BI__sync_fetch_and_xor_16: 404 case Builtin::BI__sync_fetch_and_nand: 405 case Builtin::BI__sync_fetch_and_nand_1: 406 case Builtin::BI__sync_fetch_and_nand_2: 407 case Builtin::BI__sync_fetch_and_nand_4: 408 case Builtin::BI__sync_fetch_and_nand_8: 409 case Builtin::BI__sync_fetch_and_nand_16: 410 case Builtin::BI__sync_add_and_fetch: 411 case Builtin::BI__sync_add_and_fetch_1: 412 case Builtin::BI__sync_add_and_fetch_2: 413 case Builtin::BI__sync_add_and_fetch_4: 414 case Builtin::BI__sync_add_and_fetch_8: 415 case Builtin::BI__sync_add_and_fetch_16: 416 case Builtin::BI__sync_sub_and_fetch: 417 case Builtin::BI__sync_sub_and_fetch_1: 418 case Builtin::BI__sync_sub_and_fetch_2: 419 case Builtin::BI__sync_sub_and_fetch_4: 420 case Builtin::BI__sync_sub_and_fetch_8: 421 case Builtin::BI__sync_sub_and_fetch_16: 422 case Builtin::BI__sync_and_and_fetch: 423 case Builtin::BI__sync_and_and_fetch_1: 424 case Builtin::BI__sync_and_and_fetch_2: 425 case Builtin::BI__sync_and_and_fetch_4: 426 case Builtin::BI__sync_and_and_fetch_8: 427 case Builtin::BI__sync_and_and_fetch_16: 428 case Builtin::BI__sync_or_and_fetch: 429 case Builtin::BI__sync_or_and_fetch_1: 430 case Builtin::BI__sync_or_and_fetch_2: 431 case Builtin::BI__sync_or_and_fetch_4: 432 case Builtin::BI__sync_or_and_fetch_8: 433 case Builtin::BI__sync_or_and_fetch_16: 434 case Builtin::BI__sync_xor_and_fetch: 435 case Builtin::BI__sync_xor_and_fetch_1: 436 case Builtin::BI__sync_xor_and_fetch_2: 437 case Builtin::BI__sync_xor_and_fetch_4: 438 case Builtin::BI__sync_xor_and_fetch_8: 439 case Builtin::BI__sync_xor_and_fetch_16: 440 case Builtin::BI__sync_nand_and_fetch: 441 case Builtin::BI__sync_nand_and_fetch_1: 442 case Builtin::BI__sync_nand_and_fetch_2: 443 case Builtin::BI__sync_nand_and_fetch_4: 444 case Builtin::BI__sync_nand_and_fetch_8: 445 case Builtin::BI__sync_nand_and_fetch_16: 446 case Builtin::BI__sync_val_compare_and_swap: 447 case Builtin::BI__sync_val_compare_and_swap_1: 448 case Builtin::BI__sync_val_compare_and_swap_2: 449 case Builtin::BI__sync_val_compare_and_swap_4: 450 case Builtin::BI__sync_val_compare_and_swap_8: 451 case Builtin::BI__sync_val_compare_and_swap_16: 452 case Builtin::BI__sync_bool_compare_and_swap: 453 case Builtin::BI__sync_bool_compare_and_swap_1: 454 case Builtin::BI__sync_bool_compare_and_swap_2: 455 case Builtin::BI__sync_bool_compare_and_swap_4: 456 case Builtin::BI__sync_bool_compare_and_swap_8: 457 case Builtin::BI__sync_bool_compare_and_swap_16: 458 case Builtin::BI__sync_lock_test_and_set: 459 case Builtin::BI__sync_lock_test_and_set_1: 460 case Builtin::BI__sync_lock_test_and_set_2: 461 case Builtin::BI__sync_lock_test_and_set_4: 462 case Builtin::BI__sync_lock_test_and_set_8: 463 case Builtin::BI__sync_lock_test_and_set_16: 464 case Builtin::BI__sync_lock_release: 465 case Builtin::BI__sync_lock_release_1: 466 case Builtin::BI__sync_lock_release_2: 467 case Builtin::BI__sync_lock_release_4: 468 case Builtin::BI__sync_lock_release_8: 469 case Builtin::BI__sync_lock_release_16: 470 case Builtin::BI__sync_swap: 471 case Builtin::BI__sync_swap_1: 472 case Builtin::BI__sync_swap_2: 473 case Builtin::BI__sync_swap_4: 474 case Builtin::BI__sync_swap_8: 475 case Builtin::BI__sync_swap_16: 476 return SemaBuiltinAtomicOverloaded(TheCallResult); 477 case Builtin::BI__builtin_nontemporal_load: 478 case Builtin::BI__builtin_nontemporal_store: 479 return SemaBuiltinNontemporalOverloaded(TheCallResult); 480#define BUILTIN(ID, TYPE, ATTRS) 481#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 482 case Builtin::BI##ID: \ 483 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 484#include "clang/Basic/Builtins.def" 485 case Builtin::BI__builtin_annotation: 486 if (SemaBuiltinAnnotation(*this, TheCall)) 487 return ExprError(); 488 break; 489 case Builtin::BI__builtin_addressof: 490 if (SemaBuiltinAddressof(*this, TheCall)) 491 return ExprError(); 492 break; 493 case Builtin::BI__builtin_add_overflow: 494 case Builtin::BI__builtin_sub_overflow: 495 case Builtin::BI__builtin_mul_overflow: 496 if (SemaBuiltinOverflow(*this, TheCall)) 497 return ExprError(); 498 break; 499 case Builtin::BI__builtin_operator_new: 500 case Builtin::BI__builtin_operator_delete: 501 if (!getLangOpts().CPlusPlus) { 502 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 503 << (BuiltinID == Builtin::BI__builtin_operator_new 504 ? "__builtin_operator_new" 505 : "__builtin_operator_delete") 506 << "C++"; 507 return ExprError(); 508 } 509 // CodeGen assumes it can find the global new and delete to call, 510 // so ensure that they are declared. 511 DeclareGlobalNewDelete(); 512 break; 513 514 // check secure string manipulation functions where overflows 515 // are detectable at compile time 516 case Builtin::BI__builtin___memcpy_chk: 517 case Builtin::BI__builtin___memmove_chk: 518 case Builtin::BI__builtin___memset_chk: 519 case Builtin::BI__builtin___strlcat_chk: 520 case Builtin::BI__builtin___strlcpy_chk: 521 case Builtin::BI__builtin___strncat_chk: 522 case Builtin::BI__builtin___strncpy_chk: 523 case Builtin::BI__builtin___stpncpy_chk: 524 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 525 break; 526 case Builtin::BI__builtin___memccpy_chk: 527 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 528 break; 529 case Builtin::BI__builtin___snprintf_chk: 530 case Builtin::BI__builtin___vsnprintf_chk: 531 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 532 break; 533 534 case Builtin::BI__builtin_call_with_static_chain: 535 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 536 return ExprError(); 537 break; 538 539 case Builtin::BI__exception_code: 540 case Builtin::BI_exception_code: { 541 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 542 diag::err_seh___except_block)) 543 return ExprError(); 544 break; 545 } 546 case Builtin::BI__exception_info: 547 case Builtin::BI_exception_info: { 548 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 549 diag::err_seh___except_filter)) 550 return ExprError(); 551 break; 552 } 553 554 case Builtin::BI__GetExceptionInfo: 555 if (checkArgCount(*this, TheCall, 1)) 556 return ExprError(); 557 558 if (CheckCXXThrowOperand( 559 TheCall->getLocStart(), 560 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 561 TheCall)) 562 return ExprError(); 563 564 TheCall->setType(Context.VoidPtrTy); 565 break; 566 567 } 568 569 // Since the target specific builtins for each arch overlap, only check those 570 // of the arch we are compiling for. 571 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 572 switch (Context.getTargetInfo().getTriple().getArch()) { 573 case llvm::Triple::arm: 574 case llvm::Triple::armeb: 575 case llvm::Triple::thumb: 576 case llvm::Triple::thumbeb: 577 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 578 return ExprError(); 579 break; 580 case llvm::Triple::aarch64: 581 case llvm::Triple::aarch64_be: 582 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 583 return ExprError(); 584 break; 585 case llvm::Triple::mips: 586 case llvm::Triple::mipsel: 587 case llvm::Triple::mips64: 588 case llvm::Triple::mips64el: 589 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 590 return ExprError(); 591 break; 592 case llvm::Triple::systemz: 593 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 594 return ExprError(); 595 break; 596 case llvm::Triple::x86: 597 case llvm::Triple::x86_64: 598 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 599 return ExprError(); 600 break; 601 case llvm::Triple::ppc: 602 case llvm::Triple::ppc64: 603 case llvm::Triple::ppc64le: 604 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 605 return ExprError(); 606 break; 607 default: 608 break; 609 } 610 } 611 612 return TheCallResult; 613} 614 615// Get the valid immediate range for the specified NEON type code. 616static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 617 NeonTypeFlags Type(t); 618 int IsQuad = ForceQuad ? true : Type.isQuad(); 619 switch (Type.getEltType()) { 620 case NeonTypeFlags::Int8: 621 case NeonTypeFlags::Poly8: 622 return shift ? 7 : (8 << IsQuad) - 1; 623 case NeonTypeFlags::Int16: 624 case NeonTypeFlags::Poly16: 625 return shift ? 15 : (4 << IsQuad) - 1; 626 case NeonTypeFlags::Int32: 627 return shift ? 31 : (2 << IsQuad) - 1; 628 case NeonTypeFlags::Int64: 629 case NeonTypeFlags::Poly64: 630 return shift ? 63 : (1 << IsQuad) - 1; 631 case NeonTypeFlags::Poly128: 632 return shift ? 127 : (1 << IsQuad) - 1; 633 case NeonTypeFlags::Float16: 634 assert(!shift && "cannot shift float types!"); 635 return (4 << IsQuad) - 1; 636 case NeonTypeFlags::Float32: 637 assert(!shift && "cannot shift float types!"); 638 return (2 << IsQuad) - 1; 639 case NeonTypeFlags::Float64: 640 assert(!shift && "cannot shift float types!"); 641 return (1 << IsQuad) - 1; 642 } 643 llvm_unreachable("Invalid NeonTypeFlag!"); 644} 645 646/// getNeonEltType - Return the QualType corresponding to the elements of 647/// the vector type specified by the NeonTypeFlags. This is used to check 648/// the pointer arguments for Neon load/store intrinsics. 649static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 650 bool IsPolyUnsigned, bool IsInt64Long) { 651 switch (Flags.getEltType()) { 652 case NeonTypeFlags::Int8: 653 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 654 case NeonTypeFlags::Int16: 655 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 656 case NeonTypeFlags::Int32: 657 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 658 case NeonTypeFlags::Int64: 659 if (IsInt64Long) 660 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 661 else 662 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 663 : Context.LongLongTy; 664 case NeonTypeFlags::Poly8: 665 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 666 case NeonTypeFlags::Poly16: 667 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 668 case NeonTypeFlags::Poly64: 669 if (IsInt64Long) 670 return Context.UnsignedLongTy; 671 else 672 return Context.UnsignedLongLongTy; 673 case NeonTypeFlags::Poly128: 674 break; 675 case NeonTypeFlags::Float16: 676 return Context.HalfTy; 677 case NeonTypeFlags::Float32: 678 return Context.FloatTy; 679 case NeonTypeFlags::Float64: 680 return Context.DoubleTy; 681 } 682 llvm_unreachable("Invalid NeonTypeFlag!"); 683} 684 685bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 686 llvm::APSInt Result; 687 uint64_t mask = 0; 688 unsigned TV = 0; 689 int PtrArgNum = -1; 690 bool HasConstPtr = false; 691 switch (BuiltinID) { 692#define GET_NEON_OVERLOAD_CHECK 693#include "clang/Basic/arm_neon.inc" 694#undef GET_NEON_OVERLOAD_CHECK 695 } 696 697 // For NEON intrinsics which are overloaded on vector element type, validate 698 // the immediate which specifies which variant to emit. 699 unsigned ImmArg = TheCall->getNumArgs()-1; 700 if (mask) { 701 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 702 return true; 703 704 TV = Result.getLimitedValue(64); 705 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 706 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 707 << TheCall->getArg(ImmArg)->getSourceRange(); 708 } 709 710 if (PtrArgNum >= 0) { 711 // Check that pointer arguments have the specified type. 712 Expr *Arg = TheCall->getArg(PtrArgNum); 713 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 714 Arg = ICE->getSubExpr(); 715 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 716 QualType RHSTy = RHS.get()->getType(); 717 718 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 719 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64; 720 bool IsInt64Long = 721 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 722 QualType EltTy = 723 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 724 if (HasConstPtr) 725 EltTy = EltTy.withConst(); 726 QualType LHSTy = Context.getPointerType(EltTy); 727 AssignConvertType ConvTy; 728 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 729 if (RHS.isInvalid()) 730 return true; 731 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 732 RHS.get(), AA_Assigning)) 733 return true; 734 } 735 736 // For NEON intrinsics which take an immediate value as part of the 737 // instruction, range check them here. 738 unsigned i = 0, l = 0, u = 0; 739 switch (BuiltinID) { 740 default: 741 return false; 742#define GET_NEON_IMMEDIATE_CHECK 743#include "clang/Basic/arm_neon.inc" 744#undef GET_NEON_IMMEDIATE_CHECK 745 } 746 747 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 748} 749 750bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 751 unsigned MaxWidth) { 752 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 753 BuiltinID == ARM::BI__builtin_arm_ldaex || 754 BuiltinID == ARM::BI__builtin_arm_strex || 755 BuiltinID == ARM::BI__builtin_arm_stlex || 756 BuiltinID == AArch64::BI__builtin_arm_ldrex || 757 BuiltinID == AArch64::BI__builtin_arm_ldaex || 758 BuiltinID == AArch64::BI__builtin_arm_strex || 759 BuiltinID == AArch64::BI__builtin_arm_stlex) && 760 "unexpected ARM builtin"); 761 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 762 BuiltinID == ARM::BI__builtin_arm_ldaex || 763 BuiltinID == AArch64::BI__builtin_arm_ldrex || 764 BuiltinID == AArch64::BI__builtin_arm_ldaex; 765 766 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 767 768 // Ensure that we have the proper number of arguments. 769 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 770 return true; 771 772 // Inspect the pointer argument of the atomic builtin. This should always be 773 // a pointer type, whose element is an integral scalar or pointer type. 774 // Because it is a pointer type, we don't have to worry about any implicit 775 // casts here. 776 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 777 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 778 if (PointerArgRes.isInvalid()) 779 return true; 780 PointerArg = PointerArgRes.get(); 781 782 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 783 if (!pointerType) { 784 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 785 << PointerArg->getType() << PointerArg->getSourceRange(); 786 return true; 787 } 788 789 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 790 // task is to insert the appropriate casts into the AST. First work out just 791 // what the appropriate type is. 792 QualType ValType = pointerType->getPointeeType(); 793 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 794 if (IsLdrex) 795 AddrType.addConst(); 796 797 // Issue a warning if the cast is dodgy. 798 CastKind CastNeeded = CK_NoOp; 799 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 800 CastNeeded = CK_BitCast; 801 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 802 << PointerArg->getType() 803 << Context.getPointerType(AddrType) 804 << AA_Passing << PointerArg->getSourceRange(); 805 } 806 807 // Finally, do the cast and replace the argument with the corrected version. 808 AddrType = Context.getPointerType(AddrType); 809 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 810 if (PointerArgRes.isInvalid()) 811 return true; 812 PointerArg = PointerArgRes.get(); 813 814 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 815 816 // In general, we allow ints, floats and pointers to be loaded and stored. 817 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 818 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 819 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 820 << PointerArg->getType() << PointerArg->getSourceRange(); 821 return true; 822 } 823 824 // But ARM doesn't have instructions to deal with 128-bit versions. 825 if (Context.getTypeSize(ValType) > MaxWidth) { 826 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 827 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 828 << PointerArg->getType() << PointerArg->getSourceRange(); 829 return true; 830 } 831 832 switch (ValType.getObjCLifetime()) { 833 case Qualifiers::OCL_None: 834 case Qualifiers::OCL_ExplicitNone: 835 // okay 836 break; 837 838 case Qualifiers::OCL_Weak: 839 case Qualifiers::OCL_Strong: 840 case Qualifiers::OCL_Autoreleasing: 841 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 842 << ValType << PointerArg->getSourceRange(); 843 return true; 844 } 845 846 847 if (IsLdrex) { 848 TheCall->setType(ValType); 849 return false; 850 } 851 852 // Initialize the argument to be stored. 853 ExprResult ValArg = TheCall->getArg(0); 854 InitializedEntity Entity = InitializedEntity::InitializeParameter( 855 Context, ValType, /*consume*/ false); 856 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 857 if (ValArg.isInvalid()) 858 return true; 859 TheCall->setArg(0, ValArg.get()); 860 861 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 862 // but the custom checker bypasses all default analysis. 863 TheCall->setType(Context.IntTy); 864 return false; 865} 866 867bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 868 llvm::APSInt Result; 869 870 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 871 BuiltinID == ARM::BI__builtin_arm_ldaex || 872 BuiltinID == ARM::BI__builtin_arm_strex || 873 BuiltinID == ARM::BI__builtin_arm_stlex) { 874 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 875 } 876 877 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 878 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 879 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 880 } 881 882 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 883 BuiltinID == ARM::BI__builtin_arm_wsr64) 884 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 885 886 if (BuiltinID == ARM::BI__builtin_arm_rsr || 887 BuiltinID == ARM::BI__builtin_arm_rsrp || 888 BuiltinID == ARM::BI__builtin_arm_wsr || 889 BuiltinID == ARM::BI__builtin_arm_wsrp) 890 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 891 892 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 893 return true; 894 895 // For intrinsics which take an immediate value as part of the instruction, 896 // range check them here. 897 unsigned i = 0, l = 0, u = 0; 898 switch (BuiltinID) { 899 default: return false; 900 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 901 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 902 case ARM::BI__builtin_arm_vcvtr_f: 903 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 904 case ARM::BI__builtin_arm_dmb: 905 case ARM::BI__builtin_arm_dsb: 906 case ARM::BI__builtin_arm_isb: 907 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break; 908 } 909 910 // FIXME: VFP Intrinsics should error if VFP not present. 911 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 912} 913 914bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 915 CallExpr *TheCall) { 916 llvm::APSInt Result; 917 918 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 919 BuiltinID == AArch64::BI__builtin_arm_ldaex || 920 BuiltinID == AArch64::BI__builtin_arm_strex || 921 BuiltinID == AArch64::BI__builtin_arm_stlex) { 922 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 923 } 924 925 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 926 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 927 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 928 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 929 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 930 } 931 932 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 933 BuiltinID == AArch64::BI__builtin_arm_wsr64) 934 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, false); 935 936 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 937 BuiltinID == AArch64::BI__builtin_arm_rsrp || 938 BuiltinID == AArch64::BI__builtin_arm_wsr || 939 BuiltinID == AArch64::BI__builtin_arm_wsrp) 940 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 941 942 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 943 return true; 944 945 // For intrinsics which take an immediate value as part of the instruction, 946 // range check them here. 947 unsigned i = 0, l = 0, u = 0; 948 switch (BuiltinID) { 949 default: return false; 950 case AArch64::BI__builtin_arm_dmb: 951 case AArch64::BI__builtin_arm_dsb: 952 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 953 } 954 955 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 956} 957 958bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 959 unsigned i = 0, l = 0, u = 0; 960 switch (BuiltinID) { 961 default: return false; 962 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 963 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 964 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 965 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 966 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 967 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 968 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 969 } 970 971 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 972} 973 974bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 975 unsigned i = 0, l = 0, u = 0; 976 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 977 BuiltinID == PPC::BI__builtin_divdeu || 978 BuiltinID == PPC::BI__builtin_bpermd; 979 bool IsTarget64Bit = Context.getTargetInfo() 980 .getTypeWidth(Context 981 .getTargetInfo() 982 .getIntPtrType()) == 64; 983 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 984 BuiltinID == PPC::BI__builtin_divweu || 985 BuiltinID == PPC::BI__builtin_divde || 986 BuiltinID == PPC::BI__builtin_divdeu; 987 988 if (Is64BitBltin && !IsTarget64Bit) 989 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 990 << TheCall->getSourceRange(); 991 992 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 993 (BuiltinID == PPC::BI__builtin_bpermd && 994 !Context.getTargetInfo().hasFeature("bpermd"))) 995 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 996 << TheCall->getSourceRange(); 997 998 switch (BuiltinID) { 999 default: return false; 1000 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 1001 case PPC::BI__builtin_altivec_crypto_vshasigmad: 1002 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1003 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1004 case PPC::BI__builtin_tbegin: 1005 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 1006 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 1007 case PPC::BI__builtin_tabortwc: 1008 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 1009 case PPC::BI__builtin_tabortwci: 1010 case PPC::BI__builtin_tabortdci: 1011 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 1012 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 1013 } 1014 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1015} 1016 1017bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 1018 CallExpr *TheCall) { 1019 if (BuiltinID == SystemZ::BI__builtin_tabort) { 1020 Expr *Arg = TheCall->getArg(0); 1021 llvm::APSInt AbortCode(32); 1022 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 1023 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 1024 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 1025 << Arg->getSourceRange(); 1026 } 1027 1028 // For intrinsics which take an immediate value as part of the instruction, 1029 // range check them here. 1030 unsigned i = 0, l = 0, u = 0; 1031 switch (BuiltinID) { 1032 default: return false; 1033 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 1034 case SystemZ::BI__builtin_s390_verimb: 1035 case SystemZ::BI__builtin_s390_verimh: 1036 case SystemZ::BI__builtin_s390_verimf: 1037 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 1038 case SystemZ::BI__builtin_s390_vfaeb: 1039 case SystemZ::BI__builtin_s390_vfaeh: 1040 case SystemZ::BI__builtin_s390_vfaef: 1041 case SystemZ::BI__builtin_s390_vfaebs: 1042 case SystemZ::BI__builtin_s390_vfaehs: 1043 case SystemZ::BI__builtin_s390_vfaefs: 1044 case SystemZ::BI__builtin_s390_vfaezb: 1045 case SystemZ::BI__builtin_s390_vfaezh: 1046 case SystemZ::BI__builtin_s390_vfaezf: 1047 case SystemZ::BI__builtin_s390_vfaezbs: 1048 case SystemZ::BI__builtin_s390_vfaezhs: 1049 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 1050 case SystemZ::BI__builtin_s390_vfidb: 1051 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 1052 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 1053 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 1054 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 1055 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 1056 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 1057 case SystemZ::BI__builtin_s390_vstrcb: 1058 case SystemZ::BI__builtin_s390_vstrch: 1059 case SystemZ::BI__builtin_s390_vstrcf: 1060 case SystemZ::BI__builtin_s390_vstrczb: 1061 case SystemZ::BI__builtin_s390_vstrczh: 1062 case SystemZ::BI__builtin_s390_vstrczf: 1063 case SystemZ::BI__builtin_s390_vstrcbs: 1064 case SystemZ::BI__builtin_s390_vstrchs: 1065 case SystemZ::BI__builtin_s390_vstrcfs: 1066 case SystemZ::BI__builtin_s390_vstrczbs: 1067 case SystemZ::BI__builtin_s390_vstrczhs: 1068 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 1069 } 1070 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1071} 1072 1073/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 1074/// This checks that the target supports __builtin_cpu_supports and 1075/// that the string argument is constant and valid. 1076static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 1077 Expr *Arg = TheCall->getArg(0); 1078 1079 // Check if the argument is a string literal. 1080 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 1081 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 1082 << Arg->getSourceRange(); 1083 1084 // Check the contents of the string. 1085 StringRef Feature = 1086 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 1087 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 1088 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 1089 << Arg->getSourceRange(); 1090 return false; 1091} 1092 1093bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1094 unsigned i = 0, l = 0, u = 0; 1095 switch (BuiltinID) { 1096 default: return false; 1097 case X86::BI__builtin_cpu_supports: 1098 return SemaBuiltinCpuSupports(*this, TheCall); 1099 case X86::BI__builtin_ms_va_start: 1100 return SemaBuiltinMSVAStart(TheCall); 1101 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break; 1102 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break; 1103 case X86::BI__builtin_ia32_vpermil2pd: 1104 case X86::BI__builtin_ia32_vpermil2pd256: 1105 case X86::BI__builtin_ia32_vpermil2ps: 1106 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break; 1107 case X86::BI__builtin_ia32_cmpb128_mask: 1108 case X86::BI__builtin_ia32_cmpw128_mask: 1109 case X86::BI__builtin_ia32_cmpd128_mask: 1110 case X86::BI__builtin_ia32_cmpq128_mask: 1111 case X86::BI__builtin_ia32_cmpb256_mask: 1112 case X86::BI__builtin_ia32_cmpw256_mask: 1113 case X86::BI__builtin_ia32_cmpd256_mask: 1114 case X86::BI__builtin_ia32_cmpq256_mask: 1115 case X86::BI__builtin_ia32_cmpb512_mask: 1116 case X86::BI__builtin_ia32_cmpw512_mask: 1117 case X86::BI__builtin_ia32_cmpd512_mask: 1118 case X86::BI__builtin_ia32_cmpq512_mask: 1119 case X86::BI__builtin_ia32_ucmpb128_mask: 1120 case X86::BI__builtin_ia32_ucmpw128_mask: 1121 case X86::BI__builtin_ia32_ucmpd128_mask: 1122 case X86::BI__builtin_ia32_ucmpq128_mask: 1123 case X86::BI__builtin_ia32_ucmpb256_mask: 1124 case X86::BI__builtin_ia32_ucmpw256_mask: 1125 case X86::BI__builtin_ia32_ucmpd256_mask: 1126 case X86::BI__builtin_ia32_ucmpq256_mask: 1127 case X86::BI__builtin_ia32_ucmpb512_mask: 1128 case X86::BI__builtin_ia32_ucmpw512_mask: 1129 case X86::BI__builtin_ia32_ucmpd512_mask: 1130 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break; 1131 case X86::BI__builtin_ia32_roundps: 1132 case X86::BI__builtin_ia32_roundpd: 1133 case X86::BI__builtin_ia32_roundps256: 1134 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break; 1135 case X86::BI__builtin_ia32_roundss: 1136 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break; 1137 case X86::BI__builtin_ia32_cmpps: 1138 case X86::BI__builtin_ia32_cmpss: 1139 case X86::BI__builtin_ia32_cmppd: 1140 case X86::BI__builtin_ia32_cmpsd: 1141 case X86::BI__builtin_ia32_cmpps256: 1142 case X86::BI__builtin_ia32_cmppd256: 1143 case X86::BI__builtin_ia32_cmpps512_mask: 1144 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break; 1145 case X86::BI__builtin_ia32_vpcomub: 1146 case X86::BI__builtin_ia32_vpcomuw: 1147 case X86::BI__builtin_ia32_vpcomud: 1148 case X86::BI__builtin_ia32_vpcomuq: 1149 case X86::BI__builtin_ia32_vpcomb: 1150 case X86::BI__builtin_ia32_vpcomw: 1151 case X86::BI__builtin_ia32_vpcomd: 1152 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break; 1153 } 1154 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 1155} 1156 1157/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 1158/// parameter with the FormatAttr's correct format_idx and firstDataArg. 1159/// Returns true when the format fits the function and the FormatStringInfo has 1160/// been populated. 1161bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 1162 FormatStringInfo *FSI) { 1163 FSI->HasVAListArg = Format->getFirstArg() == 0; 1164 FSI->FormatIdx = Format->getFormatIdx() - 1; 1165 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 1166 1167 // The way the format attribute works in GCC, the implicit this argument 1168 // of member functions is counted. However, it doesn't appear in our own 1169 // lists, so decrement format_idx in that case. 1170 if (IsCXXMember) { 1171 if(FSI->FormatIdx == 0) 1172 return false; 1173 --FSI->FormatIdx; 1174 if (FSI->FirstDataArg != 0) 1175 --FSI->FirstDataArg; 1176 } 1177 return true; 1178} 1179 1180/// Checks if a the given expression evaluates to null. 1181/// 1182/// \brief Returns true if the value evaluates to null. 1183static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 1184 // If the expression has non-null type, it doesn't evaluate to null. 1185 if (auto nullability 1186 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 1187 if (*nullability == NullabilityKind::NonNull) 1188 return false; 1189 } 1190 1191 // As a special case, transparent unions initialized with zero are 1192 // considered null for the purposes of the nonnull attribute. 1193 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 1194 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1195 if (const CompoundLiteralExpr *CLE = 1196 dyn_cast<CompoundLiteralExpr>(Expr)) 1197 if (const InitListExpr *ILE = 1198 dyn_cast<InitListExpr>(CLE->getInitializer())) 1199 Expr = ILE->getInit(0); 1200 } 1201 1202 bool Result; 1203 return (!Expr->isValueDependent() && 1204 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 1205 !Result); 1206} 1207 1208static void CheckNonNullArgument(Sema &S, 1209 const Expr *ArgExpr, 1210 SourceLocation CallSiteLoc) { 1211 if (CheckNonNullExpr(S, ArgExpr)) 1212 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 1213 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 1214} 1215 1216bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 1217 FormatStringInfo FSI; 1218 if ((GetFormatStringType(Format) == FST_NSString) && 1219 getFormatStringInfo(Format, false, &FSI)) { 1220 Idx = FSI.FormatIdx; 1221 return true; 1222 } 1223 return false; 1224} 1225/// \brief Diagnose use of %s directive in an NSString which is being passed 1226/// as formatting string to formatting method. 1227static void 1228DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 1229 const NamedDecl *FDecl, 1230 Expr **Args, 1231 unsigned NumArgs) { 1232 unsigned Idx = 0; 1233 bool Format = false; 1234 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 1235 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 1236 Idx = 2; 1237 Format = true; 1238 } 1239 else 1240 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 1241 if (S.GetFormatNSStringIdx(I, Idx)) { 1242 Format = true; 1243 break; 1244 } 1245 } 1246 if (!Format || NumArgs <= Idx) 1247 return; 1248 const Expr *FormatExpr = Args[Idx]; 1249 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 1250 FormatExpr = CSCE->getSubExpr(); 1251 const StringLiteral *FormatString; 1252 if (const ObjCStringLiteral *OSL = 1253 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 1254 FormatString = OSL->getString(); 1255 else 1256 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 1257 if (!FormatString) 1258 return; 1259 if (S.FormatStringHasSArg(FormatString)) { 1260 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 1261 << "%s" << 1 << 1; 1262 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 1263 << FDecl->getDeclName(); 1264 } 1265} 1266 1267/// Determine whether the given type has a non-null nullability annotation. 1268static bool isNonNullType(ASTContext &ctx, QualType type) { 1269 if (auto nullability = type->getNullability(ctx)) 1270 return *nullability == NullabilityKind::NonNull; 1271 1272 return false; 1273} 1274 1275static void CheckNonNullArguments(Sema &S, 1276 const NamedDecl *FDecl, 1277 const FunctionProtoType *Proto, 1278 ArrayRef<const Expr *> Args, 1279 SourceLocation CallSiteLoc) { 1280 assert((FDecl || Proto) && "Need a function declaration or prototype"); 1281 1282 // Check the attributes attached to the method/function itself. 1283 llvm::SmallBitVector NonNullArgs; 1284 if (FDecl) { 1285 // Handle the nonnull attribute on the function/method declaration itself. 1286 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 1287 if (!NonNull->args_size()) { 1288 // Easy case: all pointer arguments are nonnull. 1289 for (const auto *Arg : Args) 1290 if (S.isValidPointerAttrType(Arg->getType())) 1291 CheckNonNullArgument(S, Arg, CallSiteLoc); 1292 return; 1293 } 1294 1295 for (unsigned Val : NonNull->args()) { 1296 if (Val >= Args.size()) 1297 continue; 1298 if (NonNullArgs.empty()) 1299 NonNullArgs.resize(Args.size()); 1300 NonNullArgs.set(Val); 1301 } 1302 } 1303 } 1304 1305 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 1306 // Handle the nonnull attribute on the parameters of the 1307 // function/method. 1308 ArrayRef<ParmVarDecl*> parms; 1309 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 1310 parms = FD->parameters(); 1311 else 1312 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 1313 1314 unsigned ParamIndex = 0; 1315 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 1316 I != E; ++I, ++ParamIndex) { 1317 const ParmVarDecl *PVD = *I; 1318 if (PVD->hasAttr<NonNullAttr>() || 1319 isNonNullType(S.Context, PVD->getType())) { 1320 if (NonNullArgs.empty()) 1321 NonNullArgs.resize(Args.size()); 1322 1323 NonNullArgs.set(ParamIndex); 1324 } 1325 } 1326 } else { 1327 // If we have a non-function, non-method declaration but no 1328 // function prototype, try to dig out the function prototype. 1329 if (!Proto) { 1330 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 1331 QualType type = VD->getType().getNonReferenceType(); 1332 if (auto pointerType = type->getAs<PointerType>()) 1333 type = pointerType->getPointeeType(); 1334 else if (auto blockType = type->getAs<BlockPointerType>()) 1335 type = blockType->getPointeeType(); 1336 // FIXME: data member pointers? 1337 1338 // Dig out the function prototype, if there is one. 1339 Proto = type->getAs<FunctionProtoType>(); 1340 } 1341 } 1342 1343 // Fill in non-null argument information from the nullability 1344 // information on the parameter types (if we have them). 1345 if (Proto) { 1346 unsigned Index = 0; 1347 for (auto paramType : Proto->getParamTypes()) { 1348 if (isNonNullType(S.Context, paramType)) { 1349 if (NonNullArgs.empty()) 1350 NonNullArgs.resize(Args.size()); 1351 1352 NonNullArgs.set(Index); 1353 } 1354 1355 ++Index; 1356 } 1357 } 1358 } 1359 1360 // Check for non-null arguments. 1361 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 1362 ArgIndex != ArgIndexEnd; ++ArgIndex) { 1363 if (NonNullArgs[ArgIndex]) 1364 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 1365 } 1366} 1367 1368/// Handles the checks for format strings, non-POD arguments to vararg 1369/// functions, and NULL arguments passed to non-NULL parameters. 1370void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 1371 ArrayRef<const Expr *> Args, bool IsMemberFunction, 1372 SourceLocation Loc, SourceRange Range, 1373 VariadicCallType CallType) { 1374 // FIXME: We should check as much as we can in the template definition. 1375 if (CurContext->isDependentContext()) 1376 return; 1377 1378 // Printf and scanf checking. 1379 llvm::SmallBitVector CheckedVarArgs; 1380 if (FDecl) { 1381 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 1382 // Only create vector if there are format attributes. 1383 CheckedVarArgs.resize(Args.size()); 1384 1385 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 1386 CheckedVarArgs); 1387 } 1388 } 1389 1390 // Refuse POD arguments that weren't caught by the format string 1391 // checks above. 1392 if (CallType != VariadicDoesNotApply) { 1393 unsigned NumParams = Proto ? Proto->getNumParams() 1394 : FDecl && isa<FunctionDecl>(FDecl) 1395 ? cast<FunctionDecl>(FDecl)->getNumParams() 1396 : FDecl && isa<ObjCMethodDecl>(FDecl) 1397 ? cast<ObjCMethodDecl>(FDecl)->param_size() 1398 : 0; 1399 1400 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 1401 // Args[ArgIdx] can be null in malformed code. 1402 if (const Expr *Arg = Args[ArgIdx]) { 1403 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 1404 checkVariadicArgument(Arg, CallType); 1405 } 1406 } 1407 } 1408 1409 if (FDecl || Proto) { 1410 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 1411 1412 // Type safety checking. 1413 if (FDecl) { 1414 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 1415 CheckArgumentWithTypeTag(I, Args.data()); 1416 } 1417 } 1418} 1419 1420/// CheckConstructorCall - Check a constructor call for correctness and safety 1421/// properties not enforced by the C type system. 1422void Sema::CheckConstructorCall(FunctionDecl *FDecl, 1423 ArrayRef<const Expr *> Args, 1424 const FunctionProtoType *Proto, 1425 SourceLocation Loc) { 1426 VariadicCallType CallType = 1427 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 1428 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(), 1429 CallType); 1430} 1431 1432/// CheckFunctionCall - Check a direct function call for various correctness 1433/// and safety properties not strictly enforced by the C type system. 1434bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 1435 const FunctionProtoType *Proto) { 1436 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 1437 isa<CXXMethodDecl>(FDecl); 1438 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 1439 IsMemberOperatorCall; 1440 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 1441 TheCall->getCallee()); 1442 Expr** Args = TheCall->getArgs(); 1443 unsigned NumArgs = TheCall->getNumArgs(); 1444 if (IsMemberOperatorCall) { 1445 // If this is a call to a member operator, hide the first argument 1446 // from checkCall. 1447 // FIXME: Our choice of AST representation here is less than ideal. 1448 ++Args; 1449 --NumArgs; 1450 } 1451 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs), 1452 IsMemberFunction, TheCall->getRParenLoc(), 1453 TheCall->getCallee()->getSourceRange(), CallType); 1454 1455 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 1456 // None of the checks below are needed for functions that don't have 1457 // simple names (e.g., C++ conversion functions). 1458 if (!FnInfo) 1459 return false; 1460 1461 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo); 1462 if (getLangOpts().ObjC1) 1463 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 1464 1465 unsigned CMId = FDecl->getMemoryFunctionKind(); 1466 if (CMId == 0) 1467 return false; 1468 1469 // Handle memory setting and copying functions. 1470 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 1471 CheckStrlcpycatArguments(TheCall, FnInfo); 1472 else if (CMId == Builtin::BIstrncat) 1473 CheckStrncatArguments(TheCall, FnInfo); 1474 else 1475 CheckMemaccessArguments(TheCall, CMId, FnInfo); 1476 1477 return false; 1478} 1479 1480bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 1481 ArrayRef<const Expr *> Args) { 1482 VariadicCallType CallType = 1483 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 1484 1485 checkCall(Method, nullptr, Args, 1486 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 1487 CallType); 1488 1489 return false; 1490} 1491 1492bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 1493 const FunctionProtoType *Proto) { 1494 QualType Ty; 1495 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 1496 Ty = V->getType().getNonReferenceType(); 1497 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 1498 Ty = F->getType().getNonReferenceType(); 1499 else 1500 return false; 1501 1502 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 1503 !Ty->isFunctionProtoType()) 1504 return false; 1505 1506 VariadicCallType CallType; 1507 if (!Proto || !Proto->isVariadic()) { 1508 CallType = VariadicDoesNotApply; 1509 } else if (Ty->isBlockPointerType()) { 1510 CallType = VariadicBlock; 1511 } else { // Ty->isFunctionPointerType() 1512 CallType = VariadicFunction; 1513 } 1514 1515 checkCall(NDecl, Proto, 1516 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 1517 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 1518 TheCall->getCallee()->getSourceRange(), CallType); 1519 1520 return false; 1521} 1522 1523/// Checks function calls when a FunctionDecl or a NamedDecl is not available, 1524/// such as function pointers returned from functions. 1525bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 1526 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 1527 TheCall->getCallee()); 1528 checkCall(/*FDecl=*/nullptr, Proto, 1529 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 1530 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 1531 TheCall->getCallee()->getSourceRange(), CallType); 1532 1533 return false; 1534} 1535 1536static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 1537 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed || 1538 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst) 1539 return false; 1540 1541 switch (Op) { 1542 case AtomicExpr::AO__c11_atomic_init: 1543 llvm_unreachable("There is no ordering argument for an init"); 1544 1545 case AtomicExpr::AO__c11_atomic_load: 1546 case AtomicExpr::AO__atomic_load_n: 1547 case AtomicExpr::AO__atomic_load: 1548 return Ordering != AtomicExpr::AO_ABI_memory_order_release && 1549 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel; 1550 1551 case AtomicExpr::AO__c11_atomic_store: 1552 case AtomicExpr::AO__atomic_store: 1553 case AtomicExpr::AO__atomic_store_n: 1554 return Ordering != AtomicExpr::AO_ABI_memory_order_consume && 1555 Ordering != AtomicExpr::AO_ABI_memory_order_acquire && 1556 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel; 1557 1558 default: 1559 return true; 1560 } 1561} 1562 1563ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 1564 AtomicExpr::AtomicOp Op) { 1565 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 1566 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1567 1568 // All these operations take one of the following forms: 1569 enum { 1570 // C __c11_atomic_init(A *, C) 1571 Init, 1572 // C __c11_atomic_load(A *, int) 1573 Load, 1574 // void __atomic_load(A *, CP, int) 1575 Copy, 1576 // C __c11_atomic_add(A *, M, int) 1577 Arithmetic, 1578 // C __atomic_exchange_n(A *, CP, int) 1579 Xchg, 1580 // void __atomic_exchange(A *, C *, CP, int) 1581 GNUXchg, 1582 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 1583 C11CmpXchg, 1584 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 1585 GNUCmpXchg 1586 } Form = Init; 1587 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 }; 1588 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 }; 1589 // where: 1590 // C is an appropriate type, 1591 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 1592 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 1593 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 1594 // the int parameters are for orderings. 1595 1596 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 1597 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 1598 AtomicExpr::AO__atomic_load, 1599 "need to update code for modified C11 atomics"); 1600 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init && 1601 Op <= AtomicExpr::AO__c11_atomic_fetch_xor; 1602 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 1603 Op == AtomicExpr::AO__atomic_store_n || 1604 Op == AtomicExpr::AO__atomic_exchange_n || 1605 Op == AtomicExpr::AO__atomic_compare_exchange_n; 1606 bool IsAddSub = false; 1607 1608 switch (Op) { 1609 case AtomicExpr::AO__c11_atomic_init: 1610 Form = Init; 1611 break; 1612 1613 case AtomicExpr::AO__c11_atomic_load: 1614 case AtomicExpr::AO__atomic_load_n: 1615 Form = Load; 1616 break; 1617 1618 case AtomicExpr::AO__c11_atomic_store: 1619 case AtomicExpr::AO__atomic_load: 1620 case AtomicExpr::AO__atomic_store: 1621 case AtomicExpr::AO__atomic_store_n: 1622 Form = Copy; 1623 break; 1624 1625 case AtomicExpr::AO__c11_atomic_fetch_add: 1626 case AtomicExpr::AO__c11_atomic_fetch_sub: 1627 case AtomicExpr::AO__atomic_fetch_add: 1628 case AtomicExpr::AO__atomic_fetch_sub: 1629 case AtomicExpr::AO__atomic_add_fetch: 1630 case AtomicExpr::AO__atomic_sub_fetch: 1631 IsAddSub = true; 1632 // Fall through. 1633 case AtomicExpr::AO__c11_atomic_fetch_and: 1634 case AtomicExpr::AO__c11_atomic_fetch_or: 1635 case AtomicExpr::AO__c11_atomic_fetch_xor: 1636 case AtomicExpr::AO__atomic_fetch_and: 1637 case AtomicExpr::AO__atomic_fetch_or: 1638 case AtomicExpr::AO__atomic_fetch_xor: 1639 case AtomicExpr::AO__atomic_fetch_nand: 1640 case AtomicExpr::AO__atomic_and_fetch: 1641 case AtomicExpr::AO__atomic_or_fetch: 1642 case AtomicExpr::AO__atomic_xor_fetch: 1643 case AtomicExpr::AO__atomic_nand_fetch: 1644 Form = Arithmetic; 1645 break; 1646 1647 case AtomicExpr::AO__c11_atomic_exchange: 1648 case AtomicExpr::AO__atomic_exchange_n: 1649 Form = Xchg; 1650 break; 1651 1652 case AtomicExpr::AO__atomic_exchange: 1653 Form = GNUXchg; 1654 break; 1655 1656 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 1657 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 1658 Form = C11CmpXchg; 1659 break; 1660 1661 case AtomicExpr::AO__atomic_compare_exchange: 1662 case AtomicExpr::AO__atomic_compare_exchange_n: 1663 Form = GNUCmpXchg; 1664 break; 1665 } 1666 1667 // Check we have the right number of arguments. 1668 if (TheCall->getNumArgs() < NumArgs[Form]) { 1669 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1670 << 0 << NumArgs[Form] << TheCall->getNumArgs() 1671 << TheCall->getCallee()->getSourceRange(); 1672 return ExprError(); 1673 } else if (TheCall->getNumArgs() > NumArgs[Form]) { 1674 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(), 1675 diag::err_typecheck_call_too_many_args) 1676 << 0 << NumArgs[Form] << TheCall->getNumArgs() 1677 << TheCall->getCallee()->getSourceRange(); 1678 return ExprError(); 1679 } 1680 1681 // Inspect the first argument of the atomic operation. 1682 Expr *Ptr = TheCall->getArg(0); 1683 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get(); 1684 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 1685 if (!pointerType) { 1686 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1687 << Ptr->getType() << Ptr->getSourceRange(); 1688 return ExprError(); 1689 } 1690 1691 // For a __c11 builtin, this should be a pointer to an _Atomic type. 1692 QualType AtomTy = pointerType->getPointeeType(); // 'A' 1693 QualType ValType = AtomTy; // 'C' 1694 if (IsC11) { 1695 if (!AtomTy->isAtomicType()) { 1696 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 1697 << Ptr->getType() << Ptr->getSourceRange(); 1698 return ExprError(); 1699 } 1700 if (AtomTy.isConstQualified()) { 1701 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 1702 << Ptr->getType() << Ptr->getSourceRange(); 1703 return ExprError(); 1704 } 1705 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 1706 } else if (Form != Load && Op != AtomicExpr::AO__atomic_load) { 1707 if (ValType.isConstQualified()) { 1708 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 1709 << Ptr->getType() << Ptr->getSourceRange(); 1710 return ExprError(); 1711 } 1712 } 1713 1714 // For an arithmetic operation, the implied arithmetic must be well-formed. 1715 if (Form == Arithmetic) { 1716 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 1717 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 1718 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 1719 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 1720 return ExprError(); 1721 } 1722 if (!IsAddSub && !ValType->isIntegerType()) { 1723 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 1724 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 1725 return ExprError(); 1726 } 1727 if (IsC11 && ValType->isPointerType() && 1728 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 1729 diag::err_incomplete_type)) { 1730 return ExprError(); 1731 } 1732 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 1733 // For __atomic_*_n operations, the value type must be a scalar integral or 1734 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 1735 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 1736 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 1737 return ExprError(); 1738 } 1739 1740 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 1741 !AtomTy->isScalarType()) { 1742 // For GNU atomics, require a trivially-copyable type. This is not part of 1743 // the GNU atomics specification, but we enforce it for sanity. 1744 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 1745 << Ptr->getType() << Ptr->getSourceRange(); 1746 return ExprError(); 1747 } 1748 1749 switch (ValType.getObjCLifetime()) { 1750 case Qualifiers::OCL_None: 1751 case Qualifiers::OCL_ExplicitNone: 1752 // okay 1753 break; 1754 1755 case Qualifiers::OCL_Weak: 1756 case Qualifiers::OCL_Strong: 1757 case Qualifiers::OCL_Autoreleasing: 1758 // FIXME: Can this happen? By this point, ValType should be known 1759 // to be trivially copyable. 1760 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1761 << ValType << Ptr->getSourceRange(); 1762 return ExprError(); 1763 } 1764 1765 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the 1766 // volatile-ness of the pointee-type inject itself into the result or the 1767 // other operands. 1768 ValType.removeLocalVolatile(); 1769 QualType ResultType = ValType; 1770 if (Form == Copy || Form == GNUXchg || Form == Init) 1771 ResultType = Context.VoidTy; 1772 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 1773 ResultType = Context.BoolTy; 1774 1775 // The type of a parameter passed 'by value'. In the GNU atomics, such 1776 // arguments are actually passed as pointers. 1777 QualType ByValType = ValType; // 'CP' 1778 if (!IsC11 && !IsN) 1779 ByValType = Ptr->getType(); 1780 1781 // FIXME: __atomic_load allows the first argument to be a a pointer to const 1782 // but not the second argument. We need to manually remove possible const 1783 // qualifiers. 1784 1785 // The first argument --- the pointer --- has a fixed type; we 1786 // deduce the types of the rest of the arguments accordingly. Walk 1787 // the remaining arguments, converting them to the deduced value type. 1788 for (unsigned i = 1; i != NumArgs[Form]; ++i) { 1789 QualType Ty; 1790 if (i < NumVals[Form] + 1) { 1791 switch (i) { 1792 case 1: 1793 // The second argument is the non-atomic operand. For arithmetic, this 1794 // is always passed by value, and for a compare_exchange it is always 1795 // passed by address. For the rest, GNU uses by-address and C11 uses 1796 // by-value. 1797 assert(Form != Load); 1798 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 1799 Ty = ValType; 1800 else if (Form == Copy || Form == Xchg) 1801 Ty = ByValType; 1802 else if (Form == Arithmetic) 1803 Ty = Context.getPointerDiffType(); 1804 else { 1805 Expr *ValArg = TheCall->getArg(i); 1806 unsigned AS = 0; 1807 // Keep address space of non-atomic pointer type. 1808 if (const PointerType *PtrTy = 1809 ValArg->getType()->getAs<PointerType>()) { 1810 AS = PtrTy->getPointeeType().getAddressSpace(); 1811 } 1812 Ty = Context.getPointerType( 1813 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 1814 } 1815 break; 1816 case 2: 1817 // The third argument to compare_exchange / GNU exchange is a 1818 // (pointer to a) desired value. 1819 Ty = ByValType; 1820 break; 1821 case 3: 1822 // The fourth argument to GNU compare_exchange is a 'weak' flag. 1823 Ty = Context.BoolTy; 1824 break; 1825 } 1826 } else { 1827 // The order(s) are always converted to int. 1828 Ty = Context.IntTy; 1829 } 1830 1831 InitializedEntity Entity = 1832 InitializedEntity::InitializeParameter(Context, Ty, false); 1833 ExprResult Arg = TheCall->getArg(i); 1834 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 1835 if (Arg.isInvalid()) 1836 return true; 1837 TheCall->setArg(i, Arg.get()); 1838 } 1839 1840 // Permute the arguments into a 'consistent' order. 1841 SmallVector<Expr*, 5> SubExprs; 1842 SubExprs.push_back(Ptr); 1843 switch (Form) { 1844 case Init: 1845 // Note, AtomicExpr::getVal1() has a special case for this atomic. 1846 SubExprs.push_back(TheCall->getArg(1)); // Val1 1847 break; 1848 case Load: 1849 SubExprs.push_back(TheCall->getArg(1)); // Order 1850 break; 1851 case Copy: 1852 case Arithmetic: 1853 case Xchg: 1854 SubExprs.push_back(TheCall->getArg(2)); // Order 1855 SubExprs.push_back(TheCall->getArg(1)); // Val1 1856 break; 1857 case GNUXchg: 1858 // Note, AtomicExpr::getVal2() has a special case for this atomic. 1859 SubExprs.push_back(TheCall->getArg(3)); // Order 1860 SubExprs.push_back(TheCall->getArg(1)); // Val1 1861 SubExprs.push_back(TheCall->getArg(2)); // Val2 1862 break; 1863 case C11CmpXchg: 1864 SubExprs.push_back(TheCall->getArg(3)); // Order 1865 SubExprs.push_back(TheCall->getArg(1)); // Val1 1866 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 1867 SubExprs.push_back(TheCall->getArg(2)); // Val2 1868 break; 1869 case GNUCmpXchg: 1870 SubExprs.push_back(TheCall->getArg(4)); // Order 1871 SubExprs.push_back(TheCall->getArg(1)); // Val1 1872 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 1873 SubExprs.push_back(TheCall->getArg(2)); // Val2 1874 SubExprs.push_back(TheCall->getArg(3)); // Weak 1875 break; 1876 } 1877 1878 if (SubExprs.size() >= 2 && Form != Init) { 1879 llvm::APSInt Result(32); 1880 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 1881 !isValidOrderingForOp(Result.getSExtValue(), Op)) 1882 Diag(SubExprs[1]->getLocStart(), 1883 diag::warn_atomic_op_has_invalid_memory_order) 1884 << SubExprs[1]->getSourceRange(); 1885 } 1886 1887 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 1888 SubExprs, ResultType, Op, 1889 TheCall->getRParenLoc()); 1890 1891 if ((Op == AtomicExpr::AO__c11_atomic_load || 1892 (Op == AtomicExpr::AO__c11_atomic_store)) && 1893 Context.AtomicUsesUnsupportedLibcall(AE)) 1894 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) << 1895 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1); 1896 1897 return AE; 1898} 1899 1900 1901/// checkBuiltinArgument - Given a call to a builtin function, perform 1902/// normal type-checking on the given argument, updating the call in 1903/// place. This is useful when a builtin function requires custom 1904/// type-checking for some of its arguments but not necessarily all of 1905/// them. 1906/// 1907/// Returns true on error. 1908static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 1909 FunctionDecl *Fn = E->getDirectCallee(); 1910 assert(Fn && "builtin call without direct callee!"); 1911 1912 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 1913 InitializedEntity Entity = 1914 InitializedEntity::InitializeParameter(S.Context, Param); 1915 1916 ExprResult Arg = E->getArg(0); 1917 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 1918 if (Arg.isInvalid()) 1919 return true; 1920 1921 E->setArg(ArgIndex, Arg.get()); 1922 return false; 1923} 1924 1925/// SemaBuiltinAtomicOverloaded - We have a call to a function like 1926/// __sync_fetch_and_add, which is an overloaded function based on the pointer 1927/// type of its first argument. The main ActOnCallExpr routines have already 1928/// promoted the types of arguments because all of these calls are prototyped as 1929/// void(...). 1930/// 1931/// This function goes through and does final semantic checking for these 1932/// builtins, 1933ExprResult 1934Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 1935 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 1936 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1937 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 1938 1939 // Ensure that we have at least one argument to do type inference from. 1940 if (TheCall->getNumArgs() < 1) { 1941 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 1942 << 0 << 1 << TheCall->getNumArgs() 1943 << TheCall->getCallee()->getSourceRange(); 1944 return ExprError(); 1945 } 1946 1947 // Inspect the first argument of the atomic builtin. This should always be 1948 // a pointer type, whose element is an integral scalar or pointer type. 1949 // Because it is a pointer type, we don't have to worry about any implicit 1950 // casts here. 1951 // FIXME: We don't allow floating point scalars as input. 1952 Expr *FirstArg = TheCall->getArg(0); 1953 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 1954 if (FirstArgResult.isInvalid()) 1955 return ExprError(); 1956 FirstArg = FirstArgResult.get(); 1957 TheCall->setArg(0, FirstArg); 1958 1959 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 1960 if (!pointerType) { 1961 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1962 << FirstArg->getType() << FirstArg->getSourceRange(); 1963 return ExprError(); 1964 } 1965 1966 QualType ValType = pointerType->getPointeeType(); 1967 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1968 !ValType->isBlockPointerType()) { 1969 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 1970 << FirstArg->getType() << FirstArg->getSourceRange(); 1971 return ExprError(); 1972 } 1973 1974 switch (ValType.getObjCLifetime()) { 1975 case Qualifiers::OCL_None: 1976 case Qualifiers::OCL_ExplicitNone: 1977 // okay 1978 break; 1979 1980 case Qualifiers::OCL_Weak: 1981 case Qualifiers::OCL_Strong: 1982 case Qualifiers::OCL_Autoreleasing: 1983 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1984 << ValType << FirstArg->getSourceRange(); 1985 return ExprError(); 1986 } 1987 1988 // Strip any qualifiers off ValType. 1989 ValType = ValType.getUnqualifiedType(); 1990 1991 // The majority of builtins return a value, but a few have special return 1992 // types, so allow them to override appropriately below. 1993 QualType ResultType = ValType; 1994 1995 // We need to figure out which concrete builtin this maps onto. For example, 1996 // __sync_fetch_and_add with a 2 byte object turns into 1997 // __sync_fetch_and_add_2. 1998#define BUILTIN_ROW(x) \ 1999 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 2000 Builtin::BI##x##_8, Builtin::BI##x##_16 } 2001 2002 static const unsigned BuiltinIndices[][5] = { 2003 BUILTIN_ROW(__sync_fetch_and_add), 2004 BUILTIN_ROW(__sync_fetch_and_sub), 2005 BUILTIN_ROW(__sync_fetch_and_or), 2006 BUILTIN_ROW(__sync_fetch_and_and), 2007 BUILTIN_ROW(__sync_fetch_and_xor), 2008 BUILTIN_ROW(__sync_fetch_and_nand), 2009 2010 BUILTIN_ROW(__sync_add_and_fetch), 2011 BUILTIN_ROW(__sync_sub_and_fetch), 2012 BUILTIN_ROW(__sync_and_and_fetch), 2013 BUILTIN_ROW(__sync_or_and_fetch), 2014 BUILTIN_ROW(__sync_xor_and_fetch), 2015 BUILTIN_ROW(__sync_nand_and_fetch), 2016 2017 BUILTIN_ROW(__sync_val_compare_and_swap), 2018 BUILTIN_ROW(__sync_bool_compare_and_swap), 2019 BUILTIN_ROW(__sync_lock_test_and_set), 2020 BUILTIN_ROW(__sync_lock_release), 2021 BUILTIN_ROW(__sync_swap) 2022 }; 2023#undef BUILTIN_ROW 2024 2025 // Determine the index of the size. 2026 unsigned SizeIndex; 2027 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 2028 case 1: SizeIndex = 0; break; 2029 case 2: SizeIndex = 1; break; 2030 case 4: SizeIndex = 2; break; 2031 case 8: SizeIndex = 3; break; 2032 case 16: SizeIndex = 4; break; 2033 default: 2034 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 2035 << FirstArg->getType() << FirstArg->getSourceRange(); 2036 return ExprError(); 2037 } 2038 2039 // Each of these builtins has one pointer argument, followed by some number of 2040 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 2041 // that we ignore. Find out which row of BuiltinIndices to read from as well 2042 // as the number of fixed args. 2043 unsigned BuiltinID = FDecl->getBuiltinID(); 2044 unsigned BuiltinIndex, NumFixed = 1; 2045 bool WarnAboutSemanticsChange = false; 2046 switch (BuiltinID) { 2047 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 2048 case Builtin::BI__sync_fetch_and_add: 2049 case Builtin::BI__sync_fetch_and_add_1: 2050 case Builtin::BI__sync_fetch_and_add_2: 2051 case Builtin::BI__sync_fetch_and_add_4: 2052 case Builtin::BI__sync_fetch_and_add_8: 2053 case Builtin::BI__sync_fetch_and_add_16: 2054 BuiltinIndex = 0; 2055 break; 2056 2057 case Builtin::BI__sync_fetch_and_sub: 2058 case Builtin::BI__sync_fetch_and_sub_1: 2059 case Builtin::BI__sync_fetch_and_sub_2: 2060 case Builtin::BI__sync_fetch_and_sub_4: 2061 case Builtin::BI__sync_fetch_and_sub_8: 2062 case Builtin::BI__sync_fetch_and_sub_16: 2063 BuiltinIndex = 1; 2064 break; 2065 2066 case Builtin::BI__sync_fetch_and_or: 2067 case Builtin::BI__sync_fetch_and_or_1: 2068 case Builtin::BI__sync_fetch_and_or_2: 2069 case Builtin::BI__sync_fetch_and_or_4: 2070 case Builtin::BI__sync_fetch_and_or_8: 2071 case Builtin::BI__sync_fetch_and_or_16: 2072 BuiltinIndex = 2; 2073 break; 2074 2075 case Builtin::BI__sync_fetch_and_and: 2076 case Builtin::BI__sync_fetch_and_and_1: 2077 case Builtin::BI__sync_fetch_and_and_2: 2078 case Builtin::BI__sync_fetch_and_and_4: 2079 case Builtin::BI__sync_fetch_and_and_8: 2080 case Builtin::BI__sync_fetch_and_and_16: 2081 BuiltinIndex = 3; 2082 break; 2083 2084 case Builtin::BI__sync_fetch_and_xor: 2085 case Builtin::BI__sync_fetch_and_xor_1: 2086 case Builtin::BI__sync_fetch_and_xor_2: 2087 case Builtin::BI__sync_fetch_and_xor_4: 2088 case Builtin::BI__sync_fetch_and_xor_8: 2089 case Builtin::BI__sync_fetch_and_xor_16: 2090 BuiltinIndex = 4; 2091 break; 2092 2093 case Builtin::BI__sync_fetch_and_nand: 2094 case Builtin::BI__sync_fetch_and_nand_1: 2095 case Builtin::BI__sync_fetch_and_nand_2: 2096 case Builtin::BI__sync_fetch_and_nand_4: 2097 case Builtin::BI__sync_fetch_and_nand_8: 2098 case Builtin::BI__sync_fetch_and_nand_16: 2099 BuiltinIndex = 5; 2100 WarnAboutSemanticsChange = true; 2101 break; 2102 2103 case Builtin::BI__sync_add_and_fetch: 2104 case Builtin::BI__sync_add_and_fetch_1: 2105 case Builtin::BI__sync_add_and_fetch_2: 2106 case Builtin::BI__sync_add_and_fetch_4: 2107 case Builtin::BI__sync_add_and_fetch_8: 2108 case Builtin::BI__sync_add_and_fetch_16: 2109 BuiltinIndex = 6; 2110 break; 2111 2112 case Builtin::BI__sync_sub_and_fetch: 2113 case Builtin::BI__sync_sub_and_fetch_1: 2114 case Builtin::BI__sync_sub_and_fetch_2: 2115 case Builtin::BI__sync_sub_and_fetch_4: 2116 case Builtin::BI__sync_sub_and_fetch_8: 2117 case Builtin::BI__sync_sub_and_fetch_16: 2118 BuiltinIndex = 7; 2119 break; 2120 2121 case Builtin::BI__sync_and_and_fetch: 2122 case Builtin::BI__sync_and_and_fetch_1: 2123 case Builtin::BI__sync_and_and_fetch_2: 2124 case Builtin::BI__sync_and_and_fetch_4: 2125 case Builtin::BI__sync_and_and_fetch_8: 2126 case Builtin::BI__sync_and_and_fetch_16: 2127 BuiltinIndex = 8; 2128 break; 2129 2130 case Builtin::BI__sync_or_and_fetch: 2131 case Builtin::BI__sync_or_and_fetch_1: 2132 case Builtin::BI__sync_or_and_fetch_2: 2133 case Builtin::BI__sync_or_and_fetch_4: 2134 case Builtin::BI__sync_or_and_fetch_8: 2135 case Builtin::BI__sync_or_and_fetch_16: 2136 BuiltinIndex = 9; 2137 break; 2138 2139 case Builtin::BI__sync_xor_and_fetch: 2140 case Builtin::BI__sync_xor_and_fetch_1: 2141 case Builtin::BI__sync_xor_and_fetch_2: 2142 case Builtin::BI__sync_xor_and_fetch_4: 2143 case Builtin::BI__sync_xor_and_fetch_8: 2144 case Builtin::BI__sync_xor_and_fetch_16: 2145 BuiltinIndex = 10; 2146 break; 2147 2148 case Builtin::BI__sync_nand_and_fetch: 2149 case Builtin::BI__sync_nand_and_fetch_1: 2150 case Builtin::BI__sync_nand_and_fetch_2: 2151 case Builtin::BI__sync_nand_and_fetch_4: 2152 case Builtin::BI__sync_nand_and_fetch_8: 2153 case Builtin::BI__sync_nand_and_fetch_16: 2154 BuiltinIndex = 11; 2155 WarnAboutSemanticsChange = true; 2156 break; 2157 2158 case Builtin::BI__sync_val_compare_and_swap: 2159 case Builtin::BI__sync_val_compare_and_swap_1: 2160 case Builtin::BI__sync_val_compare_and_swap_2: 2161 case Builtin::BI__sync_val_compare_and_swap_4: 2162 case Builtin::BI__sync_val_compare_and_swap_8: 2163 case Builtin::BI__sync_val_compare_and_swap_16: 2164 BuiltinIndex = 12; 2165 NumFixed = 2; 2166 break; 2167 2168 case Builtin::BI__sync_bool_compare_and_swap: 2169 case Builtin::BI__sync_bool_compare_and_swap_1: 2170 case Builtin::BI__sync_bool_compare_and_swap_2: 2171 case Builtin::BI__sync_bool_compare_and_swap_4: 2172 case Builtin::BI__sync_bool_compare_and_swap_8: 2173 case Builtin::BI__sync_bool_compare_and_swap_16: 2174 BuiltinIndex = 13; 2175 NumFixed = 2; 2176 ResultType = Context.BoolTy; 2177 break; 2178 2179 case Builtin::BI__sync_lock_test_and_set: 2180 case Builtin::BI__sync_lock_test_and_set_1: 2181 case Builtin::BI__sync_lock_test_and_set_2: 2182 case Builtin::BI__sync_lock_test_and_set_4: 2183 case Builtin::BI__sync_lock_test_and_set_8: 2184 case Builtin::BI__sync_lock_test_and_set_16: 2185 BuiltinIndex = 14; 2186 break; 2187 2188 case Builtin::BI__sync_lock_release: 2189 case Builtin::BI__sync_lock_release_1: 2190 case Builtin::BI__sync_lock_release_2: 2191 case Builtin::BI__sync_lock_release_4: 2192 case Builtin::BI__sync_lock_release_8: 2193 case Builtin::BI__sync_lock_release_16: 2194 BuiltinIndex = 15; 2195 NumFixed = 0; 2196 ResultType = Context.VoidTy; 2197 break; 2198 2199 case Builtin::BI__sync_swap: 2200 case Builtin::BI__sync_swap_1: 2201 case Builtin::BI__sync_swap_2: 2202 case Builtin::BI__sync_swap_4: 2203 case Builtin::BI__sync_swap_8: 2204 case Builtin::BI__sync_swap_16: 2205 BuiltinIndex = 16; 2206 break; 2207 } 2208 2209 // Now that we know how many fixed arguments we expect, first check that we 2210 // have at least that many. 2211 if (TheCall->getNumArgs() < 1+NumFixed) { 2212 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 2213 << 0 << 1+NumFixed << TheCall->getNumArgs() 2214 << TheCall->getCallee()->getSourceRange(); 2215 return ExprError(); 2216 } 2217 2218 if (WarnAboutSemanticsChange) { 2219 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 2220 << TheCall->getCallee()->getSourceRange(); 2221 } 2222 2223 // Get the decl for the concrete builtin from this, we can tell what the 2224 // concrete integer type we should convert to is. 2225 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 2226 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 2227 FunctionDecl *NewBuiltinDecl; 2228 if (NewBuiltinID == BuiltinID) 2229 NewBuiltinDecl = FDecl; 2230 else { 2231 // Perform builtin lookup to avoid redeclaring it. 2232 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 2233 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 2234 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 2235 assert(Res.getFoundDecl()); 2236 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 2237 if (!NewBuiltinDecl) 2238 return ExprError(); 2239 } 2240 2241 // The first argument --- the pointer --- has a fixed type; we 2242 // deduce the types of the rest of the arguments accordingly. Walk 2243 // the remaining arguments, converting them to the deduced value type. 2244 for (unsigned i = 0; i != NumFixed; ++i) { 2245 ExprResult Arg = TheCall->getArg(i+1); 2246 2247 // GCC does an implicit conversion to the pointer or integer ValType. This 2248 // can fail in some cases (1i -> int**), check for this error case now. 2249 // Initialize the argument. 2250 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 2251 ValType, /*consume*/ false); 2252 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 2253 if (Arg.isInvalid()) 2254 return ExprError(); 2255 2256 // Okay, we have something that *can* be converted to the right type. Check 2257 // to see if there is a potentially weird extension going on here. This can 2258 // happen when you do an atomic operation on something like an char* and 2259 // pass in 42. The 42 gets converted to char. This is even more strange 2260 // for things like 45.123 -> char, etc. 2261 // FIXME: Do this check. 2262 TheCall->setArg(i+1, Arg.get()); 2263 } 2264 2265 ASTContext& Context = this->getASTContext(); 2266 2267 // Create a new DeclRefExpr to refer to the new decl. 2268 DeclRefExpr* NewDRE = DeclRefExpr::Create( 2269 Context, 2270 DRE->getQualifierLoc(), 2271 SourceLocation(), 2272 NewBuiltinDecl, 2273 /*enclosing*/ false, 2274 DRE->getLocation(), 2275 Context.BuiltinFnTy, 2276 DRE->getValueKind()); 2277 2278 // Set the callee in the CallExpr. 2279 // FIXME: This loses syntactic information. 2280 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 2281 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 2282 CK_BuiltinFnToFnPtr); 2283 TheCall->setCallee(PromotedCall.get()); 2284 2285 // Change the result type of the call to match the original value type. This 2286 // is arbitrary, but the codegen for these builtins ins design to handle it 2287 // gracefully. 2288 TheCall->setType(ResultType); 2289 2290 return TheCallResult; 2291} 2292 2293/// SemaBuiltinNontemporalOverloaded - We have a call to 2294/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 2295/// overloaded function based on the pointer type of its last argument. 2296/// 2297/// This function goes through and does final semantic checking for these 2298/// builtins. 2299ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 2300 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 2301 DeclRefExpr *DRE = 2302 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2303 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 2304 unsigned BuiltinID = FDecl->getBuiltinID(); 2305 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 2306 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 2307 "Unexpected nontemporal load/store builtin!"); 2308 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 2309 unsigned numArgs = isStore ? 2 : 1; 2310 2311 // Ensure that we have the proper number of arguments. 2312 if (checkArgCount(*this, TheCall, numArgs)) 2313 return ExprError(); 2314 2315 // Inspect the last argument of the nontemporal builtin. This should always 2316 // be a pointer type, from which we imply the type of the memory access. 2317 // Because it is a pointer type, we don't have to worry about any implicit 2318 // casts here. 2319 Expr *PointerArg = TheCall->getArg(numArgs - 1); 2320 ExprResult PointerArgResult = 2321 DefaultFunctionArrayLvalueConversion(PointerArg); 2322 2323 if (PointerArgResult.isInvalid()) 2324 return ExprError(); 2325 PointerArg = PointerArgResult.get(); 2326 TheCall->setArg(numArgs - 1, PointerArg); 2327 2328 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2329 if (!pointerType) { 2330 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 2331 << PointerArg->getType() << PointerArg->getSourceRange(); 2332 return ExprError(); 2333 } 2334 2335 QualType ValType = pointerType->getPointeeType(); 2336 2337 // Strip any qualifiers off ValType. 2338 ValType = ValType.getUnqualifiedType(); 2339 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2340 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 2341 !ValType->isVectorType()) { 2342 Diag(DRE->getLocStart(), 2343 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 2344 << PointerArg->getType() << PointerArg->getSourceRange(); 2345 return ExprError(); 2346 } 2347 2348 if (!isStore) { 2349 TheCall->setType(ValType); 2350 return TheCallResult; 2351 } 2352 2353 ExprResult ValArg = TheCall->getArg(0); 2354 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2355 Context, ValType, /*consume*/ false); 2356 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2357 if (ValArg.isInvalid()) 2358 return ExprError(); 2359 2360 TheCall->setArg(0, ValArg.get()); 2361 TheCall->setType(Context.VoidTy); 2362 return TheCallResult; 2363} 2364 2365/// CheckObjCString - Checks that the argument to the builtin 2366/// CFString constructor is correct 2367/// Note: It might also make sense to do the UTF-16 conversion here (would 2368/// simplify the backend). 2369bool Sema::CheckObjCString(Expr *Arg) { 2370 Arg = Arg->IgnoreParenCasts(); 2371 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 2372 2373 if (!Literal || !Literal->isAscii()) { 2374 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 2375 << Arg->getSourceRange(); 2376 return true; 2377 } 2378 2379 if (Literal->containsNonAsciiOrNull()) { 2380 StringRef String = Literal->getString(); 2381 unsigned NumBytes = String.size(); 2382 SmallVector<UTF16, 128> ToBuf(NumBytes); 2383 const UTF8 *FromPtr = (const UTF8 *)String.data(); 2384 UTF16 *ToPtr = &ToBuf[0]; 2385 2386 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 2387 &ToPtr, ToPtr + NumBytes, 2388 strictConversion); 2389 // Check for conversion failure. 2390 if (Result != conversionOK) 2391 Diag(Arg->getLocStart(), 2392 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 2393 } 2394 return false; 2395} 2396 2397/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 2398/// for validity. Emit an error and return true on failure; return false 2399/// on success. 2400bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) { 2401 Expr *Fn = TheCall->getCallee(); 2402 if (TheCall->getNumArgs() > 2) { 2403 Diag(TheCall->getArg(2)->getLocStart(), 2404 diag::err_typecheck_call_too_many_args) 2405 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 2406 << Fn->getSourceRange() 2407 << SourceRange(TheCall->getArg(2)->getLocStart(), 2408 (*(TheCall->arg_end()-1))->getLocEnd()); 2409 return true; 2410 } 2411 2412 if (TheCall->getNumArgs() < 2) { 2413 return Diag(TheCall->getLocEnd(), 2414 diag::err_typecheck_call_too_few_args_at_least) 2415 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 2416 } 2417 2418 // Type-check the first argument normally. 2419 if (checkBuiltinArgument(*this, TheCall, 0)) 2420 return true; 2421 2422 // Determine whether the current function is variadic or not. 2423 BlockScopeInfo *CurBlock = getCurBlock(); 2424 bool isVariadic; 2425 if (CurBlock) 2426 isVariadic = CurBlock->TheDecl->isVariadic(); 2427 else if (FunctionDecl *FD = getCurFunctionDecl()) 2428 isVariadic = FD->isVariadic(); 2429 else 2430 isVariadic = getCurMethodDecl()->isVariadic(); 2431 2432 if (!isVariadic) { 2433 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 2434 return true; 2435 } 2436 2437 // Verify that the second argument to the builtin is the last argument of the 2438 // current function or method. 2439 bool SecondArgIsLastNamedArgument = false; 2440 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 2441 2442 // These are valid if SecondArgIsLastNamedArgument is false after the next 2443 // block. 2444 QualType Type; 2445 SourceLocation ParamLoc; 2446 2447 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 2448 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 2449 // FIXME: This isn't correct for methods (results in bogus warning). 2450 // Get the last formal in the current function. 2451 const ParmVarDecl *LastArg; 2452 if (CurBlock) 2453 LastArg = *(CurBlock->TheDecl->param_end()-1); 2454 else if (FunctionDecl *FD = getCurFunctionDecl()) 2455 LastArg = *(FD->param_end()-1); 2456 else 2457 LastArg = *(getCurMethodDecl()->param_end()-1); 2458 SecondArgIsLastNamedArgument = PV == LastArg; 2459 2460 Type = PV->getType(); 2461 ParamLoc = PV->getLocation(); 2462 } 2463 } 2464 2465 if (!SecondArgIsLastNamedArgument) 2466 Diag(TheCall->getArg(1)->getLocStart(), 2467 diag::warn_second_parameter_of_va_start_not_last_named_argument); 2468 else if (Type->isReferenceType()) { 2469 Diag(Arg->getLocStart(), 2470 diag::warn_va_start_of_reference_type_is_undefined); 2471 Diag(ParamLoc, diag::note_parameter_type) << Type; 2472 } 2473 2474 TheCall->setType(Context.VoidTy); 2475 return false; 2476} 2477 2478/// Check the arguments to '__builtin_va_start' for validity, and that 2479/// it was called from a function of the native ABI. 2480/// Emit an error and return true on failure; return false on success. 2481bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 2482 // On x86-64 Unix, don't allow this in Win64 ABI functions. 2483 // On x64 Windows, don't allow this in System V ABI functions. 2484 // (Yes, that means there's no corresponding way to support variadic 2485 // System V ABI functions on Windows.) 2486 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) { 2487 unsigned OS = Context.getTargetInfo().getTriple().getOS(); 2488 clang::CallingConv CC = CC_C; 2489 if (const FunctionDecl *FD = getCurFunctionDecl()) 2490 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 2491 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) || 2492 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64)) 2493 return Diag(TheCall->getCallee()->getLocStart(), 2494 diag::err_va_start_used_in_wrong_abi_function) 2495 << (OS != llvm::Triple::Win32); 2496 } 2497 return SemaBuiltinVAStartImpl(TheCall); 2498} 2499 2500/// Check the arguments to '__builtin_ms_va_start' for validity, and that 2501/// it was called from a Win64 ABI function. 2502/// Emit an error and return true on failure; return false on success. 2503bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) { 2504 // This only makes sense for x86-64. 2505 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 2506 Expr *Callee = TheCall->getCallee(); 2507 if (TT.getArch() != llvm::Triple::x86_64) 2508 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt); 2509 // Don't allow this in System V ABI functions. 2510 clang::CallingConv CC = CC_C; 2511 if (const FunctionDecl *FD = getCurFunctionDecl()) 2512 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 2513 if (CC == CC_X86_64SysV || 2514 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64)) 2515 return Diag(Callee->getLocStart(), 2516 diag::err_ms_va_start_used_in_sysv_function); 2517 return SemaBuiltinVAStartImpl(TheCall); 2518} 2519 2520bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) { 2521 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 2522 // const char *named_addr); 2523 2524 Expr *Func = Call->getCallee(); 2525 2526 if (Call->getNumArgs() < 3) 2527 return Diag(Call->getLocEnd(), 2528 diag::err_typecheck_call_too_few_args_at_least) 2529 << 0 /*function call*/ << 3 << Call->getNumArgs(); 2530 2531 // Determine whether the current function is variadic or not. 2532 bool IsVariadic; 2533 if (BlockScopeInfo *CurBlock = getCurBlock()) 2534 IsVariadic = CurBlock->TheDecl->isVariadic(); 2535 else if (FunctionDecl *FD = getCurFunctionDecl()) 2536 IsVariadic = FD->isVariadic(); 2537 else if (ObjCMethodDecl *MD = getCurMethodDecl()) 2538 IsVariadic = MD->isVariadic(); 2539 else 2540 llvm_unreachable("unexpected statement type"); 2541 2542 if (!IsVariadic) { 2543 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 2544 return true; 2545 } 2546 2547 // Type-check the first argument normally. 2548 if (checkBuiltinArgument(*this, Call, 0)) 2549 return true; 2550 2551 const struct { 2552 unsigned ArgNo; 2553 QualType Type; 2554 } ArgumentTypes[] = { 2555 { 1, Context.getPointerType(Context.CharTy.withConst()) }, 2556 { 2, Context.getSizeType() }, 2557 }; 2558 2559 for (const auto &AT : ArgumentTypes) { 2560 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens(); 2561 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType()) 2562 continue; 2563 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible) 2564 << Arg->getType() << AT.Type << 1 /* different class */ 2565 << 0 /* qualifier difference */ << 3 /* parameter mismatch */ 2566 << AT.ArgNo + 1 << Arg->getType() << AT.Type; 2567 } 2568 2569 return false; 2570} 2571 2572/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 2573/// friends. This is declared to take (...), so we have to check everything. 2574bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 2575 if (TheCall->getNumArgs() < 2) 2576 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 2577 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 2578 if (TheCall->getNumArgs() > 2) 2579 return Diag(TheCall->getArg(2)->getLocStart(), 2580 diag::err_typecheck_call_too_many_args) 2581 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 2582 << SourceRange(TheCall->getArg(2)->getLocStart(), 2583 (*(TheCall->arg_end()-1))->getLocEnd()); 2584 2585 ExprResult OrigArg0 = TheCall->getArg(0); 2586 ExprResult OrigArg1 = TheCall->getArg(1); 2587 2588 // Do standard promotions between the two arguments, returning their common 2589 // type. 2590 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 2591 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 2592 return true; 2593 2594 // Make sure any conversions are pushed back into the call; this is 2595 // type safe since unordered compare builtins are declared as "_Bool 2596 // foo(...)". 2597 TheCall->setArg(0, OrigArg0.get()); 2598 TheCall->setArg(1, OrigArg1.get()); 2599 2600 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 2601 return false; 2602 2603 // If the common type isn't a real floating type, then the arguments were 2604 // invalid for this operation. 2605 if (Res.isNull() || !Res->isRealFloatingType()) 2606 return Diag(OrigArg0.get()->getLocStart(), 2607 diag::err_typecheck_call_invalid_ordered_compare) 2608 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 2609 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 2610 2611 return false; 2612} 2613 2614/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 2615/// __builtin_isnan and friends. This is declared to take (...), so we have 2616/// to check everything. We expect the last argument to be a floating point 2617/// value. 2618bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 2619 if (TheCall->getNumArgs() < NumArgs) 2620 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 2621 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 2622 if (TheCall->getNumArgs() > NumArgs) 2623 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 2624 diag::err_typecheck_call_too_many_args) 2625 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 2626 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 2627 (*(TheCall->arg_end()-1))->getLocEnd()); 2628 2629 Expr *OrigArg = TheCall->getArg(NumArgs-1); 2630 2631 if (OrigArg->isTypeDependent()) 2632 return false; 2633 2634 // This operation requires a non-_Complex floating-point number. 2635 if (!OrigArg->getType()->isRealFloatingType()) 2636 return Diag(OrigArg->getLocStart(), 2637 diag::err_typecheck_call_invalid_unary_fp) 2638 << OrigArg->getType() << OrigArg->getSourceRange(); 2639 2640 // If this is an implicit conversion from float -> double, remove it. 2641 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 2642 Expr *CastArg = Cast->getSubExpr(); 2643 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 2644 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 2645 "promotion from float to double is the only expected cast here"); 2646 Cast->setSubExpr(nullptr); 2647 TheCall->setArg(NumArgs-1, CastArg); 2648 } 2649 } 2650 2651 return false; 2652} 2653 2654/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 2655// This is declared to take (...), so we have to check everything. 2656ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 2657 if (TheCall->getNumArgs() < 2) 2658 return ExprError(Diag(TheCall->getLocEnd(), 2659 diag::err_typecheck_call_too_few_args_at_least) 2660 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 2661 << TheCall->getSourceRange()); 2662 2663 // Determine which of the following types of shufflevector we're checking: 2664 // 1) unary, vector mask: (lhs, mask) 2665 // 2) binary, vector mask: (lhs, rhs, mask) 2666 // 3) binary, scalar mask: (lhs, rhs, index, ..., index) 2667 QualType resType = TheCall->getArg(0)->getType(); 2668 unsigned numElements = 0; 2669 2670 if (!TheCall->getArg(0)->isTypeDependent() && 2671 !TheCall->getArg(1)->isTypeDependent()) { 2672 QualType LHSType = TheCall->getArg(0)->getType(); 2673 QualType RHSType = TheCall->getArg(1)->getType(); 2674 2675 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 2676 return ExprError(Diag(TheCall->getLocStart(), 2677 diag::err_shufflevector_non_vector) 2678 << SourceRange(TheCall->getArg(0)->getLocStart(), 2679 TheCall->getArg(1)->getLocEnd())); 2680 2681 numElements = LHSType->getAs<VectorType>()->getNumElements(); 2682 unsigned numResElements = TheCall->getNumArgs() - 2; 2683 2684 // Check to see if we have a call with 2 vector arguments, the unary shuffle 2685 // with mask. If so, verify that RHS is an integer vector type with the 2686 // same number of elts as lhs. 2687 if (TheCall->getNumArgs() == 2) { 2688 if (!RHSType->hasIntegerRepresentation() || 2689 RHSType->getAs<VectorType>()->getNumElements() != numElements) 2690 return ExprError(Diag(TheCall->getLocStart(), 2691 diag::err_shufflevector_incompatible_vector) 2692 << SourceRange(TheCall->getArg(1)->getLocStart(), 2693 TheCall->getArg(1)->getLocEnd())); 2694 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 2695 return ExprError(Diag(TheCall->getLocStart(), 2696 diag::err_shufflevector_incompatible_vector) 2697 << SourceRange(TheCall->getArg(0)->getLocStart(), 2698 TheCall->getArg(1)->getLocEnd())); 2699 } else if (numElements != numResElements) { 2700 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 2701 resType = Context.getVectorType(eltType, numResElements, 2702 VectorType::GenericVector); 2703 } 2704 } 2705 2706 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 2707 if (TheCall->getArg(i)->isTypeDependent() || 2708 TheCall->getArg(i)->isValueDependent()) 2709 continue; 2710 2711 llvm::APSInt Result(32); 2712 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 2713 return ExprError(Diag(TheCall->getLocStart(), 2714 diag::err_shufflevector_nonconstant_argument) 2715 << TheCall->getArg(i)->getSourceRange()); 2716 2717 // Allow -1 which will be translated to undef in the IR. 2718 if (Result.isSigned() && Result.isAllOnesValue()) 2719 continue; 2720 2721 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 2722 return ExprError(Diag(TheCall->getLocStart(), 2723 diag::err_shufflevector_argument_too_large) 2724 << TheCall->getArg(i)->getSourceRange()); 2725 } 2726 2727 SmallVector<Expr*, 32> exprs; 2728 2729 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 2730 exprs.push_back(TheCall->getArg(i)); 2731 TheCall->setArg(i, nullptr); 2732 } 2733 2734 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 2735 TheCall->getCallee()->getLocStart(), 2736 TheCall->getRParenLoc()); 2737} 2738 2739/// SemaConvertVectorExpr - Handle __builtin_convertvector 2740ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 2741 SourceLocation BuiltinLoc, 2742 SourceLocation RParenLoc) { 2743 ExprValueKind VK = VK_RValue; 2744 ExprObjectKind OK = OK_Ordinary; 2745 QualType DstTy = TInfo->getType(); 2746 QualType SrcTy = E->getType(); 2747 2748 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 2749 return ExprError(Diag(BuiltinLoc, 2750 diag::err_convertvector_non_vector) 2751 << E->getSourceRange()); 2752 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 2753 return ExprError(Diag(BuiltinLoc, 2754 diag::err_convertvector_non_vector_type)); 2755 2756 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 2757 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 2758 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 2759 if (SrcElts != DstElts) 2760 return ExprError(Diag(BuiltinLoc, 2761 diag::err_convertvector_incompatible_vector) 2762 << E->getSourceRange()); 2763 } 2764 2765 return new (Context) 2766 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 2767} 2768 2769/// SemaBuiltinPrefetch - Handle __builtin_prefetch. 2770// This is declared to take (const void*, ...) and can take two 2771// optional constant int args. 2772bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 2773 unsigned NumArgs = TheCall->getNumArgs(); 2774 2775 if (NumArgs > 3) 2776 return Diag(TheCall->getLocEnd(), 2777 diag::err_typecheck_call_too_many_args_at_most) 2778 << 0 /*function call*/ << 3 << NumArgs 2779 << TheCall->getSourceRange(); 2780 2781 // Argument 0 is checked for us and the remaining arguments must be 2782 // constant integers. 2783 for (unsigned i = 1; i != NumArgs; ++i) 2784 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 2785 return true; 2786 2787 return false; 2788} 2789 2790/// SemaBuiltinAssume - Handle __assume (MS Extension). 2791// __assume does not evaluate its arguments, and should warn if its argument 2792// has side effects. 2793bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 2794 Expr *Arg = TheCall->getArg(0); 2795 if (Arg->isInstantiationDependent()) return false; 2796 2797 if (Arg->HasSideEffects(Context)) 2798 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 2799 << Arg->getSourceRange() 2800 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 2801 2802 return false; 2803} 2804 2805/// Handle __builtin_assume_aligned. This is declared 2806/// as (const void*, size_t, ...) and can take one optional constant int arg. 2807bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 2808 unsigned NumArgs = TheCall->getNumArgs(); 2809 2810 if (NumArgs > 3) 2811 return Diag(TheCall->getLocEnd(), 2812 diag::err_typecheck_call_too_many_args_at_most) 2813 << 0 /*function call*/ << 3 << NumArgs 2814 << TheCall->getSourceRange(); 2815 2816 // The alignment must be a constant integer. 2817 Expr *Arg = TheCall->getArg(1); 2818 2819 // We can't check the value of a dependent argument. 2820 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 2821 llvm::APSInt Result; 2822 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 2823 return true; 2824 2825 if (!Result.isPowerOf2()) 2826 return Diag(TheCall->getLocStart(), 2827 diag::err_alignment_not_power_of_two) 2828 << Arg->getSourceRange(); 2829 } 2830 2831 if (NumArgs > 2) { 2832 ExprResult Arg(TheCall->getArg(2)); 2833 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 2834 Context.getSizeType(), false); 2835 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 2836 if (Arg.isInvalid()) return true; 2837 TheCall->setArg(2, Arg.get()); 2838 } 2839 2840 return false; 2841} 2842 2843/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 2844/// TheCall is a constant expression. 2845bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 2846 llvm::APSInt &Result) { 2847 Expr *Arg = TheCall->getArg(ArgNum); 2848 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2849 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 2850 2851 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 2852 2853 if (!Arg->isIntegerConstantExpr(Result, Context)) 2854 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 2855 << FDecl->getDeclName() << Arg->getSourceRange(); 2856 2857 return false; 2858} 2859 2860/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 2861/// TheCall is a constant expression in the range [Low, High]. 2862bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 2863 int Low, int High) { 2864 llvm::APSInt Result; 2865 2866 // We can't check the value of a dependent argument. 2867 Expr *Arg = TheCall->getArg(ArgNum); 2868 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2869 return false; 2870 2871 // Check constant-ness first. 2872 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2873 return true; 2874 2875 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 2876 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 2877 << Low << High << Arg->getSourceRange(); 2878 2879 return false; 2880} 2881 2882/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 2883/// TheCall is an ARM/AArch64 special register string literal. 2884bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 2885 int ArgNum, unsigned ExpectedFieldNum, 2886 bool AllowName) { 2887 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 2888 BuiltinID == ARM::BI__builtin_arm_wsr64 || 2889 BuiltinID == ARM::BI__builtin_arm_rsr || 2890 BuiltinID == ARM::BI__builtin_arm_rsrp || 2891 BuiltinID == ARM::BI__builtin_arm_wsr || 2892 BuiltinID == ARM::BI__builtin_arm_wsrp; 2893 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2894 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 2895 BuiltinID == AArch64::BI__builtin_arm_rsr || 2896 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2897 BuiltinID == AArch64::BI__builtin_arm_wsr || 2898 BuiltinID == AArch64::BI__builtin_arm_wsrp; 2899 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 2900 2901 // We can't check the value of a dependent argument. 2902 Expr *Arg = TheCall->getArg(ArgNum); 2903 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2904 return false; 2905 2906 // Check if the argument is a string literal. 2907 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 2908 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 2909 << Arg->getSourceRange(); 2910 2911 // Check the type of special register given. 2912 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 2913 SmallVector<StringRef, 6> Fields; 2914 Reg.split(Fields, ":"); 2915 2916 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 2917 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 2918 << Arg->getSourceRange(); 2919 2920 // If the string is the name of a register then we cannot check that it is 2921 // valid here but if the string is of one the forms described in ACLE then we 2922 // can check that the supplied fields are integers and within the valid 2923 // ranges. 2924 if (Fields.size() > 1) { 2925 bool FiveFields = Fields.size() == 5; 2926 2927 bool ValidString = true; 2928 if (IsARMBuiltin) { 2929 ValidString &= Fields[0].startswith_lower("cp") || 2930 Fields[0].startswith_lower("p"); 2931 if (ValidString) 2932 Fields[0] = 2933 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 2934 2935 ValidString &= Fields[2].startswith_lower("c"); 2936 if (ValidString) 2937 Fields[2] = Fields[2].drop_front(1); 2938 2939 if (FiveFields) { 2940 ValidString &= Fields[3].startswith_lower("c"); 2941 if (ValidString) 2942 Fields[3] = Fields[3].drop_front(1); 2943 } 2944 } 2945 2946 SmallVector<int, 5> Ranges; 2947 if (FiveFields) 2948 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15}); 2949 else 2950 Ranges.append({15, 7, 15}); 2951 2952 for (unsigned i=0; i<Fields.size(); ++i) { 2953 int IntField; 2954 ValidString &= !Fields[i].getAsInteger(10, IntField); 2955 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 2956 } 2957 2958 if (!ValidString) 2959 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 2960 << Arg->getSourceRange(); 2961 2962 } else if (IsAArch64Builtin && Fields.size() == 1) { 2963 // If the register name is one of those that appear in the condition below 2964 // and the special register builtin being used is one of the write builtins, 2965 // then we require that the argument provided for writing to the register 2966 // is an integer constant expression. This is because it will be lowered to 2967 // an MSR (immediate) instruction, so we need to know the immediate at 2968 // compile time. 2969 if (TheCall->getNumArgs() != 2) 2970 return false; 2971 2972 std::string RegLower = Reg.lower(); 2973 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 2974 RegLower != "pan" && RegLower != "uao") 2975 return false; 2976 2977 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2978 } 2979 2980 return false; 2981} 2982 2983/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 2984/// This checks that the target supports __builtin_longjmp and 2985/// that val is a constant 1. 2986bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 2987 if (!Context.getTargetInfo().hasSjLjLowering()) 2988 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 2989 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 2990 2991 Expr *Arg = TheCall->getArg(1); 2992 llvm::APSInt Result; 2993 2994 // TODO: This is less than ideal. Overload this to take a value. 2995 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 2996 return true; 2997 2998 if (Result != 1) 2999 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 3000 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 3001 3002 return false; 3003} 3004 3005 3006/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 3007/// This checks that the target supports __builtin_setjmp. 3008bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 3009 if (!Context.getTargetInfo().hasSjLjLowering()) 3010 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 3011 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 3012 return false; 3013} 3014 3015namespace { 3016enum StringLiteralCheckType { 3017 SLCT_NotALiteral, 3018 SLCT_UncheckedLiteral, 3019 SLCT_CheckedLiteral 3020}; 3021} 3022 3023// Determine if an expression is a string literal or constant string. 3024// If this function returns false on the arguments to a function expecting a 3025// format string, we will usually need to emit a warning. 3026// True string literals are then checked by CheckFormatString. 3027static StringLiteralCheckType 3028checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 3029 bool HasVAListArg, unsigned format_idx, 3030 unsigned firstDataArg, Sema::FormatStringType Type, 3031 Sema::VariadicCallType CallType, bool InFunctionCall, 3032 llvm::SmallBitVector &CheckedVarArgs) { 3033 tryAgain: 3034 if (E->isTypeDependent() || E->isValueDependent()) 3035 return SLCT_NotALiteral; 3036 3037 E = E->IgnoreParenCasts(); 3038 3039 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 3040 // Technically -Wformat-nonliteral does not warn about this case. 3041 // The behavior of printf and friends in this case is implementation 3042 // dependent. Ideally if the format string cannot be null then 3043 // it should have a 'nonnull' attribute in the function prototype. 3044 return SLCT_UncheckedLiteral; 3045 3046 switch (E->getStmtClass()) { 3047 case Stmt::BinaryConditionalOperatorClass: 3048 case Stmt::ConditionalOperatorClass: { 3049 // The expression is a literal if both sub-expressions were, and it was 3050 // completely checked only if both sub-expressions were checked. 3051 const AbstractConditionalOperator *C = 3052 cast<AbstractConditionalOperator>(E); 3053 StringLiteralCheckType Left = 3054 checkFormatStringExpr(S, C->getTrueExpr(), Args, 3055 HasVAListArg, format_idx, firstDataArg, 3056 Type, CallType, InFunctionCall, CheckedVarArgs); 3057 if (Left == SLCT_NotALiteral) 3058 return SLCT_NotALiteral; 3059 StringLiteralCheckType Right = 3060 checkFormatStringExpr(S, C->getFalseExpr(), Args, 3061 HasVAListArg, format_idx, firstDataArg, 3062 Type, CallType, InFunctionCall, CheckedVarArgs); 3063 return Left < Right ? Left : Right; 3064 } 3065 3066 case Stmt::ImplicitCastExprClass: { 3067 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 3068 goto tryAgain; 3069 } 3070 3071 case Stmt::OpaqueValueExprClass: 3072 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 3073 E = src; 3074 goto tryAgain; 3075 } 3076 return SLCT_NotALiteral; 3077 3078 case Stmt::PredefinedExprClass: 3079 // While __func__, etc., are technically not string literals, they 3080 // cannot contain format specifiers and thus are not a security 3081 // liability. 3082 return SLCT_UncheckedLiteral; 3083 3084 case Stmt::DeclRefExprClass: { 3085 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 3086 3087 // As an exception, do not flag errors for variables binding to 3088 // const string literals. 3089 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 3090 bool isConstant = false; 3091 QualType T = DR->getType(); 3092 3093 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 3094 isConstant = AT->getElementType().isConstant(S.Context); 3095 } else if (const PointerType *PT = T->getAs<PointerType>()) { 3096 isConstant = T.isConstant(S.Context) && 3097 PT->getPointeeType().isConstant(S.Context); 3098 } else if (T->isObjCObjectPointerType()) { 3099 // In ObjC, there is usually no "const ObjectPointer" type, 3100 // so don't check if the pointee type is constant. 3101 isConstant = T.isConstant(S.Context); 3102 } 3103 3104 if (isConstant) { 3105 if (const Expr *Init = VD->getAnyInitializer()) { 3106 // Look through initializers like const char c[] = { "foo" } 3107 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3108 if (InitList->isStringLiteralInit()) 3109 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 3110 } 3111 return checkFormatStringExpr(S, Init, Args, 3112 HasVAListArg, format_idx, 3113 firstDataArg, Type, CallType, 3114 /*InFunctionCall*/false, CheckedVarArgs); 3115 } 3116 } 3117 3118 // For vprintf* functions (i.e., HasVAListArg==true), we add a 3119 // special check to see if the format string is a function parameter 3120 // of the function calling the printf function. If the function 3121 // has an attribute indicating it is a printf-like function, then we 3122 // should suppress warnings concerning non-literals being used in a call 3123 // to a vprintf function. For example: 3124 // 3125 // void 3126 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 3127 // va_list ap; 3128 // va_start(ap, fmt); 3129 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 3130 // ... 3131 // } 3132 if (HasVAListArg) { 3133 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 3134 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 3135 int PVIndex = PV->getFunctionScopeIndex() + 1; 3136 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 3137 // adjust for implicit parameter 3138 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 3139 if (MD->isInstance()) 3140 ++PVIndex; 3141 // We also check if the formats are compatible. 3142 // We can't pass a 'scanf' string to a 'printf' function. 3143 if (PVIndex == PVFormat->getFormatIdx() && 3144 Type == S.GetFormatStringType(PVFormat)) 3145 return SLCT_UncheckedLiteral; 3146 } 3147 } 3148 } 3149 } 3150 } 3151 3152 return SLCT_NotALiteral; 3153 } 3154 3155 case Stmt::CallExprClass: 3156 case Stmt::CXXMemberCallExprClass: { 3157 const CallExpr *CE = cast<CallExpr>(E); 3158 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 3159 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 3160 unsigned ArgIndex = FA->getFormatIdx(); 3161 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 3162 if (MD->isInstance()) 3163 --ArgIndex; 3164 const Expr *Arg = CE->getArg(ArgIndex - 1); 3165 3166 return checkFormatStringExpr(S, Arg, Args, 3167 HasVAListArg, format_idx, firstDataArg, 3168 Type, CallType, InFunctionCall, 3169 CheckedVarArgs); 3170 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 3171 unsigned BuiltinID = FD->getBuiltinID(); 3172 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 3173 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 3174 const Expr *Arg = CE->getArg(0); 3175 return checkFormatStringExpr(S, Arg, Args, 3176 HasVAListArg, format_idx, 3177 firstDataArg, Type, CallType, 3178 InFunctionCall, CheckedVarArgs); 3179 } 3180 } 3181 } 3182 3183 return SLCT_NotALiteral; 3184 } 3185 case Stmt::ObjCStringLiteralClass: 3186 case Stmt::StringLiteralClass: { 3187 const StringLiteral *StrE = nullptr; 3188 3189 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 3190 StrE = ObjCFExpr->getString(); 3191 else 3192 StrE = cast<StringLiteral>(E); 3193 3194 if (StrE) { 3195 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg, 3196 Type, InFunctionCall, CallType, CheckedVarArgs); 3197 return SLCT_CheckedLiteral; 3198 } 3199 3200 return SLCT_NotALiteral; 3201 } 3202 3203 default: 3204 return SLCT_NotALiteral; 3205 } 3206} 3207 3208Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 3209 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 3210 .Case("scanf", FST_Scanf) 3211 .Cases("printf", "printf0", FST_Printf) 3212 .Cases("NSString", "CFString", FST_NSString) 3213 .Case("strftime", FST_Strftime) 3214 .Case("strfmon", FST_Strfmon) 3215 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 3216 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 3217 .Case("os_trace", FST_OSTrace) 3218 .Default(FST_Unknown); 3219} 3220 3221/// CheckFormatArguments - Check calls to printf and scanf (and similar 3222/// functions) for correct use of format strings. 3223/// Returns true if a format string has been fully checked. 3224bool Sema::CheckFormatArguments(const FormatAttr *Format, 3225 ArrayRef<const Expr *> Args, 3226 bool IsCXXMember, 3227 VariadicCallType CallType, 3228 SourceLocation Loc, SourceRange Range, 3229 llvm::SmallBitVector &CheckedVarArgs) { 3230 FormatStringInfo FSI; 3231 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 3232 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 3233 FSI.FirstDataArg, GetFormatStringType(Format), 3234 CallType, Loc, Range, CheckedVarArgs); 3235 return false; 3236} 3237 3238bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 3239 bool HasVAListArg, unsigned format_idx, 3240 unsigned firstDataArg, FormatStringType Type, 3241 VariadicCallType CallType, 3242 SourceLocation Loc, SourceRange Range, 3243 llvm::SmallBitVector &CheckedVarArgs) { 3244 // CHECK: printf/scanf-like function is called with no format string. 3245 if (format_idx >= Args.size()) { 3246 Diag(Loc, diag::warn_missing_format_string) << Range; 3247 return false; 3248 } 3249 3250 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 3251 3252 // CHECK: format string is not a string literal. 3253 // 3254 // Dynamically generated format strings are difficult to 3255 // automatically vet at compile time. Requiring that format strings 3256 // are string literals: (1) permits the checking of format strings by 3257 // the compiler and thereby (2) can practically remove the source of 3258 // many format string exploits. 3259 3260 // Format string can be either ObjC string (e.g. @"%d") or 3261 // C string (e.g. "%d") 3262 // ObjC string uses the same format specifiers as C string, so we can use 3263 // the same format string checking logic for both ObjC and C strings. 3264 StringLiteralCheckType CT = 3265 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 3266 format_idx, firstDataArg, Type, CallType, 3267 /*IsFunctionCall*/true, CheckedVarArgs); 3268 if (CT != SLCT_NotALiteral) 3269 // Literal format string found, check done! 3270 return CT == SLCT_CheckedLiteral; 3271 3272 // Strftime is particular as it always uses a single 'time' argument, 3273 // so it is safe to pass a non-literal string. 3274 if (Type == FST_Strftime) 3275 return false; 3276 3277 // Do not emit diag when the string param is a macro expansion and the 3278 // format is either NSString or CFString. This is a hack to prevent 3279 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 3280 // which are usually used in place of NS and CF string literals. 3281 if (Type == FST_NSString && 3282 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart())) 3283 return false; 3284 3285 // If there are no arguments specified, warn with -Wformat-security, otherwise 3286 // warn only with -Wformat-nonliteral. 3287 if (Args.size() == firstDataArg) 3288 Diag(Args[format_idx]->getLocStart(), 3289 diag::warn_format_nonliteral_noargs) 3290 << OrigFormatExpr->getSourceRange(); 3291 else 3292 Diag(Args[format_idx]->getLocStart(), 3293 diag::warn_format_nonliteral) 3294 << OrigFormatExpr->getSourceRange(); 3295 return false; 3296} 3297 3298namespace { 3299class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 3300protected: 3301 Sema &S; 3302 const StringLiteral *FExpr; 3303 const Expr *OrigFormatExpr; 3304 const unsigned FirstDataArg; 3305 const unsigned NumDataArgs; 3306 const char *Beg; // Start of format string. 3307 const bool HasVAListArg; 3308 ArrayRef<const Expr *> Args; 3309 unsigned FormatIdx; 3310 llvm::SmallBitVector CoveredArgs; 3311 bool usesPositionalArgs; 3312 bool atFirstArg; 3313 bool inFunctionCall; 3314 Sema::VariadicCallType CallType; 3315 llvm::SmallBitVector &CheckedVarArgs; 3316public: 3317 CheckFormatHandler(Sema &s, const StringLiteral *fexpr, 3318 const Expr *origFormatExpr, unsigned firstDataArg, 3319 unsigned numDataArgs, const char *beg, bool hasVAListArg, 3320 ArrayRef<const Expr *> Args, 3321 unsigned formatIdx, bool inFunctionCall, 3322 Sema::VariadicCallType callType, 3323 llvm::SmallBitVector &CheckedVarArgs) 3324 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 3325 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), 3326 Beg(beg), HasVAListArg(hasVAListArg), 3327 Args(Args), FormatIdx(formatIdx), 3328 usesPositionalArgs(false), atFirstArg(true), 3329 inFunctionCall(inFunctionCall), CallType(callType), 3330 CheckedVarArgs(CheckedVarArgs) { 3331 CoveredArgs.resize(numDataArgs); 3332 CoveredArgs.reset(); 3333 } 3334 3335 void DoneProcessing(); 3336 3337 void HandleIncompleteSpecifier(const char *startSpecifier, 3338 unsigned specifierLen) override; 3339 3340 void HandleInvalidLengthModifier( 3341 const analyze_format_string::FormatSpecifier &FS, 3342 const analyze_format_string::ConversionSpecifier &CS, 3343 const char *startSpecifier, unsigned specifierLen, 3344 unsigned DiagID); 3345 3346 void HandleNonStandardLengthModifier( 3347 const analyze_format_string::FormatSpecifier &FS, 3348 const char *startSpecifier, unsigned specifierLen); 3349 3350 void HandleNonStandardConversionSpecifier( 3351 const analyze_format_string::ConversionSpecifier &CS, 3352 const char *startSpecifier, unsigned specifierLen); 3353 3354 void HandlePosition(const char *startPos, unsigned posLen) override; 3355 3356 void HandleInvalidPosition(const char *startSpecifier, 3357 unsigned specifierLen, 3358 analyze_format_string::PositionContext p) override; 3359 3360 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 3361 3362 void HandleNullChar(const char *nullCharacter) override; 3363 3364 template <typename Range> 3365 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall, 3366 const Expr *ArgumentExpr, 3367 PartialDiagnostic PDiag, 3368 SourceLocation StringLoc, 3369 bool IsStringLocation, Range StringRange, 3370 ArrayRef<FixItHint> Fixit = None); 3371 3372protected: 3373 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 3374 const char *startSpec, 3375 unsigned specifierLen, 3376 const char *csStart, unsigned csLen); 3377 3378 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 3379 const char *startSpec, 3380 unsigned specifierLen); 3381 3382 SourceRange getFormatStringRange(); 3383 CharSourceRange getSpecifierRange(const char *startSpecifier, 3384 unsigned specifierLen); 3385 SourceLocation getLocationOfByte(const char *x); 3386 3387 const Expr *getDataArg(unsigned i) const; 3388 3389 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 3390 const analyze_format_string::ConversionSpecifier &CS, 3391 const char *startSpecifier, unsigned specifierLen, 3392 unsigned argIndex); 3393 3394 template <typename Range> 3395 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 3396 bool IsStringLocation, Range StringRange, 3397 ArrayRef<FixItHint> Fixit = None); 3398}; 3399} 3400 3401SourceRange CheckFormatHandler::getFormatStringRange() { 3402 return OrigFormatExpr->getSourceRange(); 3403} 3404 3405CharSourceRange CheckFormatHandler:: 3406getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 3407 SourceLocation Start = getLocationOfByte(startSpecifier); 3408 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 3409 3410 // Advance the end SourceLocation by one due to half-open ranges. 3411 End = End.getLocWithOffset(1); 3412 3413 return CharSourceRange::getCharRange(Start, End); 3414} 3415 3416SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 3417 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 3418} 3419 3420void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 3421 unsigned specifierLen){ 3422 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 3423 getLocationOfByte(startSpecifier), 3424 /*IsStringLocation*/true, 3425 getSpecifierRange(startSpecifier, specifierLen)); 3426} 3427 3428void CheckFormatHandler::HandleInvalidLengthModifier( 3429 const analyze_format_string::FormatSpecifier &FS, 3430 const analyze_format_string::ConversionSpecifier &CS, 3431 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 3432 using namespace analyze_format_string; 3433 3434 const LengthModifier &LM = FS.getLengthModifier(); 3435 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 3436 3437 // See if we know how to fix this length modifier. 3438 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 3439 if (FixedLM) { 3440 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 3441 getLocationOfByte(LM.getStart()), 3442 /*IsStringLocation*/true, 3443 getSpecifierRange(startSpecifier, specifierLen)); 3444 3445 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 3446 << FixedLM->toString() 3447 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 3448 3449 } else { 3450 FixItHint Hint; 3451 if (DiagID == diag::warn_format_nonsensical_length) 3452 Hint = FixItHint::CreateRemoval(LMRange); 3453 3454 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 3455 getLocationOfByte(LM.getStart()), 3456 /*IsStringLocation*/true, 3457 getSpecifierRange(startSpecifier, specifierLen), 3458 Hint); 3459 } 3460} 3461 3462void CheckFormatHandler::HandleNonStandardLengthModifier( 3463 const analyze_format_string::FormatSpecifier &FS, 3464 const char *startSpecifier, unsigned specifierLen) { 3465 using namespace analyze_format_string; 3466 3467 const LengthModifier &LM = FS.getLengthModifier(); 3468 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 3469 3470 // See if we know how to fix this length modifier. 3471 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 3472 if (FixedLM) { 3473 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 3474 << LM.toString() << 0, 3475 getLocationOfByte(LM.getStart()), 3476 /*IsStringLocation*/true, 3477 getSpecifierRange(startSpecifier, specifierLen)); 3478 3479 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 3480 << FixedLM->toString() 3481 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 3482 3483 } else { 3484 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 3485 << LM.toString() << 0, 3486 getLocationOfByte(LM.getStart()), 3487 /*IsStringLocation*/true, 3488 getSpecifierRange(startSpecifier, specifierLen)); 3489 } 3490} 3491 3492void CheckFormatHandler::HandleNonStandardConversionSpecifier( 3493 const analyze_format_string::ConversionSpecifier &CS, 3494 const char *startSpecifier, unsigned specifierLen) { 3495 using namespace analyze_format_string; 3496 3497 // See if we know how to fix this conversion specifier. 3498 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 3499 if (FixedCS) { 3500 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 3501 << CS.toString() << /*conversion specifier*/1, 3502 getLocationOfByte(CS.getStart()), 3503 /*IsStringLocation*/true, 3504 getSpecifierRange(startSpecifier, specifierLen)); 3505 3506 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 3507 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 3508 << FixedCS->toString() 3509 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 3510 } else { 3511 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 3512 << CS.toString() << /*conversion specifier*/1, 3513 getLocationOfByte(CS.getStart()), 3514 /*IsStringLocation*/true, 3515 getSpecifierRange(startSpecifier, specifierLen)); 3516 } 3517} 3518 3519void CheckFormatHandler::HandlePosition(const char *startPos, 3520 unsigned posLen) { 3521 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 3522 getLocationOfByte(startPos), 3523 /*IsStringLocation*/true, 3524 getSpecifierRange(startPos, posLen)); 3525} 3526 3527void 3528CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 3529 analyze_format_string::PositionContext p) { 3530 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 3531 << (unsigned) p, 3532 getLocationOfByte(startPos), /*IsStringLocation*/true, 3533 getSpecifierRange(startPos, posLen)); 3534} 3535 3536void CheckFormatHandler::HandleZeroPosition(const char *startPos, 3537 unsigned posLen) { 3538 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 3539 getLocationOfByte(startPos), 3540 /*IsStringLocation*/true, 3541 getSpecifierRange(startPos, posLen)); 3542} 3543 3544void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 3545 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 3546 // The presence of a null character is likely an error. 3547 EmitFormatDiagnostic( 3548 S.PDiag(diag::warn_printf_format_string_contains_null_char), 3549 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 3550 getFormatStringRange()); 3551 } 3552} 3553 3554// Note that this may return NULL if there was an error parsing or building 3555// one of the argument expressions. 3556const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 3557 return Args[FirstDataArg + i]; 3558} 3559 3560void CheckFormatHandler::DoneProcessing() { 3561 // Does the number of data arguments exceed the number of 3562 // format conversions in the format string? 3563 if (!HasVAListArg) { 3564 // Find any arguments that weren't covered. 3565 CoveredArgs.flip(); 3566 signed notCoveredArg = CoveredArgs.find_first(); 3567 if (notCoveredArg >= 0) { 3568 assert((unsigned)notCoveredArg < NumDataArgs); 3569 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) { 3570 SourceLocation Loc = E->getLocStart(); 3571 if (!S.getSourceManager().isInSystemMacro(Loc)) { 3572 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used), 3573 Loc, /*IsStringLocation*/false, 3574 getFormatStringRange()); 3575 } 3576 } 3577 } 3578 } 3579} 3580 3581bool 3582CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 3583 SourceLocation Loc, 3584 const char *startSpec, 3585 unsigned specifierLen, 3586 const char *csStart, 3587 unsigned csLen) { 3588 3589 bool keepGoing = true; 3590 if (argIndex < NumDataArgs) { 3591 // Consider the argument coverered, even though the specifier doesn't 3592 // make sense. 3593 CoveredArgs.set(argIndex); 3594 } 3595 else { 3596 // If argIndex exceeds the number of data arguments we 3597 // don't issue a warning because that is just a cascade of warnings (and 3598 // they may have intended '%%' anyway). We don't want to continue processing 3599 // the format string after this point, however, as we will like just get 3600 // gibberish when trying to match arguments. 3601 keepGoing = false; 3602 } 3603 3604 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion) 3605 << StringRef(csStart, csLen), 3606 Loc, /*IsStringLocation*/true, 3607 getSpecifierRange(startSpec, specifierLen)); 3608 3609 return keepGoing; 3610} 3611 3612void 3613CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 3614 const char *startSpec, 3615 unsigned specifierLen) { 3616 EmitFormatDiagnostic( 3617 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 3618 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 3619} 3620 3621bool 3622CheckFormatHandler::CheckNumArgs( 3623 const analyze_format_string::FormatSpecifier &FS, 3624 const analyze_format_string::ConversionSpecifier &CS, 3625 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 3626 3627 if (argIndex >= NumDataArgs) { 3628 PartialDiagnostic PDiag = FS.usesPositionalArg() 3629 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 3630 << (argIndex+1) << NumDataArgs) 3631 : S.PDiag(diag::warn_printf_insufficient_data_args); 3632 EmitFormatDiagnostic( 3633 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 3634 getSpecifierRange(startSpecifier, specifierLen)); 3635 return false; 3636 } 3637 return true; 3638} 3639 3640template<typename Range> 3641void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 3642 SourceLocation Loc, 3643 bool IsStringLocation, 3644 Range StringRange, 3645 ArrayRef<FixItHint> FixIt) { 3646 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 3647 Loc, IsStringLocation, StringRange, FixIt); 3648} 3649 3650/// \brief If the format string is not within the funcion call, emit a note 3651/// so that the function call and string are in diagnostic messages. 3652/// 3653/// \param InFunctionCall if true, the format string is within the function 3654/// call and only one diagnostic message will be produced. Otherwise, an 3655/// extra note will be emitted pointing to location of the format string. 3656/// 3657/// \param ArgumentExpr the expression that is passed as the format string 3658/// argument in the function call. Used for getting locations when two 3659/// diagnostics are emitted. 3660/// 3661/// \param PDiag the callee should already have provided any strings for the 3662/// diagnostic message. This function only adds locations and fixits 3663/// to diagnostics. 3664/// 3665/// \param Loc primary location for diagnostic. If two diagnostics are 3666/// required, one will be at Loc and a new SourceLocation will be created for 3667/// the other one. 3668/// 3669/// \param IsStringLocation if true, Loc points to the format string should be 3670/// used for the note. Otherwise, Loc points to the argument list and will 3671/// be used with PDiag. 3672/// 3673/// \param StringRange some or all of the string to highlight. This is 3674/// templated so it can accept either a CharSourceRange or a SourceRange. 3675/// 3676/// \param FixIt optional fix it hint for the format string. 3677template<typename Range> 3678void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall, 3679 const Expr *ArgumentExpr, 3680 PartialDiagnostic PDiag, 3681 SourceLocation Loc, 3682 bool IsStringLocation, 3683 Range StringRange, 3684 ArrayRef<FixItHint> FixIt) { 3685 if (InFunctionCall) { 3686 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 3687 D << StringRange; 3688 D << FixIt; 3689 } else { 3690 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 3691 << ArgumentExpr->getSourceRange(); 3692 3693 const Sema::SemaDiagnosticBuilder &Note = 3694 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 3695 diag::note_format_string_defined); 3696 3697 Note << StringRange; 3698 Note << FixIt; 3699 } 3700} 3701 3702//===--- CHECK: Printf format string checking ------------------------------===// 3703 3704namespace { 3705class CheckPrintfHandler : public CheckFormatHandler { 3706 bool ObjCContext; 3707public: 3708 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 3709 const Expr *origFormatExpr, unsigned firstDataArg, 3710 unsigned numDataArgs, bool isObjC, 3711 const char *beg, bool hasVAListArg, 3712 ArrayRef<const Expr *> Args, 3713 unsigned formatIdx, bool inFunctionCall, 3714 Sema::VariadicCallType CallType, 3715 llvm::SmallBitVector &CheckedVarArgs) 3716 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 3717 numDataArgs, beg, hasVAListArg, Args, 3718 formatIdx, inFunctionCall, CallType, CheckedVarArgs), 3719 ObjCContext(isObjC) 3720 {} 3721 3722 3723 bool HandleInvalidPrintfConversionSpecifier( 3724 const analyze_printf::PrintfSpecifier &FS, 3725 const char *startSpecifier, 3726 unsigned specifierLen) override; 3727 3728 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 3729 const char *startSpecifier, 3730 unsigned specifierLen) override; 3731 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 3732 const char *StartSpecifier, 3733 unsigned SpecifierLen, 3734 const Expr *E); 3735 3736 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 3737 const char *startSpecifier, unsigned specifierLen); 3738 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 3739 const analyze_printf::OptionalAmount &Amt, 3740 unsigned type, 3741 const char *startSpecifier, unsigned specifierLen); 3742 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 3743 const analyze_printf::OptionalFlag &flag, 3744 const char *startSpecifier, unsigned specifierLen); 3745 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 3746 const analyze_printf::OptionalFlag &ignoredFlag, 3747 const analyze_printf::OptionalFlag &flag, 3748 const char *startSpecifier, unsigned specifierLen); 3749 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 3750 const Expr *E); 3751 3752 void HandleEmptyObjCModifierFlag(const char *startFlag, 3753 unsigned flagLen) override; 3754 3755 void HandleInvalidObjCModifierFlag(const char *startFlag, 3756 unsigned flagLen) override; 3757 3758 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 3759 const char *flagsEnd, 3760 const char *conversionPosition) 3761 override; 3762}; 3763} 3764 3765bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 3766 const analyze_printf::PrintfSpecifier &FS, 3767 const char *startSpecifier, 3768 unsigned specifierLen) { 3769 const analyze_printf::PrintfConversionSpecifier &CS = 3770 FS.getConversionSpecifier(); 3771 3772 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 3773 getLocationOfByte(CS.getStart()), 3774 startSpecifier, specifierLen, 3775 CS.getStart(), CS.getLength()); 3776} 3777 3778bool CheckPrintfHandler::HandleAmount( 3779 const analyze_format_string::OptionalAmount &Amt, 3780 unsigned k, const char *startSpecifier, 3781 unsigned specifierLen) { 3782 3783 if (Amt.hasDataArgument()) { 3784 if (!HasVAListArg) { 3785 unsigned argIndex = Amt.getArgIndex(); 3786 if (argIndex >= NumDataArgs) { 3787 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 3788 << k, 3789 getLocationOfByte(Amt.getStart()), 3790 /*IsStringLocation*/true, 3791 getSpecifierRange(startSpecifier, specifierLen)); 3792 // Don't do any more checking. We will just emit 3793 // spurious errors. 3794 return false; 3795 } 3796 3797 // Type check the data argument. It should be an 'int'. 3798 // Although not in conformance with C99, we also allow the argument to be 3799 // an 'unsigned int' as that is a reasonably safe case. GCC also 3800 // doesn't emit a warning for that case. 3801 CoveredArgs.set(argIndex); 3802 const Expr *Arg = getDataArg(argIndex); 3803 if (!Arg) 3804 return false; 3805 3806 QualType T = Arg->getType(); 3807 3808 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 3809 assert(AT.isValid()); 3810 3811 if (!AT.matchesType(S.Context, T)) { 3812 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 3813 << k << AT.getRepresentativeTypeName(S.Context) 3814 << T << Arg->getSourceRange(), 3815 getLocationOfByte(Amt.getStart()), 3816 /*IsStringLocation*/true, 3817 getSpecifierRange(startSpecifier, specifierLen)); 3818 // Don't do any more checking. We will just emit 3819 // spurious errors. 3820 return false; 3821 } 3822 } 3823 } 3824 return true; 3825} 3826 3827void CheckPrintfHandler::HandleInvalidAmount( 3828 const analyze_printf::PrintfSpecifier &FS, 3829 const analyze_printf::OptionalAmount &Amt, 3830 unsigned type, 3831 const char *startSpecifier, 3832 unsigned specifierLen) { 3833 const analyze_printf::PrintfConversionSpecifier &CS = 3834 FS.getConversionSpecifier(); 3835 3836 FixItHint fixit = 3837 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 3838 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 3839 Amt.getConstantLength())) 3840 : FixItHint(); 3841 3842 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 3843 << type << CS.toString(), 3844 getLocationOfByte(Amt.getStart()), 3845 /*IsStringLocation*/true, 3846 getSpecifierRange(startSpecifier, specifierLen), 3847 fixit); 3848} 3849 3850void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 3851 const analyze_printf::OptionalFlag &flag, 3852 const char *startSpecifier, 3853 unsigned specifierLen) { 3854 // Warn about pointless flag with a fixit removal. 3855 const analyze_printf::PrintfConversionSpecifier &CS = 3856 FS.getConversionSpecifier(); 3857 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 3858 << flag.toString() << CS.toString(), 3859 getLocationOfByte(flag.getPosition()), 3860 /*IsStringLocation*/true, 3861 getSpecifierRange(startSpecifier, specifierLen), 3862 FixItHint::CreateRemoval( 3863 getSpecifierRange(flag.getPosition(), 1))); 3864} 3865 3866void CheckPrintfHandler::HandleIgnoredFlag( 3867 const analyze_printf::PrintfSpecifier &FS, 3868 const analyze_printf::OptionalFlag &ignoredFlag, 3869 const analyze_printf::OptionalFlag &flag, 3870 const char *startSpecifier, 3871 unsigned specifierLen) { 3872 // Warn about ignored flag with a fixit removal. 3873 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 3874 << ignoredFlag.toString() << flag.toString(), 3875 getLocationOfByte(ignoredFlag.getPosition()), 3876 /*IsStringLocation*/true, 3877 getSpecifierRange(startSpecifier, specifierLen), 3878 FixItHint::CreateRemoval( 3879 getSpecifierRange(ignoredFlag.getPosition(), 1))); 3880} 3881 3882// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 3883// bool IsStringLocation, Range StringRange, 3884// ArrayRef<FixItHint> Fixit = None); 3885 3886void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 3887 unsigned flagLen) { 3888 // Warn about an empty flag. 3889 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 3890 getLocationOfByte(startFlag), 3891 /*IsStringLocation*/true, 3892 getSpecifierRange(startFlag, flagLen)); 3893} 3894 3895void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 3896 unsigned flagLen) { 3897 // Warn about an invalid flag. 3898 auto Range = getSpecifierRange(startFlag, flagLen); 3899 StringRef flag(startFlag, flagLen); 3900 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 3901 getLocationOfByte(startFlag), 3902 /*IsStringLocation*/true, 3903 Range, FixItHint::CreateRemoval(Range)); 3904} 3905 3906void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 3907 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 3908 // Warn about using '[...]' without a '@' conversion. 3909 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 3910 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 3911 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 3912 getLocationOfByte(conversionPosition), 3913 /*IsStringLocation*/true, 3914 Range, FixItHint::CreateRemoval(Range)); 3915} 3916 3917// Determines if the specified is a C++ class or struct containing 3918// a member with the specified name and kind (e.g. a CXXMethodDecl named 3919// "c_str()"). 3920template<typename MemberKind> 3921static llvm::SmallPtrSet<MemberKind*, 1> 3922CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 3923 const RecordType *RT = Ty->getAs<RecordType>(); 3924 llvm::SmallPtrSet<MemberKind*, 1> Results; 3925 3926 if (!RT) 3927 return Results; 3928 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 3929 if (!RD || !RD->getDefinition()) 3930 return Results; 3931 3932 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 3933 Sema::LookupMemberName); 3934 R.suppressDiagnostics(); 3935 3936 // We just need to include all members of the right kind turned up by the 3937 // filter, at this point. 3938 if (S.LookupQualifiedName(R, RT->getDecl())) 3939 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 3940 NamedDecl *decl = (*I)->getUnderlyingDecl(); 3941 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 3942 Results.insert(FK); 3943 } 3944 return Results; 3945} 3946 3947/// Check if we could call '.c_str()' on an object. 3948/// 3949/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 3950/// allow the call, or if it would be ambiguous). 3951bool Sema::hasCStrMethod(const Expr *E) { 3952 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 3953 MethodSet Results = 3954 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 3955 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 3956 MI != ME; ++MI) 3957 if ((*MI)->getMinRequiredArguments() == 0) 3958 return true; 3959 return false; 3960} 3961 3962// Check if a (w)string was passed when a (w)char* was needed, and offer a 3963// better diagnostic if so. AT is assumed to be valid. 3964// Returns true when a c_str() conversion method is found. 3965bool CheckPrintfHandler::checkForCStrMembers( 3966 const analyze_printf::ArgType &AT, const Expr *E) { 3967 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 3968 3969 MethodSet Results = 3970 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 3971 3972 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 3973 MI != ME; ++MI) { 3974 const CXXMethodDecl *Method = *MI; 3975 if (Method->getMinRequiredArguments() == 0 && 3976 AT.matchesType(S.Context, Method->getReturnType())) { 3977 // FIXME: Suggest parens if the expression needs them. 3978 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 3979 S.Diag(E->getLocStart(), diag::note_printf_c_str) 3980 << "c_str()" 3981 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 3982 return true; 3983 } 3984 } 3985 3986 return false; 3987} 3988 3989bool 3990CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 3991 &FS, 3992 const char *startSpecifier, 3993 unsigned specifierLen) { 3994 3995 using namespace analyze_format_string; 3996 using namespace analyze_printf; 3997 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 3998 3999 if (FS.consumesDataArgument()) { 4000 if (atFirstArg) { 4001 atFirstArg = false; 4002 usesPositionalArgs = FS.usesPositionalArg(); 4003 } 4004 else if (usesPositionalArgs != FS.usesPositionalArg()) { 4005 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 4006 startSpecifier, specifierLen); 4007 return false; 4008 } 4009 } 4010 4011 // First check if the field width, precision, and conversion specifier 4012 // have matching data arguments. 4013 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 4014 startSpecifier, specifierLen)) { 4015 return false; 4016 } 4017 4018 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 4019 startSpecifier, specifierLen)) { 4020 return false; 4021 } 4022 4023 if (!CS.consumesDataArgument()) { 4024 // FIXME: Technically specifying a precision or field width here 4025 // makes no sense. Worth issuing a warning at some point. 4026 return true; 4027 } 4028 4029 // Consume the argument. 4030 unsigned argIndex = FS.getArgIndex(); 4031 if (argIndex < NumDataArgs) { 4032 // The check to see if the argIndex is valid will come later. 4033 // We set the bit here because we may exit early from this 4034 // function if we encounter some other error. 4035 CoveredArgs.set(argIndex); 4036 } 4037 4038 // FreeBSD kernel extensions. 4039 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 4040 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 4041 // We need at least two arguments. 4042 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 4043 return false; 4044 4045 // Claim the second argument. 4046 CoveredArgs.set(argIndex + 1); 4047 4048 // Type check the first argument (int for %b, pointer for %D) 4049 const Expr *Ex = getDataArg(argIndex); 4050 const analyze_printf::ArgType &AT = 4051 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 4052 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 4053 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 4054 EmitFormatDiagnostic( 4055 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 4056 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 4057 << false << Ex->getSourceRange(), 4058 Ex->getLocStart(), /*IsStringLocation*/false, 4059 getSpecifierRange(startSpecifier, specifierLen)); 4060 4061 // Type check the second argument (char * for both %b and %D) 4062 Ex = getDataArg(argIndex + 1); 4063 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 4064 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 4065 EmitFormatDiagnostic( 4066 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 4067 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 4068 << false << Ex->getSourceRange(), 4069 Ex->getLocStart(), /*IsStringLocation*/false, 4070 getSpecifierRange(startSpecifier, specifierLen)); 4071 4072 return true; 4073 } 4074 4075 // Check for using an Objective-C specific conversion specifier 4076 // in a non-ObjC literal. 4077 if (!ObjCContext && CS.isObjCArg()) { 4078 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 4079 specifierLen); 4080 } 4081 4082 // Check for invalid use of field width 4083 if (!FS.hasValidFieldWidth()) { 4084 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 4085 startSpecifier, specifierLen); 4086 } 4087 4088 // Check for invalid use of precision 4089 if (!FS.hasValidPrecision()) { 4090 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 4091 startSpecifier, specifierLen); 4092 } 4093 4094 // Check each flag does not conflict with any other component. 4095 if (!FS.hasValidThousandsGroupingPrefix()) 4096 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 4097 if (!FS.hasValidLeadingZeros()) 4098 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 4099 if (!FS.hasValidPlusPrefix()) 4100 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 4101 if (!FS.hasValidSpacePrefix()) 4102 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 4103 if (!FS.hasValidAlternativeForm()) 4104 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 4105 if (!FS.hasValidLeftJustified()) 4106 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 4107 4108 // Check that flags are not ignored by another flag 4109 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 4110 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 4111 startSpecifier, specifierLen); 4112 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 4113 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 4114 startSpecifier, specifierLen); 4115 4116 // Check the length modifier is valid with the given conversion specifier. 4117 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 4118 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 4119 diag::warn_format_nonsensical_length); 4120 else if (!FS.hasStandardLengthModifier()) 4121 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 4122 else if (!FS.hasStandardLengthConversionCombination()) 4123 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 4124 diag::warn_format_non_standard_conversion_spec); 4125 4126 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 4127 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 4128 4129 // The remaining checks depend on the data arguments. 4130 if (HasVAListArg) 4131 return true; 4132 4133 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 4134 return false; 4135 4136 const Expr *Arg = getDataArg(argIndex); 4137 if (!Arg) 4138 return true; 4139 4140 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 4141} 4142 4143static bool requiresParensToAddCast(const Expr *E) { 4144 // FIXME: We should have a general way to reason about operator 4145 // precedence and whether parens are actually needed here. 4146 // Take care of a few common cases where they aren't. 4147 const Expr *Inside = E->IgnoreImpCasts(); 4148 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 4149 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 4150 4151 switch (Inside->getStmtClass()) { 4152 case Stmt::ArraySubscriptExprClass: 4153 case Stmt::CallExprClass: 4154 case Stmt::CharacterLiteralClass: 4155 case Stmt::CXXBoolLiteralExprClass: 4156 case Stmt::DeclRefExprClass: 4157 case Stmt::FloatingLiteralClass: 4158 case Stmt::IntegerLiteralClass: 4159 case Stmt::MemberExprClass: 4160 case Stmt::ObjCArrayLiteralClass: 4161 case Stmt::ObjCBoolLiteralExprClass: 4162 case Stmt::ObjCBoxedExprClass: 4163 case Stmt::ObjCDictionaryLiteralClass: 4164 case Stmt::ObjCEncodeExprClass: 4165 case Stmt::ObjCIvarRefExprClass: 4166 case Stmt::ObjCMessageExprClass: 4167 case Stmt::ObjCPropertyRefExprClass: 4168 case Stmt::ObjCStringLiteralClass: 4169 case Stmt::ObjCSubscriptRefExprClass: 4170 case Stmt::ParenExprClass: 4171 case Stmt::StringLiteralClass: 4172 case Stmt::UnaryOperatorClass: 4173 return false; 4174 default: 4175 return true; 4176 } 4177} 4178 4179static std::pair<QualType, StringRef> 4180shouldNotPrintDirectly(const ASTContext &Context, 4181 QualType IntendedTy, 4182 const Expr *E) { 4183 // Use a 'while' to peel off layers of typedefs. 4184 QualType TyTy = IntendedTy; 4185 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 4186 StringRef Name = UserTy->getDecl()->getName(); 4187 QualType CastTy = llvm::StringSwitch<QualType>(Name) 4188 .Case("NSInteger", Context.LongTy) 4189 .Case("NSUInteger", Context.UnsignedLongTy) 4190 .Case("SInt32", Context.IntTy) 4191 .Case("UInt32", Context.UnsignedIntTy) 4192 .Default(QualType()); 4193 4194 if (!CastTy.isNull()) 4195 return std::make_pair(CastTy, Name); 4196 4197 TyTy = UserTy->desugar(); 4198 } 4199 4200 // Strip parens if necessary. 4201 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 4202 return shouldNotPrintDirectly(Context, 4203 PE->getSubExpr()->getType(), 4204 PE->getSubExpr()); 4205 4206 // If this is a conditional expression, then its result type is constructed 4207 // via usual arithmetic conversions and thus there might be no necessary 4208 // typedef sugar there. Recurse to operands to check for NSInteger & 4209 // Co. usage condition. 4210 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 4211 QualType TrueTy, FalseTy; 4212 StringRef TrueName, FalseName; 4213 4214 std::tie(TrueTy, TrueName) = 4215 shouldNotPrintDirectly(Context, 4216 CO->getTrueExpr()->getType(), 4217 CO->getTrueExpr()); 4218 std::tie(FalseTy, FalseName) = 4219 shouldNotPrintDirectly(Context, 4220 CO->getFalseExpr()->getType(), 4221 CO->getFalseExpr()); 4222 4223 if (TrueTy == FalseTy) 4224 return std::make_pair(TrueTy, TrueName); 4225 else if (TrueTy.isNull()) 4226 return std::make_pair(FalseTy, FalseName); 4227 else if (FalseTy.isNull()) 4228 return std::make_pair(TrueTy, TrueName); 4229 } 4230 4231 return std::make_pair(QualType(), StringRef()); 4232} 4233 4234bool 4235CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 4236 const char *StartSpecifier, 4237 unsigned SpecifierLen, 4238 const Expr *E) { 4239 using namespace analyze_format_string; 4240 using namespace analyze_printf; 4241 // Now type check the data expression that matches the 4242 // format specifier. 4243 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, 4244 ObjCContext); 4245 if (!AT.isValid()) 4246 return true; 4247 4248 QualType ExprTy = E->getType(); 4249 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 4250 ExprTy = TET->getUnderlyingExpr()->getType(); 4251 } 4252 4253 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 4254 4255 if (match == analyze_printf::ArgType::Match) { 4256 return true; 4257 } 4258 4259 // Look through argument promotions for our error message's reported type. 4260 // This includes the integral and floating promotions, but excludes array 4261 // and function pointer decay; seeing that an argument intended to be a 4262 // string has type 'char [6]' is probably more confusing than 'char *'. 4263 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 4264 if (ICE->getCastKind() == CK_IntegralCast || 4265 ICE->getCastKind() == CK_FloatingCast) { 4266 E = ICE->getSubExpr(); 4267 ExprTy = E->getType(); 4268 4269 // Check if we didn't match because of an implicit cast from a 'char' 4270 // or 'short' to an 'int'. This is done because printf is a varargs 4271 // function. 4272 if (ICE->getType() == S.Context.IntTy || 4273 ICE->getType() == S.Context.UnsignedIntTy) { 4274 // All further checking is done on the subexpression. 4275 if (AT.matchesType(S.Context, ExprTy)) 4276 return true; 4277 } 4278 } 4279 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 4280 // Special case for 'a', which has type 'int' in C. 4281 // Note, however, that we do /not/ want to treat multibyte constants like 4282 // 'MooV' as characters! This form is deprecated but still exists. 4283 if (ExprTy == S.Context.IntTy) 4284 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 4285 ExprTy = S.Context.CharTy; 4286 } 4287 4288 // Look through enums to their underlying type. 4289 bool IsEnum = false; 4290 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 4291 ExprTy = EnumTy->getDecl()->getIntegerType(); 4292 IsEnum = true; 4293 } 4294 4295 // %C in an Objective-C context prints a unichar, not a wchar_t. 4296 // If the argument is an integer of some kind, believe the %C and suggest 4297 // a cast instead of changing the conversion specifier. 4298 QualType IntendedTy = ExprTy; 4299 if (ObjCContext && 4300 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 4301 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 4302 !ExprTy->isCharType()) { 4303 // 'unichar' is defined as a typedef of unsigned short, but we should 4304 // prefer using the typedef if it is visible. 4305 IntendedTy = S.Context.UnsignedShortTy; 4306 4307 // While we are here, check if the value is an IntegerLiteral that happens 4308 // to be within the valid range. 4309 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 4310 const llvm::APInt &V = IL->getValue(); 4311 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 4312 return true; 4313 } 4314 4315 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 4316 Sema::LookupOrdinaryName); 4317 if (S.LookupName(Result, S.getCurScope())) { 4318 NamedDecl *ND = Result.getFoundDecl(); 4319 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 4320 if (TD->getUnderlyingType() == IntendedTy) 4321 IntendedTy = S.Context.getTypedefType(TD); 4322 } 4323 } 4324 } 4325 4326 // Special-case some of Darwin's platform-independence types by suggesting 4327 // casts to primitive types that are known to be large enough. 4328 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 4329 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 4330 QualType CastTy; 4331 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 4332 if (!CastTy.isNull()) { 4333 IntendedTy = CastTy; 4334 ShouldNotPrintDirectly = true; 4335 } 4336 } 4337 4338 // We may be able to offer a FixItHint if it is a supported type. 4339 PrintfSpecifier fixedFS = FS; 4340 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(), 4341 S.Context, ObjCContext); 4342 4343 if (success) { 4344 // Get the fix string from the fixed format specifier 4345 SmallString<16> buf; 4346 llvm::raw_svector_ostream os(buf); 4347 fixedFS.toString(os); 4348 4349 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 4350 4351 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 4352 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 4353 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 4354 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 4355 } 4356 // In this case, the specifier is wrong and should be changed to match 4357 // the argument. 4358 EmitFormatDiagnostic(S.PDiag(diag) 4359 << AT.getRepresentativeTypeName(S.Context) 4360 << IntendedTy << IsEnum << E->getSourceRange(), 4361 E->getLocStart(), 4362 /*IsStringLocation*/ false, SpecRange, 4363 FixItHint::CreateReplacement(SpecRange, os.str())); 4364 4365 } else { 4366 // The canonical type for formatting this value is different from the 4367 // actual type of the expression. (This occurs, for example, with Darwin's 4368 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 4369 // should be printed as 'long' for 64-bit compatibility.) 4370 // Rather than emitting a normal format/argument mismatch, we want to 4371 // add a cast to the recommended type (and correct the format string 4372 // if necessary). 4373 SmallString<16> CastBuf; 4374 llvm::raw_svector_ostream CastFix(CastBuf); 4375 CastFix << "("; 4376 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 4377 CastFix << ")"; 4378 4379 SmallVector<FixItHint,4> Hints; 4380 if (!AT.matchesType(S.Context, IntendedTy)) 4381 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 4382 4383 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 4384 // If there's already a cast present, just replace it. 4385 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 4386 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 4387 4388 } else if (!requiresParensToAddCast(E)) { 4389 // If the expression has high enough precedence, 4390 // just write the C-style cast. 4391 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 4392 CastFix.str())); 4393 } else { 4394 // Otherwise, add parens around the expression as well as the cast. 4395 CastFix << "("; 4396 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 4397 CastFix.str())); 4398 4399 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 4400 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 4401 } 4402 4403 if (ShouldNotPrintDirectly) { 4404 // The expression has a type that should not be printed directly. 4405 // We extract the name from the typedef because we don't want to show 4406 // the underlying type in the diagnostic. 4407 StringRef Name; 4408 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 4409 Name = TypedefTy->getDecl()->getName(); 4410 else 4411 Name = CastTyName; 4412 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 4413 << Name << IntendedTy << IsEnum 4414 << E->getSourceRange(), 4415 E->getLocStart(), /*IsStringLocation=*/false, 4416 SpecRange, Hints); 4417 } else { 4418 // In this case, the expression could be printed using a different 4419 // specifier, but we've decided that the specifier is probably correct 4420 // and we should cast instead. Just use the normal warning message. 4421 EmitFormatDiagnostic( 4422 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 4423 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 4424 << E->getSourceRange(), 4425 E->getLocStart(), /*IsStringLocation*/false, 4426 SpecRange, Hints); 4427 } 4428 } 4429 } else { 4430 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 4431 SpecifierLen); 4432 // Since the warning for passing non-POD types to variadic functions 4433 // was deferred until now, we emit a warning for non-POD 4434 // arguments here. 4435 switch (S.isValidVarArgType(ExprTy)) { 4436 case Sema::VAK_Valid: 4437 case Sema::VAK_ValidInCXX11: { 4438 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 4439 if (match == analyze_printf::ArgType::NoMatchPedantic) { 4440 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 4441 } 4442 4443 EmitFormatDiagnostic( 4444 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 4445 << IsEnum << CSR << E->getSourceRange(), 4446 E->getLocStart(), /*IsStringLocation*/ false, CSR); 4447 break; 4448 } 4449 case Sema::VAK_Undefined: 4450 case Sema::VAK_MSVCUndefined: 4451 EmitFormatDiagnostic( 4452 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 4453 << S.getLangOpts().CPlusPlus11 4454 << ExprTy 4455 << CallType 4456 << AT.getRepresentativeTypeName(S.Context) 4457 << CSR 4458 << E->getSourceRange(), 4459 E->getLocStart(), /*IsStringLocation*/false, CSR); 4460 checkForCStrMembers(AT, E); 4461 break; 4462 4463 case Sema::VAK_Invalid: 4464 if (ExprTy->isObjCObjectType()) 4465 EmitFormatDiagnostic( 4466 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 4467 << S.getLangOpts().CPlusPlus11 4468 << ExprTy 4469 << CallType 4470 << AT.getRepresentativeTypeName(S.Context) 4471 << CSR 4472 << E->getSourceRange(), 4473 E->getLocStart(), /*IsStringLocation*/false, CSR); 4474 else 4475 // FIXME: If this is an initializer list, suggest removing the braces 4476 // or inserting a cast to the target type. 4477 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 4478 << isa<InitListExpr>(E) << ExprTy << CallType 4479 << AT.getRepresentativeTypeName(S.Context) 4480 << E->getSourceRange(); 4481 break; 4482 } 4483 4484 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 4485 "format string specifier index out of range"); 4486 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 4487 } 4488 4489 return true; 4490} 4491 4492//===--- CHECK: Scanf format string checking ------------------------------===// 4493 4494namespace { 4495class CheckScanfHandler : public CheckFormatHandler { 4496public: 4497 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 4498 const Expr *origFormatExpr, unsigned firstDataArg, 4499 unsigned numDataArgs, const char *beg, bool hasVAListArg, 4500 ArrayRef<const Expr *> Args, 4501 unsigned formatIdx, bool inFunctionCall, 4502 Sema::VariadicCallType CallType, 4503 llvm::SmallBitVector &CheckedVarArgs) 4504 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 4505 numDataArgs, beg, hasVAListArg, 4506 Args, formatIdx, inFunctionCall, CallType, 4507 CheckedVarArgs) 4508 {} 4509 4510 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 4511 const char *startSpecifier, 4512 unsigned specifierLen) override; 4513 4514 bool HandleInvalidScanfConversionSpecifier( 4515 const analyze_scanf::ScanfSpecifier &FS, 4516 const char *startSpecifier, 4517 unsigned specifierLen) override; 4518 4519 void HandleIncompleteScanList(const char *start, const char *end) override; 4520}; 4521} 4522 4523void CheckScanfHandler::HandleIncompleteScanList(const char *start, 4524 const char *end) { 4525 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 4526 getLocationOfByte(end), /*IsStringLocation*/true, 4527 getSpecifierRange(start, end - start)); 4528} 4529 4530bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 4531 const analyze_scanf::ScanfSpecifier &FS, 4532 const char *startSpecifier, 4533 unsigned specifierLen) { 4534 4535 const analyze_scanf::ScanfConversionSpecifier &CS = 4536 FS.getConversionSpecifier(); 4537 4538 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 4539 getLocationOfByte(CS.getStart()), 4540 startSpecifier, specifierLen, 4541 CS.getStart(), CS.getLength()); 4542} 4543 4544bool CheckScanfHandler::HandleScanfSpecifier( 4545 const analyze_scanf::ScanfSpecifier &FS, 4546 const char *startSpecifier, 4547 unsigned specifierLen) { 4548 4549 using namespace analyze_scanf; 4550 using namespace analyze_format_string; 4551 4552 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 4553 4554 // Handle case where '%' and '*' don't consume an argument. These shouldn't 4555 // be used to decide if we are using positional arguments consistently. 4556 if (FS.consumesDataArgument()) { 4557 if (atFirstArg) { 4558 atFirstArg = false; 4559 usesPositionalArgs = FS.usesPositionalArg(); 4560 } 4561 else if (usesPositionalArgs != FS.usesPositionalArg()) { 4562 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 4563 startSpecifier, specifierLen); 4564 return false; 4565 } 4566 } 4567 4568 // Check if the field with is non-zero. 4569 const OptionalAmount &Amt = FS.getFieldWidth(); 4570 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 4571 if (Amt.getConstantAmount() == 0) { 4572 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 4573 Amt.getConstantLength()); 4574 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 4575 getLocationOfByte(Amt.getStart()), 4576 /*IsStringLocation*/true, R, 4577 FixItHint::CreateRemoval(R)); 4578 } 4579 } 4580 4581 if (!FS.consumesDataArgument()) { 4582 // FIXME: Technically specifying a precision or field width here 4583 // makes no sense. Worth issuing a warning at some point. 4584 return true; 4585 } 4586 4587 // Consume the argument. 4588 unsigned argIndex = FS.getArgIndex(); 4589 if (argIndex < NumDataArgs) { 4590 // The check to see if the argIndex is valid will come later. 4591 // We set the bit here because we may exit early from this 4592 // function if we encounter some other error. 4593 CoveredArgs.set(argIndex); 4594 } 4595 4596 // Check the length modifier is valid with the given conversion specifier. 4597 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 4598 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 4599 diag::warn_format_nonsensical_length); 4600 else if (!FS.hasStandardLengthModifier()) 4601 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 4602 else if (!FS.hasStandardLengthConversionCombination()) 4603 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 4604 diag::warn_format_non_standard_conversion_spec); 4605 4606 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 4607 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 4608 4609 // The remaining checks depend on the data arguments. 4610 if (HasVAListArg) 4611 return true; 4612 4613 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 4614 return false; 4615 4616 // Check that the argument type matches the format specifier. 4617 const Expr *Ex = getDataArg(argIndex); 4618 if (!Ex) 4619 return true; 4620 4621 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 4622 4623 if (!AT.isValid()) { 4624 return true; 4625 } 4626 4627 analyze_format_string::ArgType::MatchKind match = 4628 AT.matchesType(S.Context, Ex->getType()); 4629 if (match == analyze_format_string::ArgType::Match) { 4630 return true; 4631 } 4632 4633 ScanfSpecifier fixedFS = FS; 4634 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 4635 S.getLangOpts(), S.Context); 4636 4637 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 4638 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 4639 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 4640 } 4641 4642 if (success) { 4643 // Get the fix string from the fixed format specifier. 4644 SmallString<128> buf; 4645 llvm::raw_svector_ostream os(buf); 4646 fixedFS.toString(os); 4647 4648 EmitFormatDiagnostic( 4649 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 4650 << Ex->getType() << false << Ex->getSourceRange(), 4651 Ex->getLocStart(), 4652 /*IsStringLocation*/ false, 4653 getSpecifierRange(startSpecifier, specifierLen), 4654 FixItHint::CreateReplacement( 4655 getSpecifierRange(startSpecifier, specifierLen), os.str())); 4656 } else { 4657 EmitFormatDiagnostic(S.PDiag(diag) 4658 << AT.getRepresentativeTypeName(S.Context) 4659 << Ex->getType() << false << Ex->getSourceRange(), 4660 Ex->getLocStart(), 4661 /*IsStringLocation*/ false, 4662 getSpecifierRange(startSpecifier, specifierLen)); 4663 } 4664 4665 return true; 4666} 4667 4668void Sema::CheckFormatString(const StringLiteral *FExpr, 4669 const Expr *OrigFormatExpr, 4670 ArrayRef<const Expr *> Args, 4671 bool HasVAListArg, unsigned format_idx, 4672 unsigned firstDataArg, FormatStringType Type, 4673 bool inFunctionCall, VariadicCallType CallType, 4674 llvm::SmallBitVector &CheckedVarArgs) { 4675 4676 // CHECK: is the format string a wide literal? 4677 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 4678 CheckFormatHandler::EmitFormatDiagnostic( 4679 *this, inFunctionCall, Args[format_idx], 4680 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 4681 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 4682 return; 4683 } 4684 4685 // Str - The format string. NOTE: this is NOT null-terminated! 4686 StringRef StrRef = FExpr->getString(); 4687 const char *Str = StrRef.data(); 4688 // Account for cases where the string literal is truncated in a declaration. 4689 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 4690 assert(T && "String literal not of constant array type!"); 4691 size_t TypeSize = T->getSize().getZExtValue(); 4692 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 4693 const unsigned numDataArgs = Args.size() - firstDataArg; 4694 4695 // Emit a warning if the string literal is truncated and does not contain an 4696 // embedded null character. 4697 if (TypeSize <= StrRef.size() && 4698 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 4699 CheckFormatHandler::EmitFormatDiagnostic( 4700 *this, inFunctionCall, Args[format_idx], 4701 PDiag(diag::warn_printf_format_string_not_null_terminated), 4702 FExpr->getLocStart(), 4703 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 4704 return; 4705 } 4706 4707 // CHECK: empty format string? 4708 if (StrLen == 0 && numDataArgs > 0) { 4709 CheckFormatHandler::EmitFormatDiagnostic( 4710 *this, inFunctionCall, Args[format_idx], 4711 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 4712 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 4713 return; 4714 } 4715 4716 if (Type == FST_Printf || Type == FST_NSString || 4717 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) { 4718 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 4719 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace), 4720 Str, HasVAListArg, Args, format_idx, 4721 inFunctionCall, CallType, CheckedVarArgs); 4722 4723 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 4724 getLangOpts(), 4725 Context.getTargetInfo(), 4726 Type == FST_FreeBSDKPrintf)) 4727 H.DoneProcessing(); 4728 } else if (Type == FST_Scanf) { 4729 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs, 4730 Str, HasVAListArg, Args, format_idx, 4731 inFunctionCall, CallType, CheckedVarArgs); 4732 4733 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 4734 getLangOpts(), 4735 Context.getTargetInfo())) 4736 H.DoneProcessing(); 4737 } // TODO: handle other formats 4738} 4739 4740bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 4741 // Str - The format string. NOTE: this is NOT null-terminated! 4742 StringRef StrRef = FExpr->getString(); 4743 const char *Str = StrRef.data(); 4744 // Account for cases where the string literal is truncated in a declaration. 4745 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 4746 assert(T && "String literal not of constant array type!"); 4747 size_t TypeSize = T->getSize().getZExtValue(); 4748 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 4749 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 4750 getLangOpts(), 4751 Context.getTargetInfo()); 4752} 4753 4754//===--- CHECK: Warn on use of wrong absolute value function. -------------===// 4755 4756// Returns the related absolute value function that is larger, of 0 if one 4757// does not exist. 4758static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 4759 switch (AbsFunction) { 4760 default: 4761 return 0; 4762 4763 case Builtin::BI__builtin_abs: 4764 return Builtin::BI__builtin_labs; 4765 case Builtin::BI__builtin_labs: 4766 return Builtin::BI__builtin_llabs; 4767 case Builtin::BI__builtin_llabs: 4768 return 0; 4769 4770 case Builtin::BI__builtin_fabsf: 4771 return Builtin::BI__builtin_fabs; 4772 case Builtin::BI__builtin_fabs: 4773 return Builtin::BI__builtin_fabsl; 4774 case Builtin::BI__builtin_fabsl: 4775 return 0; 4776 4777 case Builtin::BI__builtin_cabsf: 4778 return Builtin::BI__builtin_cabs; 4779 case Builtin::BI__builtin_cabs: 4780 return Builtin::BI__builtin_cabsl; 4781 case Builtin::BI__builtin_cabsl: 4782 return 0; 4783 4784 case Builtin::BIabs: 4785 return Builtin::BIlabs; 4786 case Builtin::BIlabs: 4787 return Builtin::BIllabs; 4788 case Builtin::BIllabs: 4789 return 0; 4790 4791 case Builtin::BIfabsf: 4792 return Builtin::BIfabs; 4793 case Builtin::BIfabs: 4794 return Builtin::BIfabsl; 4795 case Builtin::BIfabsl: 4796 return 0; 4797 4798 case Builtin::BIcabsf: 4799 return Builtin::BIcabs; 4800 case Builtin::BIcabs: 4801 return Builtin::BIcabsl; 4802 case Builtin::BIcabsl: 4803 return 0; 4804 } 4805} 4806 4807// Returns the argument type of the absolute value function. 4808static QualType getAbsoluteValueArgumentType(ASTContext &Context, 4809 unsigned AbsType) { 4810 if (AbsType == 0) 4811 return QualType(); 4812 4813 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 4814 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 4815 if (Error != ASTContext::GE_None) 4816 return QualType(); 4817 4818 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 4819 if (!FT) 4820 return QualType(); 4821 4822 if (FT->getNumParams() != 1) 4823 return QualType(); 4824 4825 return FT->getParamType(0); 4826} 4827 4828// Returns the best absolute value function, or zero, based on type and 4829// current absolute value function. 4830static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 4831 unsigned AbsFunctionKind) { 4832 unsigned BestKind = 0; 4833 uint64_t ArgSize = Context.getTypeSize(ArgType); 4834 for (unsigned Kind = AbsFunctionKind; Kind != 0; 4835 Kind = getLargerAbsoluteValueFunction(Kind)) { 4836 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 4837 if (Context.getTypeSize(ParamType) >= ArgSize) { 4838 if (BestKind == 0) 4839 BestKind = Kind; 4840 else if (Context.hasSameType(ParamType, ArgType)) { 4841 BestKind = Kind; 4842 break; 4843 } 4844 } 4845 } 4846 return BestKind; 4847} 4848 4849enum AbsoluteValueKind { 4850 AVK_Integer, 4851 AVK_Floating, 4852 AVK_Complex 4853}; 4854 4855static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 4856 if (T->isIntegralOrEnumerationType()) 4857 return AVK_Integer; 4858 if (T->isRealFloatingType()) 4859 return AVK_Floating; 4860 if (T->isAnyComplexType()) 4861 return AVK_Complex; 4862 4863 llvm_unreachable("Type not integer, floating, or complex"); 4864} 4865 4866// Changes the absolute value function to a different type. Preserves whether 4867// the function is a builtin. 4868static unsigned changeAbsFunction(unsigned AbsKind, 4869 AbsoluteValueKind ValueKind) { 4870 switch (ValueKind) { 4871 case AVK_Integer: 4872 switch (AbsKind) { 4873 default: 4874 return 0; 4875 case Builtin::BI__builtin_fabsf: 4876 case Builtin::BI__builtin_fabs: 4877 case Builtin::BI__builtin_fabsl: 4878 case Builtin::BI__builtin_cabsf: 4879 case Builtin::BI__builtin_cabs: 4880 case Builtin::BI__builtin_cabsl: 4881 return Builtin::BI__builtin_abs; 4882 case Builtin::BIfabsf: 4883 case Builtin::BIfabs: 4884 case Builtin::BIfabsl: 4885 case Builtin::BIcabsf: 4886 case Builtin::BIcabs: 4887 case Builtin::BIcabsl: 4888 return Builtin::BIabs; 4889 } 4890 case AVK_Floating: 4891 switch (AbsKind) { 4892 default: 4893 return 0; 4894 case Builtin::BI__builtin_abs: 4895 case Builtin::BI__builtin_labs: 4896 case Builtin::BI__builtin_llabs: 4897 case Builtin::BI__builtin_cabsf: 4898 case Builtin::BI__builtin_cabs: 4899 case Builtin::BI__builtin_cabsl: 4900 return Builtin::BI__builtin_fabsf; 4901 case Builtin::BIabs: 4902 case Builtin::BIlabs: 4903 case Builtin::BIllabs: 4904 case Builtin::BIcabsf: 4905 case Builtin::BIcabs: 4906 case Builtin::BIcabsl: 4907 return Builtin::BIfabsf; 4908 } 4909 case AVK_Complex: 4910 switch (AbsKind) { 4911 default: 4912 return 0; 4913 case Builtin::BI__builtin_abs: 4914 case Builtin::BI__builtin_labs: 4915 case Builtin::BI__builtin_llabs: 4916 case Builtin::BI__builtin_fabsf: 4917 case Builtin::BI__builtin_fabs: 4918 case Builtin::BI__builtin_fabsl: 4919 return Builtin::BI__builtin_cabsf; 4920 case Builtin::BIabs: 4921 case Builtin::BIlabs: 4922 case Builtin::BIllabs: 4923 case Builtin::BIfabsf: 4924 case Builtin::BIfabs: 4925 case Builtin::BIfabsl: 4926 return Builtin::BIcabsf; 4927 } 4928 } 4929 llvm_unreachable("Unable to convert function"); 4930} 4931 4932static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 4933 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4934 if (!FnInfo) 4935 return 0; 4936 4937 switch (FDecl->getBuiltinID()) { 4938 default: 4939 return 0; 4940 case Builtin::BI__builtin_abs: 4941 case Builtin::BI__builtin_fabs: 4942 case Builtin::BI__builtin_fabsf: 4943 case Builtin::BI__builtin_fabsl: 4944 case Builtin::BI__builtin_labs: 4945 case Builtin::BI__builtin_llabs: 4946 case Builtin::BI__builtin_cabs: 4947 case Builtin::BI__builtin_cabsf: 4948 case Builtin::BI__builtin_cabsl: 4949 case Builtin::BIabs: 4950 case Builtin::BIlabs: 4951 case Builtin::BIllabs: 4952 case Builtin::BIfabs: 4953 case Builtin::BIfabsf: 4954 case Builtin::BIfabsl: 4955 case Builtin::BIcabs: 4956 case Builtin::BIcabsf: 4957 case Builtin::BIcabsl: 4958 return FDecl->getBuiltinID(); 4959 } 4960 llvm_unreachable("Unknown Builtin type"); 4961} 4962 4963// If the replacement is valid, emit a note with replacement function. 4964// Additionally, suggest including the proper header if not already included. 4965static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 4966 unsigned AbsKind, QualType ArgType) { 4967 bool EmitHeaderHint = true; 4968 const char *HeaderName = nullptr; 4969 const char *FunctionName = nullptr; 4970 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 4971 FunctionName = "std::abs"; 4972 if (ArgType->isIntegralOrEnumerationType()) { 4973 HeaderName = "cstdlib"; 4974 } else if (ArgType->isRealFloatingType()) { 4975 HeaderName = "cmath"; 4976 } else { 4977 llvm_unreachable("Invalid Type"); 4978 } 4979 4980 // Lookup all std::abs 4981 if (NamespaceDecl *Std = S.getStdNamespace()) { 4982 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 4983 R.suppressDiagnostics(); 4984 S.LookupQualifiedName(R, Std); 4985 4986 for (const auto *I : R) { 4987 const FunctionDecl *FDecl = nullptr; 4988 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 4989 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 4990 } else { 4991 FDecl = dyn_cast<FunctionDecl>(I); 4992 } 4993 if (!FDecl) 4994 continue; 4995 4996 // Found std::abs(), check that they are the right ones. 4997 if (FDecl->getNumParams() != 1) 4998 continue; 4999 5000 // Check that the parameter type can handle the argument. 5001 QualType ParamType = FDecl->getParamDecl(0)->getType(); 5002 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 5003 S.Context.getTypeSize(ArgType) <= 5004 S.Context.getTypeSize(ParamType)) { 5005 // Found a function, don't need the header hint. 5006 EmitHeaderHint = false; 5007 break; 5008 } 5009 } 5010 } 5011 } else { 5012 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 5013 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 5014 5015 if (HeaderName) { 5016 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 5017 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 5018 R.suppressDiagnostics(); 5019 S.LookupName(R, S.getCurScope()); 5020 5021 if (R.isSingleResult()) { 5022 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 5023 if (FD && FD->getBuiltinID() == AbsKind) { 5024 EmitHeaderHint = false; 5025 } else { 5026 return; 5027 } 5028 } else if (!R.empty()) { 5029 return; 5030 } 5031 } 5032 } 5033 5034 S.Diag(Loc, diag::note_replace_abs_function) 5035 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 5036 5037 if (!HeaderName) 5038 return; 5039 5040 if (!EmitHeaderHint) 5041 return; 5042 5043 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 5044 << FunctionName; 5045} 5046 5047static bool IsFunctionStdAbs(const FunctionDecl *FDecl) { 5048 if (!FDecl) 5049 return false; 5050 5051 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs")) 5052 return false; 5053 5054 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext()); 5055 5056 while (ND && ND->isInlineNamespace()) { 5057 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext()); 5058 } 5059 5060 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std")) 5061 return false; 5062 5063 if (!isa<TranslationUnitDecl>(ND->getDeclContext())) 5064 return false; 5065 5066 return true; 5067} 5068 5069// Warn when using the wrong abs() function. 5070void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 5071 const FunctionDecl *FDecl, 5072 IdentifierInfo *FnInfo) { 5073 if (Call->getNumArgs() != 1) 5074 return; 5075 5076 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 5077 bool IsStdAbs = IsFunctionStdAbs(FDecl); 5078 if (AbsKind == 0 && !IsStdAbs) 5079 return; 5080 5081 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 5082 QualType ParamType = Call->getArg(0)->getType(); 5083 5084 // Unsigned types cannot be negative. Suggest removing the absolute value 5085 // function call. 5086 if (ArgType->isUnsignedIntegerType()) { 5087 const char *FunctionName = 5088 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 5089 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 5090 Diag(Call->getExprLoc(), diag::note_remove_abs) 5091 << FunctionName 5092 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 5093 return; 5094 } 5095 5096 // Taking the absolute value of a pointer is very suspicious, they probably 5097 // wanted to index into an array, dereference a pointer, call a function, etc. 5098 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 5099 unsigned DiagType = 0; 5100 if (ArgType->isFunctionType()) 5101 DiagType = 1; 5102 else if (ArgType->isArrayType()) 5103 DiagType = 2; 5104 5105 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 5106 return; 5107 } 5108 5109 // std::abs has overloads which prevent most of the absolute value problems 5110 // from occurring. 5111 if (IsStdAbs) 5112 return; 5113 5114 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 5115 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 5116 5117 // The argument and parameter are the same kind. Check if they are the right 5118 // size. 5119 if (ArgValueKind == ParamValueKind) { 5120 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 5121 return; 5122 5123 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 5124 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 5125 << FDecl << ArgType << ParamType; 5126 5127 if (NewAbsKind == 0) 5128 return; 5129 5130 emitReplacement(*this, Call->getExprLoc(), 5131 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 5132 return; 5133 } 5134 5135 // ArgValueKind != ParamValueKind 5136 // The wrong type of absolute value function was used. Attempt to find the 5137 // proper one. 5138 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 5139 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 5140 if (NewAbsKind == 0) 5141 return; 5142 5143 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 5144 << FDecl << ParamValueKind << ArgValueKind; 5145 5146 emitReplacement(*this, Call->getExprLoc(), 5147 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 5148 return; 5149} 5150 5151//===--- CHECK: Standard memory functions ---------------------------------===// 5152 5153/// \brief Takes the expression passed to the size_t parameter of functions 5154/// such as memcmp, strncat, etc and warns if it's a comparison. 5155/// 5156/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 5157static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 5158 IdentifierInfo *FnName, 5159 SourceLocation FnLoc, 5160 SourceLocation RParenLoc) { 5161 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 5162 if (!Size) 5163 return false; 5164 5165 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 5166 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 5167 return false; 5168 5169 SourceRange SizeRange = Size->getSourceRange(); 5170 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 5171 << SizeRange << FnName; 5172 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 5173 << FnName << FixItHint::CreateInsertion( 5174 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 5175 << FixItHint::CreateRemoval(RParenLoc); 5176 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 5177 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 5178 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 5179 ")"); 5180 5181 return true; 5182} 5183 5184/// \brief Determine whether the given type is or contains a dynamic class type 5185/// (e.g., whether it has a vtable). 5186static const CXXRecordDecl *getContainedDynamicClass(QualType T, 5187 bool &IsContained) { 5188 // Look through array types while ignoring qualifiers. 5189 const Type *Ty = T->getBaseElementTypeUnsafe(); 5190 IsContained = false; 5191 5192 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 5193 RD = RD ? RD->getDefinition() : nullptr; 5194 if (!RD) 5195 return nullptr; 5196 5197 if (RD->isDynamicClass()) 5198 return RD; 5199 5200 // Check all the fields. If any bases were dynamic, the class is dynamic. 5201 // It's impossible for a class to transitively contain itself by value, so 5202 // infinite recursion is impossible. 5203 for (auto *FD : RD->fields()) { 5204 bool SubContained; 5205 if (const CXXRecordDecl *ContainedRD = 5206 getContainedDynamicClass(FD->getType(), SubContained)) { 5207 IsContained = true; 5208 return ContainedRD; 5209 } 5210 } 5211 5212 return nullptr; 5213} 5214 5215/// \brief If E is a sizeof expression, returns its argument expression, 5216/// otherwise returns NULL. 5217static const Expr *getSizeOfExprArg(const Expr *E) { 5218 if (const UnaryExprOrTypeTraitExpr *SizeOf = 5219 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 5220 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 5221 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 5222 5223 return nullptr; 5224} 5225 5226/// \brief If E is a sizeof expression, returns its argument type. 5227static QualType getSizeOfArgType(const Expr *E) { 5228 if (const UnaryExprOrTypeTraitExpr *SizeOf = 5229 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 5230 if (SizeOf->getKind() == clang::UETT_SizeOf) 5231 return SizeOf->getTypeOfArgument(); 5232 5233 return QualType(); 5234} 5235 5236/// \brief Check for dangerous or invalid arguments to memset(). 5237/// 5238/// This issues warnings on known problematic, dangerous or unspecified 5239/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 5240/// function calls. 5241/// 5242/// \param Call The call expression to diagnose. 5243void Sema::CheckMemaccessArguments(const CallExpr *Call, 5244 unsigned BId, 5245 IdentifierInfo *FnName) { 5246 assert(BId != 0); 5247 5248 // It is possible to have a non-standard definition of memset. Validate 5249 // we have enough arguments, and if not, abort further checking. 5250 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3); 5251 if (Call->getNumArgs() < ExpectedNumArgs) 5252 return; 5253 5254 unsigned LastArg = (BId == Builtin::BImemset || 5255 BId == Builtin::BIstrndup ? 1 : 2); 5256 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2); 5257 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 5258 5259 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 5260 Call->getLocStart(), Call->getRParenLoc())) 5261 return; 5262 5263 // We have special checking when the length is a sizeof expression. 5264 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 5265 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 5266 llvm::FoldingSetNodeID SizeOfArgID; 5267 5268 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 5269 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 5270 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 5271 5272 QualType DestTy = Dest->getType(); 5273 QualType PointeeTy; 5274 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 5275 PointeeTy = DestPtrTy->getPointeeType(); 5276 5277 // Never warn about void type pointers. This can be used to suppress 5278 // false positives. 5279 if (PointeeTy->isVoidType()) 5280 continue; 5281 5282 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 5283 // actually comparing the expressions for equality. Because computing the 5284 // expression IDs can be expensive, we only do this if the diagnostic is 5285 // enabled. 5286 if (SizeOfArg && 5287 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 5288 SizeOfArg->getExprLoc())) { 5289 // We only compute IDs for expressions if the warning is enabled, and 5290 // cache the sizeof arg's ID. 5291 if (SizeOfArgID == llvm::FoldingSetNodeID()) 5292 SizeOfArg->Profile(SizeOfArgID, Context, true); 5293 llvm::FoldingSetNodeID DestID; 5294 Dest->Profile(DestID, Context, true); 5295 if (DestID == SizeOfArgID) { 5296 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 5297 // over sizeof(src) as well. 5298 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 5299 StringRef ReadableName = FnName->getName(); 5300 5301 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 5302 if (UnaryOp->getOpcode() == UO_AddrOf) 5303 ActionIdx = 1; // If its an address-of operator, just remove it. 5304 if (!PointeeTy->isIncompleteType() && 5305 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 5306 ActionIdx = 2; // If the pointee's size is sizeof(char), 5307 // suggest an explicit length. 5308 5309 // If the function is defined as a builtin macro, do not show macro 5310 // expansion. 5311 SourceLocation SL = SizeOfArg->getExprLoc(); 5312 SourceRange DSR = Dest->getSourceRange(); 5313 SourceRange SSR = SizeOfArg->getSourceRange(); 5314 SourceManager &SM = getSourceManager(); 5315 5316 if (SM.isMacroArgExpansion(SL)) { 5317 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 5318 SL = SM.getSpellingLoc(SL); 5319 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 5320 SM.getSpellingLoc(DSR.getEnd())); 5321 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 5322 SM.getSpellingLoc(SSR.getEnd())); 5323 } 5324 5325 DiagRuntimeBehavior(SL, SizeOfArg, 5326 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 5327 << ReadableName 5328 << PointeeTy 5329 << DestTy 5330 << DSR 5331 << SSR); 5332 DiagRuntimeBehavior(SL, SizeOfArg, 5333 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 5334 << ActionIdx 5335 << SSR); 5336 5337 break; 5338 } 5339 } 5340 5341 // Also check for cases where the sizeof argument is the exact same 5342 // type as the memory argument, and where it points to a user-defined 5343 // record type. 5344 if (SizeOfArgTy != QualType()) { 5345 if (PointeeTy->isRecordType() && 5346 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 5347 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 5348 PDiag(diag::warn_sizeof_pointer_type_memaccess) 5349 << FnName << SizeOfArgTy << ArgIdx 5350 << PointeeTy << Dest->getSourceRange() 5351 << LenExpr->getSourceRange()); 5352 break; 5353 } 5354 } 5355 } else if (DestTy->isArrayType()) { 5356 PointeeTy = DestTy; 5357 } 5358 5359 if (PointeeTy == QualType()) 5360 continue; 5361 5362 // Always complain about dynamic classes. 5363 bool IsContained; 5364 if (const CXXRecordDecl *ContainedRD = 5365 getContainedDynamicClass(PointeeTy, IsContained)) { 5366 5367 unsigned OperationType = 0; 5368 // "overwritten" if we're warning about the destination for any call 5369 // but memcmp; otherwise a verb appropriate to the call. 5370 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 5371 if (BId == Builtin::BImemcpy) 5372 OperationType = 1; 5373 else if(BId == Builtin::BImemmove) 5374 OperationType = 2; 5375 else if (BId == Builtin::BImemcmp) 5376 OperationType = 3; 5377 } 5378 5379 DiagRuntimeBehavior( 5380 Dest->getExprLoc(), Dest, 5381 PDiag(diag::warn_dyn_class_memaccess) 5382 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 5383 << FnName << IsContained << ContainedRD << OperationType 5384 << Call->getCallee()->getSourceRange()); 5385 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 5386 BId != Builtin::BImemset) 5387 DiagRuntimeBehavior( 5388 Dest->getExprLoc(), Dest, 5389 PDiag(diag::warn_arc_object_memaccess) 5390 << ArgIdx << FnName << PointeeTy 5391 << Call->getCallee()->getSourceRange()); 5392 else 5393 continue; 5394 5395 DiagRuntimeBehavior( 5396 Dest->getExprLoc(), Dest, 5397 PDiag(diag::note_bad_memaccess_silence) 5398 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 5399 break; 5400 } 5401 5402} 5403 5404// A little helper routine: ignore addition and subtraction of integer literals. 5405// This intentionally does not ignore all integer constant expressions because 5406// we don't want to remove sizeof(). 5407static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 5408 Ex = Ex->IgnoreParenCasts(); 5409 5410 for (;;) { 5411 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 5412 if (!BO || !BO->isAdditiveOp()) 5413 break; 5414 5415 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 5416 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 5417 5418 if (isa<IntegerLiteral>(RHS)) 5419 Ex = LHS; 5420 else if (isa<IntegerLiteral>(LHS)) 5421 Ex = RHS; 5422 else 5423 break; 5424 } 5425 5426 return Ex; 5427} 5428 5429static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 5430 ASTContext &Context) { 5431 // Only handle constant-sized or VLAs, but not flexible members. 5432 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 5433 // Only issue the FIXIT for arrays of size > 1. 5434 if (CAT->getSize().getSExtValue() <= 1) 5435 return false; 5436 } else if (!Ty->isVariableArrayType()) { 5437 return false; 5438 } 5439 return true; 5440} 5441 5442// Warn if the user has made the 'size' argument to strlcpy or strlcat 5443// be the size of the source, instead of the destination. 5444void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 5445 IdentifierInfo *FnName) { 5446 5447 // Don't crash if the user has the wrong number of arguments 5448 unsigned NumArgs = Call->getNumArgs(); 5449 if ((NumArgs != 3) && (NumArgs != 4)) 5450 return; 5451 5452 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 5453 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 5454 const Expr *CompareWithSrc = nullptr; 5455 5456 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 5457 Call->getLocStart(), Call->getRParenLoc())) 5458 return; 5459 5460 // Look for 'strlcpy(dst, x, sizeof(x))' 5461 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 5462 CompareWithSrc = Ex; 5463 else { 5464 // Look for 'strlcpy(dst, x, strlen(x))' 5465 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 5466 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 5467 SizeCall->getNumArgs() == 1) 5468 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 5469 } 5470 } 5471 5472 if (!CompareWithSrc) 5473 return; 5474 5475 // Determine if the argument to sizeof/strlen is equal to the source 5476 // argument. In principle there's all kinds of things you could do 5477 // here, for instance creating an == expression and evaluating it with 5478 // EvaluateAsBooleanCondition, but this uses a more direct technique: 5479 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 5480 if (!SrcArgDRE) 5481 return; 5482 5483 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 5484 if (!CompareWithSrcDRE || 5485 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 5486 return; 5487 5488 const Expr *OriginalSizeArg = Call->getArg(2); 5489 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 5490 << OriginalSizeArg->getSourceRange() << FnName; 5491 5492 // Output a FIXIT hint if the destination is an array (rather than a 5493 // pointer to an array). This could be enhanced to handle some 5494 // pointers if we know the actual size, like if DstArg is 'array+2' 5495 // we could say 'sizeof(array)-2'. 5496 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 5497 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 5498 return; 5499 5500 SmallString<128> sizeString; 5501 llvm::raw_svector_ostream OS(sizeString); 5502 OS << "sizeof("; 5503 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 5504 OS << ")"; 5505 5506 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 5507 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 5508 OS.str()); 5509} 5510 5511/// Check if two expressions refer to the same declaration. 5512static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 5513 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 5514 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 5515 return D1->getDecl() == D2->getDecl(); 5516 return false; 5517} 5518 5519static const Expr *getStrlenExprArg(const Expr *E) { 5520 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 5521 const FunctionDecl *FD = CE->getDirectCallee(); 5522 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 5523 return nullptr; 5524 return CE->getArg(0)->IgnoreParenCasts(); 5525 } 5526 return nullptr; 5527} 5528 5529// Warn on anti-patterns as the 'size' argument to strncat. 5530// The correct size argument should look like following: 5531// strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 5532void Sema::CheckStrncatArguments(const CallExpr *CE, 5533 IdentifierInfo *FnName) { 5534 // Don't crash if the user has the wrong number of arguments. 5535 if (CE->getNumArgs() < 3) 5536 return; 5537 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 5538 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 5539 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 5540 5541 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 5542 CE->getRParenLoc())) 5543 return; 5544 5545 // Identify common expressions, which are wrongly used as the size argument 5546 // to strncat and may lead to buffer overflows. 5547 unsigned PatternType = 0; 5548 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 5549 // - sizeof(dst) 5550 if (referToTheSameDecl(SizeOfArg, DstArg)) 5551 PatternType = 1; 5552 // - sizeof(src) 5553 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 5554 PatternType = 2; 5555 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 5556 if (BE->getOpcode() == BO_Sub) { 5557 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 5558 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 5559 // - sizeof(dst) - strlen(dst) 5560 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 5561 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 5562 PatternType = 1; 5563 // - sizeof(src) - (anything) 5564 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 5565 PatternType = 2; 5566 } 5567 } 5568 5569 if (PatternType == 0) 5570 return; 5571 5572 // Generate the diagnostic. 5573 SourceLocation SL = LenArg->getLocStart(); 5574 SourceRange SR = LenArg->getSourceRange(); 5575 SourceManager &SM = getSourceManager(); 5576 5577 // If the function is defined as a builtin macro, do not show macro expansion. 5578 if (SM.isMacroArgExpansion(SL)) { 5579 SL = SM.getSpellingLoc(SL); 5580 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 5581 SM.getSpellingLoc(SR.getEnd())); 5582 } 5583 5584 // Check if the destination is an array (rather than a pointer to an array). 5585 QualType DstTy = DstArg->getType(); 5586 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 5587 Context); 5588 if (!isKnownSizeArray) { 5589 if (PatternType == 1) 5590 Diag(SL, diag::warn_strncat_wrong_size) << SR; 5591 else 5592 Diag(SL, diag::warn_strncat_src_size) << SR; 5593 return; 5594 } 5595 5596 if (PatternType == 1) 5597 Diag(SL, diag::warn_strncat_large_size) << SR; 5598 else 5599 Diag(SL, diag::warn_strncat_src_size) << SR; 5600 5601 SmallString<128> sizeString; 5602 llvm::raw_svector_ostream OS(sizeString); 5603 OS << "sizeof("; 5604 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 5605 OS << ") - "; 5606 OS << "strlen("; 5607 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 5608 OS << ") - 1"; 5609 5610 Diag(SL, diag::note_strncat_wrong_size) 5611 << FixItHint::CreateReplacement(SR, OS.str()); 5612} 5613 5614//===--- CHECK: Return Address of Stack Variable --------------------------===// 5615 5616static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 5617 Decl *ParentDecl); 5618static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars, 5619 Decl *ParentDecl); 5620 5621/// CheckReturnStackAddr - Check if a return statement returns the address 5622/// of a stack variable. 5623static void 5624CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 5625 SourceLocation ReturnLoc) { 5626 5627 Expr *stackE = nullptr; 5628 SmallVector<DeclRefExpr *, 8> refVars; 5629 5630 // Perform checking for returned stack addresses, local blocks, 5631 // label addresses or references to temporaries. 5632 if (lhsType->isPointerType() || 5633 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 5634 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 5635 } else if (lhsType->isReferenceType()) { 5636 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 5637 } 5638 5639 if (!stackE) 5640 return; // Nothing suspicious was found. 5641 5642 SourceLocation diagLoc; 5643 SourceRange diagRange; 5644 if (refVars.empty()) { 5645 diagLoc = stackE->getLocStart(); 5646 diagRange = stackE->getSourceRange(); 5647 } else { 5648 // We followed through a reference variable. 'stackE' contains the 5649 // problematic expression but we will warn at the return statement pointing 5650 // at the reference variable. We will later display the "trail" of 5651 // reference variables using notes. 5652 diagLoc = refVars[0]->getLocStart(); 5653 diagRange = refVars[0]->getSourceRange(); 5654 } 5655 5656 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var. 5657 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 5658 << DR->getDecl()->getDeclName() << diagRange; 5659 } else if (isa<BlockExpr>(stackE)) { // local block. 5660 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 5661 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 5662 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 5663 } else { // local temporary. 5664 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 5665 << lhsType->isReferenceType() << diagRange; 5666 } 5667 5668 // Display the "trail" of reference variables that we followed until we 5669 // found the problematic expression using notes. 5670 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 5671 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 5672 // If this var binds to another reference var, show the range of the next 5673 // var, otherwise the var binds to the problematic expression, in which case 5674 // show the range of the expression. 5675 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange() 5676 : stackE->getSourceRange(); 5677 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 5678 << VD->getDeclName() << range; 5679 } 5680} 5681 5682/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 5683/// check if the expression in a return statement evaluates to an address 5684/// to a location on the stack, a local block, an address of a label, or a 5685/// reference to local temporary. The recursion is used to traverse the 5686/// AST of the return expression, with recursion backtracking when we 5687/// encounter a subexpression that (1) clearly does not lead to one of the 5688/// above problematic expressions (2) is something we cannot determine leads to 5689/// a problematic expression based on such local checking. 5690/// 5691/// Both EvalAddr and EvalVal follow through reference variables to evaluate 5692/// the expression that they point to. Such variables are added to the 5693/// 'refVars' vector so that we know what the reference variable "trail" was. 5694/// 5695/// EvalAddr processes expressions that are pointers that are used as 5696/// references (and not L-values). EvalVal handles all other values. 5697/// At the base case of the recursion is a check for the above problematic 5698/// expressions. 5699/// 5700/// This implementation handles: 5701/// 5702/// * pointer-to-pointer casts 5703/// * implicit conversions from array references to pointers 5704/// * taking the address of fields 5705/// * arbitrary interplay between "&" and "*" operators 5706/// * pointer arithmetic from an address of a stack variable 5707/// * taking the address of an array element where the array is on the stack 5708static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 5709 Decl *ParentDecl) { 5710 if (E->isTypeDependent()) 5711 return nullptr; 5712 5713 // We should only be called for evaluating pointer expressions. 5714 assert((E->getType()->isAnyPointerType() || 5715 E->getType()->isBlockPointerType() || 5716 E->getType()->isObjCQualifiedIdType()) && 5717 "EvalAddr only works on pointers"); 5718 5719 E = E->IgnoreParens(); 5720 5721 // Our "symbolic interpreter" is just a dispatch off the currently 5722 // viewed AST node. We then recursively traverse the AST by calling 5723 // EvalAddr and EvalVal appropriately. 5724 switch (E->getStmtClass()) { 5725 case Stmt::DeclRefExprClass: { 5726 DeclRefExpr *DR = cast<DeclRefExpr>(E); 5727 5728 // If we leave the immediate function, the lifetime isn't about to end. 5729 if (DR->refersToEnclosingVariableOrCapture()) 5730 return nullptr; 5731 5732 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 5733 // If this is a reference variable, follow through to the expression that 5734 // it points to. 5735 if (V->hasLocalStorage() && 5736 V->getType()->isReferenceType() && V->hasInit()) { 5737 // Add the reference variable to the "trail". 5738 refVars.push_back(DR); 5739 return EvalAddr(V->getInit(), refVars, ParentDecl); 5740 } 5741 5742 return nullptr; 5743 } 5744 5745 case Stmt::UnaryOperatorClass: { 5746 // The only unary operator that make sense to handle here 5747 // is AddrOf. All others don't make sense as pointers. 5748 UnaryOperator *U = cast<UnaryOperator>(E); 5749 5750 if (U->getOpcode() == UO_AddrOf) 5751 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 5752 else 5753 return nullptr; 5754 } 5755 5756 case Stmt::BinaryOperatorClass: { 5757 // Handle pointer arithmetic. All other binary operators are not valid 5758 // in this context. 5759 BinaryOperator *B = cast<BinaryOperator>(E); 5760 BinaryOperatorKind op = B->getOpcode(); 5761 5762 if (op != BO_Add && op != BO_Sub) 5763 return nullptr; 5764 5765 Expr *Base = B->getLHS(); 5766 5767 // Determine which argument is the real pointer base. It could be 5768 // the RHS argument instead of the LHS. 5769 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 5770 5771 assert (Base->getType()->isPointerType()); 5772 return EvalAddr(Base, refVars, ParentDecl); 5773 } 5774 5775 // For conditional operators we need to see if either the LHS or RHS are 5776 // valid DeclRefExpr*s. If one of them is valid, we return it. 5777 case Stmt::ConditionalOperatorClass: { 5778 ConditionalOperator *C = cast<ConditionalOperator>(E); 5779 5780 // Handle the GNU extension for missing LHS. 5781 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 5782 if (Expr *LHSExpr = C->getLHS()) { 5783 // In C++, we can have a throw-expression, which has 'void' type. 5784 if (!LHSExpr->getType()->isVoidType()) 5785 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 5786 return LHS; 5787 } 5788 5789 // In C++, we can have a throw-expression, which has 'void' type. 5790 if (C->getRHS()->getType()->isVoidType()) 5791 return nullptr; 5792 5793 return EvalAddr(C->getRHS(), refVars, ParentDecl); 5794 } 5795 5796 case Stmt::BlockExprClass: 5797 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 5798 return E; // local block. 5799 return nullptr; 5800 5801 case Stmt::AddrLabelExprClass: 5802 return E; // address of label. 5803 5804 case Stmt::ExprWithCleanupsClass: 5805 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 5806 ParentDecl); 5807 5808 // For casts, we need to handle conversions from arrays to 5809 // pointer values, and pointer-to-pointer conversions. 5810 case Stmt::ImplicitCastExprClass: 5811 case Stmt::CStyleCastExprClass: 5812 case Stmt::CXXFunctionalCastExprClass: 5813 case Stmt::ObjCBridgedCastExprClass: 5814 case Stmt::CXXStaticCastExprClass: 5815 case Stmt::CXXDynamicCastExprClass: 5816 case Stmt::CXXConstCastExprClass: 5817 case Stmt::CXXReinterpretCastExprClass: { 5818 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 5819 switch (cast<CastExpr>(E)->getCastKind()) { 5820 case CK_LValueToRValue: 5821 case CK_NoOp: 5822 case CK_BaseToDerived: 5823 case CK_DerivedToBase: 5824 case CK_UncheckedDerivedToBase: 5825 case CK_Dynamic: 5826 case CK_CPointerToObjCPointerCast: 5827 case CK_BlockPointerToObjCPointerCast: 5828 case CK_AnyPointerToBlockPointerCast: 5829 return EvalAddr(SubExpr, refVars, ParentDecl); 5830 5831 case CK_ArrayToPointerDecay: 5832 return EvalVal(SubExpr, refVars, ParentDecl); 5833 5834 case CK_BitCast: 5835 if (SubExpr->getType()->isAnyPointerType() || 5836 SubExpr->getType()->isBlockPointerType() || 5837 SubExpr->getType()->isObjCQualifiedIdType()) 5838 return EvalAddr(SubExpr, refVars, ParentDecl); 5839 else 5840 return nullptr; 5841 5842 default: 5843 return nullptr; 5844 } 5845 } 5846 5847 case Stmt::MaterializeTemporaryExprClass: 5848 if (Expr *Result = EvalAddr( 5849 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 5850 refVars, ParentDecl)) 5851 return Result; 5852 5853 return E; 5854 5855 // Everything else: we simply don't reason about them. 5856 default: 5857 return nullptr; 5858 } 5859} 5860 5861 5862/// EvalVal - This function is complements EvalAddr in the mutual recursion. 5863/// See the comments for EvalAddr for more details. 5864static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 5865 Decl *ParentDecl) { 5866do { 5867 // We should only be called for evaluating non-pointer expressions, or 5868 // expressions with a pointer type that are not used as references but instead 5869 // are l-values (e.g., DeclRefExpr with a pointer type). 5870 5871 // Our "symbolic interpreter" is just a dispatch off the currently 5872 // viewed AST node. We then recursively traverse the AST by calling 5873 // EvalAddr and EvalVal appropriately. 5874 5875 E = E->IgnoreParens(); 5876 switch (E->getStmtClass()) { 5877 case Stmt::ImplicitCastExprClass: { 5878 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 5879 if (IE->getValueKind() == VK_LValue) { 5880 E = IE->getSubExpr(); 5881 continue; 5882 } 5883 return nullptr; 5884 } 5885 5886 case Stmt::ExprWithCleanupsClass: 5887 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl); 5888 5889 case Stmt::DeclRefExprClass: { 5890 // When we hit a DeclRefExpr we are looking at code that refers to a 5891 // variable's name. If it's not a reference variable we check if it has 5892 // local storage within the function, and if so, return the expression. 5893 DeclRefExpr *DR = cast<DeclRefExpr>(E); 5894 5895 // If we leave the immediate function, the lifetime isn't about to end. 5896 if (DR->refersToEnclosingVariableOrCapture()) 5897 return nullptr; 5898 5899 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 5900 // Check if it refers to itself, e.g. "int& i = i;". 5901 if (V == ParentDecl) 5902 return DR; 5903 5904 if (V->hasLocalStorage()) { 5905 if (!V->getType()->isReferenceType()) 5906 return DR; 5907 5908 // Reference variable, follow through to the expression that 5909 // it points to. 5910 if (V->hasInit()) { 5911 // Add the reference variable to the "trail". 5912 refVars.push_back(DR); 5913 return EvalVal(V->getInit(), refVars, V); 5914 } 5915 } 5916 } 5917 5918 return nullptr; 5919 } 5920 5921 case Stmt::UnaryOperatorClass: { 5922 // The only unary operator that make sense to handle here 5923 // is Deref. All others don't resolve to a "name." This includes 5924 // handling all sorts of rvalues passed to a unary operator. 5925 UnaryOperator *U = cast<UnaryOperator>(E); 5926 5927 if (U->getOpcode() == UO_Deref) 5928 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 5929 5930 return nullptr; 5931 } 5932 5933 case Stmt::ArraySubscriptExprClass: { 5934 // Array subscripts are potential references to data on the stack. We 5935 // retrieve the DeclRefExpr* for the array variable if it indeed 5936 // has local storage. 5937 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl); 5938 } 5939 5940 case Stmt::OMPArraySectionExprClass: { 5941 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 5942 ParentDecl); 5943 } 5944 5945 case Stmt::ConditionalOperatorClass: { 5946 // For conditional operators we need to see if either the LHS or RHS are 5947 // non-NULL Expr's. If one is non-NULL, we return it. 5948 ConditionalOperator *C = cast<ConditionalOperator>(E); 5949 5950 // Handle the GNU extension for missing LHS. 5951 if (Expr *LHSExpr = C->getLHS()) { 5952 // In C++, we can have a throw-expression, which has 'void' type. 5953 if (!LHSExpr->getType()->isVoidType()) 5954 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 5955 return LHS; 5956 } 5957 5958 // In C++, we can have a throw-expression, which has 'void' type. 5959 if (C->getRHS()->getType()->isVoidType()) 5960 return nullptr; 5961 5962 return EvalVal(C->getRHS(), refVars, ParentDecl); 5963 } 5964 5965 // Accesses to members are potential references to data on the stack. 5966 case Stmt::MemberExprClass: { 5967 MemberExpr *M = cast<MemberExpr>(E); 5968 5969 // Check for indirect access. We only want direct field accesses. 5970 if (M->isArrow()) 5971 return nullptr; 5972 5973 // Check whether the member type is itself a reference, in which case 5974 // we're not going to refer to the member, but to what the member refers to. 5975 if (M->getMemberDecl()->getType()->isReferenceType()) 5976 return nullptr; 5977 5978 return EvalVal(M->getBase(), refVars, ParentDecl); 5979 } 5980 5981 case Stmt::MaterializeTemporaryExprClass: 5982 if (Expr *Result = EvalVal( 5983 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 5984 refVars, ParentDecl)) 5985 return Result; 5986 5987 return E; 5988 5989 default: 5990 // Check that we don't return or take the address of a reference to a 5991 // temporary. This is only useful in C++. 5992 if (!E->isTypeDependent() && E->isRValue()) 5993 return E; 5994 5995 // Everything else: we simply don't reason about them. 5996 return nullptr; 5997 } 5998} while (true); 5999} 6000 6001void 6002Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 6003 SourceLocation ReturnLoc, 6004 bool isObjCMethod, 6005 const AttrVec *Attrs, 6006 const FunctionDecl *FD) { 6007 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 6008 6009 // Check if the return value is null but should not be. 6010 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 6011 (!isObjCMethod && isNonNullType(Context, lhsType))) && 6012 CheckNonNullExpr(*this, RetValExp)) 6013 Diag(ReturnLoc, diag::warn_null_ret) 6014 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 6015 6016 // C++11 [basic.stc.dynamic.allocation]p4: 6017 // If an allocation function declared with a non-throwing 6018 // exception-specification fails to allocate storage, it shall return 6019 // a null pointer. Any other allocation function that fails to allocate 6020 // storage shall indicate failure only by throwing an exception [...] 6021 if (FD) { 6022 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 6023 if (Op == OO_New || Op == OO_Array_New) { 6024 const FunctionProtoType *Proto 6025 = FD->getType()->castAs<FunctionProtoType>(); 6026 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 6027 CheckNonNullExpr(*this, RetValExp)) 6028 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 6029 << FD << getLangOpts().CPlusPlus11; 6030 } 6031 } 6032} 6033 6034//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 6035 6036/// Check for comparisons of floating point operands using != and ==. 6037/// Issue a warning if these are no self-comparisons, as they are not likely 6038/// to do what the programmer intended. 6039void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 6040 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 6041 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 6042 6043 // Special case: check for x == x (which is OK). 6044 // Do not emit warnings for such cases. 6045 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 6046 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 6047 if (DRL->getDecl() == DRR->getDecl()) 6048 return; 6049 6050 6051 // Special case: check for comparisons against literals that can be exactly 6052 // represented by APFloat. In such cases, do not emit a warning. This 6053 // is a heuristic: often comparison against such literals are used to 6054 // detect if a value in a variable has not changed. This clearly can 6055 // lead to false negatives. 6056 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 6057 if (FLL->isExact()) 6058 return; 6059 } else 6060 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 6061 if (FLR->isExact()) 6062 return; 6063 6064 // Check for comparisons with builtin types. 6065 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 6066 if (CL->getBuiltinCallee()) 6067 return; 6068 6069 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 6070 if (CR->getBuiltinCallee()) 6071 return; 6072 6073 // Emit the diagnostic. 6074 Diag(Loc, diag::warn_floatingpoint_eq) 6075 << LHS->getSourceRange() << RHS->getSourceRange(); 6076} 6077 6078//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 6079//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 6080 6081namespace { 6082 6083/// Structure recording the 'active' range of an integer-valued 6084/// expression. 6085struct IntRange { 6086 /// The number of bits active in the int. 6087 unsigned Width; 6088 6089 /// True if the int is known not to have negative values. 6090 bool NonNegative; 6091 6092 IntRange(unsigned Width, bool NonNegative) 6093 : Width(Width), NonNegative(NonNegative) 6094 {} 6095 6096 /// Returns the range of the bool type. 6097 static IntRange forBoolType() { 6098 return IntRange(1, true); 6099 } 6100 6101 /// Returns the range of an opaque value of the given integral type. 6102 static IntRange forValueOfType(ASTContext &C, QualType T) { 6103 return forValueOfCanonicalType(C, 6104 T->getCanonicalTypeInternal().getTypePtr()); 6105 } 6106 6107 /// Returns the range of an opaque value of a canonical integral type. 6108 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 6109 assert(T->isCanonicalUnqualified()); 6110 6111 if (const VectorType *VT = dyn_cast<VectorType>(T)) 6112 T = VT->getElementType().getTypePtr(); 6113 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 6114 T = CT->getElementType().getTypePtr(); 6115 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 6116 T = AT->getValueType().getTypePtr(); 6117 6118 // For enum types, use the known bit width of the enumerators. 6119 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 6120 EnumDecl *Enum = ET->getDecl(); 6121 if (!Enum->isCompleteDefinition()) 6122 return IntRange(C.getIntWidth(QualType(T, 0)), false); 6123 6124 unsigned NumPositive = Enum->getNumPositiveBits(); 6125 unsigned NumNegative = Enum->getNumNegativeBits(); 6126 6127 if (NumNegative == 0) 6128 return IntRange(NumPositive, true/*NonNegative*/); 6129 else 6130 return IntRange(std::max(NumPositive + 1, NumNegative), 6131 false/*NonNegative*/); 6132 } 6133 6134 const BuiltinType *BT = cast<BuiltinType>(T); 6135 assert(BT->isInteger()); 6136 6137 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 6138 } 6139 6140 /// Returns the "target" range of a canonical integral type, i.e. 6141 /// the range of values expressible in the type. 6142 /// 6143 /// This matches forValueOfCanonicalType except that enums have the 6144 /// full range of their type, not the range of their enumerators. 6145 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 6146 assert(T->isCanonicalUnqualified()); 6147 6148 if (const VectorType *VT = dyn_cast<VectorType>(T)) 6149 T = VT->getElementType().getTypePtr(); 6150 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 6151 T = CT->getElementType().getTypePtr(); 6152 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 6153 T = AT->getValueType().getTypePtr(); 6154 if (const EnumType *ET = dyn_cast<EnumType>(T)) 6155 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 6156 6157 const BuiltinType *BT = cast<BuiltinType>(T); 6158 assert(BT->isInteger()); 6159 6160 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 6161 } 6162 6163 /// Returns the supremum of two ranges: i.e. their conservative merge. 6164 static IntRange join(IntRange L, IntRange R) { 6165 return IntRange(std::max(L.Width, R.Width), 6166 L.NonNegative && R.NonNegative); 6167 } 6168 6169 /// Returns the infinum of two ranges: i.e. their aggressive merge. 6170 static IntRange meet(IntRange L, IntRange R) { 6171 return IntRange(std::min(L.Width, R.Width), 6172 L.NonNegative || R.NonNegative); 6173 } 6174}; 6175 6176static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 6177 unsigned MaxWidth) { 6178 if (value.isSigned() && value.isNegative()) 6179 return IntRange(value.getMinSignedBits(), false); 6180 6181 if (value.getBitWidth() > MaxWidth) 6182 value = value.trunc(MaxWidth); 6183 6184 // isNonNegative() just checks the sign bit without considering 6185 // signedness. 6186 return IntRange(value.getActiveBits(), true); 6187} 6188 6189static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 6190 unsigned MaxWidth) { 6191 if (result.isInt()) 6192 return GetValueRange(C, result.getInt(), MaxWidth); 6193 6194 if (result.isVector()) { 6195 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 6196 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 6197 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 6198 R = IntRange::join(R, El); 6199 } 6200 return R; 6201 } 6202 6203 if (result.isComplexInt()) { 6204 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 6205 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 6206 return IntRange::join(R, I); 6207 } 6208 6209 // This can happen with lossless casts to intptr_t of "based" lvalues. 6210 // Assume it might use arbitrary bits. 6211 // FIXME: The only reason we need to pass the type in here is to get 6212 // the sign right on this one case. It would be nice if APValue 6213 // preserved this. 6214 assert(result.isLValue() || result.isAddrLabelDiff()); 6215 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 6216} 6217 6218static QualType GetExprType(Expr *E) { 6219 QualType Ty = E->getType(); 6220 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 6221 Ty = AtomicRHS->getValueType(); 6222 return Ty; 6223} 6224 6225/// Pseudo-evaluate the given integer expression, estimating the 6226/// range of values it might take. 6227/// 6228/// \param MaxWidth - the width to which the value will be truncated 6229static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { 6230 E = E->IgnoreParens(); 6231 6232 // Try a full evaluation first. 6233 Expr::EvalResult result; 6234 if (E->EvaluateAsRValue(result, C)) 6235 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 6236 6237 // I think we only want to look through implicit casts here; if the 6238 // user has an explicit widening cast, we should treat the value as 6239 // being of the new, wider type. 6240 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 6241 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 6242 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 6243 6244 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 6245 6246 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 6247 CE->getCastKind() == CK_BooleanToSignedIntegral; 6248 6249 // Assume that non-integer casts can span the full range of the type. 6250 if (!isIntegerCast) 6251 return OutputTypeRange; 6252 6253 IntRange SubRange 6254 = GetExprRange(C, CE->getSubExpr(), 6255 std::min(MaxWidth, OutputTypeRange.Width)); 6256 6257 // Bail out if the subexpr's range is as wide as the cast type. 6258 if (SubRange.Width >= OutputTypeRange.Width) 6259 return OutputTypeRange; 6260 6261 // Otherwise, we take the smaller width, and we're non-negative if 6262 // either the output type or the subexpr is. 6263 return IntRange(SubRange.Width, 6264 SubRange.NonNegative || OutputTypeRange.NonNegative); 6265 } 6266 6267 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6268 // If we can fold the condition, just take that operand. 6269 bool CondResult; 6270 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 6271 return GetExprRange(C, CondResult ? CO->getTrueExpr() 6272 : CO->getFalseExpr(), 6273 MaxWidth); 6274 6275 // Otherwise, conservatively merge. 6276 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 6277 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 6278 return IntRange::join(L, R); 6279 } 6280 6281 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 6282 switch (BO->getOpcode()) { 6283 6284 // Boolean-valued operations are single-bit and positive. 6285 case BO_LAnd: 6286 case BO_LOr: 6287 case BO_LT: 6288 case BO_GT: 6289 case BO_LE: 6290 case BO_GE: 6291 case BO_EQ: 6292 case BO_NE: 6293 return IntRange::forBoolType(); 6294 6295 // The type of the assignments is the type of the LHS, so the RHS 6296 // is not necessarily the same type. 6297 case BO_MulAssign: 6298 case BO_DivAssign: 6299 case BO_RemAssign: 6300 case BO_AddAssign: 6301 case BO_SubAssign: 6302 case BO_XorAssign: 6303 case BO_OrAssign: 6304 // TODO: bitfields? 6305 return IntRange::forValueOfType(C, GetExprType(E)); 6306 6307 // Simple assignments just pass through the RHS, which will have 6308 // been coerced to the LHS type. 6309 case BO_Assign: 6310 // TODO: bitfields? 6311 return GetExprRange(C, BO->getRHS(), MaxWidth); 6312 6313 // Operations with opaque sources are black-listed. 6314 case BO_PtrMemD: 6315 case BO_PtrMemI: 6316 return IntRange::forValueOfType(C, GetExprType(E)); 6317 6318 // Bitwise-and uses the *infinum* of the two source ranges. 6319 case BO_And: 6320 case BO_AndAssign: 6321 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 6322 GetExprRange(C, BO->getRHS(), MaxWidth)); 6323 6324 // Left shift gets black-listed based on a judgement call. 6325 case BO_Shl: 6326 // ...except that we want to treat '1 << (blah)' as logically 6327 // positive. It's an important idiom. 6328 if (IntegerLiteral *I 6329 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 6330 if (I->getValue() == 1) { 6331 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 6332 return IntRange(R.Width, /*NonNegative*/ true); 6333 } 6334 } 6335 // fallthrough 6336 6337 case BO_ShlAssign: 6338 return IntRange::forValueOfType(C, GetExprType(E)); 6339 6340 // Right shift by a constant can narrow its left argument. 6341 case BO_Shr: 6342 case BO_ShrAssign: { 6343 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 6344 6345 // If the shift amount is a positive constant, drop the width by 6346 // that much. 6347 llvm::APSInt shift; 6348 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 6349 shift.isNonNegative()) { 6350 unsigned zext = shift.getZExtValue(); 6351 if (zext >= L.Width) 6352 L.Width = (L.NonNegative ? 0 : 1); 6353 else 6354 L.Width -= zext; 6355 } 6356 6357 return L; 6358 } 6359 6360 // Comma acts as its right operand. 6361 case BO_Comma: 6362 return GetExprRange(C, BO->getRHS(), MaxWidth); 6363 6364 // Black-list pointer subtractions. 6365 case BO_Sub: 6366 if (BO->getLHS()->getType()->isPointerType()) 6367 return IntRange::forValueOfType(C, GetExprType(E)); 6368 break; 6369 6370 // The width of a division result is mostly determined by the size 6371 // of the LHS. 6372 case BO_Div: { 6373 // Don't 'pre-truncate' the operands. 6374 unsigned opWidth = C.getIntWidth(GetExprType(E)); 6375 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 6376 6377 // If the divisor is constant, use that. 6378 llvm::APSInt divisor; 6379 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 6380 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 6381 if (log2 >= L.Width) 6382 L.Width = (L.NonNegative ? 0 : 1); 6383 else 6384 L.Width = std::min(L.Width - log2, MaxWidth); 6385 return L; 6386 } 6387 6388 // Otherwise, just use the LHS's width. 6389 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 6390 return IntRange(L.Width, L.NonNegative && R.NonNegative); 6391 } 6392 6393 // The result of a remainder can't be larger than the result of 6394 // either side. 6395 case BO_Rem: { 6396 // Don't 'pre-truncate' the operands. 6397 unsigned opWidth = C.getIntWidth(GetExprType(E)); 6398 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 6399 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 6400 6401 IntRange meet = IntRange::meet(L, R); 6402 meet.Width = std::min(meet.Width, MaxWidth); 6403 return meet; 6404 } 6405 6406 // The default behavior is okay for these. 6407 case BO_Mul: 6408 case BO_Add: 6409 case BO_Xor: 6410 case BO_Or: 6411 break; 6412 } 6413 6414 // The default case is to treat the operation as if it were closed 6415 // on the narrowest type that encompasses both operands. 6416 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 6417 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 6418 return IntRange::join(L, R); 6419 } 6420 6421 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 6422 switch (UO->getOpcode()) { 6423 // Boolean-valued operations are white-listed. 6424 case UO_LNot: 6425 return IntRange::forBoolType(); 6426 6427 // Operations with opaque sources are black-listed. 6428 case UO_Deref: 6429 case UO_AddrOf: // should be impossible 6430 return IntRange::forValueOfType(C, GetExprType(E)); 6431 6432 default: 6433 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 6434 } 6435 } 6436 6437 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) 6438 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 6439 6440 if (FieldDecl *BitField = E->getSourceBitField()) 6441 return IntRange(BitField->getBitWidthValue(C), 6442 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 6443 6444 return IntRange::forValueOfType(C, GetExprType(E)); 6445} 6446 6447static IntRange GetExprRange(ASTContext &C, Expr *E) { 6448 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 6449} 6450 6451/// Checks whether the given value, which currently has the given 6452/// source semantics, has the same value when coerced through the 6453/// target semantics. 6454static bool IsSameFloatAfterCast(const llvm::APFloat &value, 6455 const llvm::fltSemantics &Src, 6456 const llvm::fltSemantics &Tgt) { 6457 llvm::APFloat truncated = value; 6458 6459 bool ignored; 6460 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 6461 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 6462 6463 return truncated.bitwiseIsEqual(value); 6464} 6465 6466/// Checks whether the given value, which currently has the given 6467/// source semantics, has the same value when coerced through the 6468/// target semantics. 6469/// 6470/// The value might be a vector of floats (or a complex number). 6471static bool IsSameFloatAfterCast(const APValue &value, 6472 const llvm::fltSemantics &Src, 6473 const llvm::fltSemantics &Tgt) { 6474 if (value.isFloat()) 6475 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 6476 6477 if (value.isVector()) { 6478 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 6479 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 6480 return false; 6481 return true; 6482 } 6483 6484 assert(value.isComplexFloat()); 6485 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 6486 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 6487} 6488 6489static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 6490 6491static bool IsZero(Sema &S, Expr *E) { 6492 // Suppress cases where we are comparing against an enum constant. 6493 if (const DeclRefExpr *DR = 6494 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 6495 if (isa<EnumConstantDecl>(DR->getDecl())) 6496 return false; 6497 6498 // Suppress cases where the '0' value is expanded from a macro. 6499 if (E->getLocStart().isMacroID()) 6500 return false; 6501 6502 llvm::APSInt Value; 6503 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 6504} 6505 6506static bool HasEnumType(Expr *E) { 6507 // Strip off implicit integral promotions. 6508 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6509 if (ICE->getCastKind() != CK_IntegralCast && 6510 ICE->getCastKind() != CK_NoOp) 6511 break; 6512 E = ICE->getSubExpr(); 6513 } 6514 6515 return E->getType()->isEnumeralType(); 6516} 6517 6518static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 6519 // Disable warning in template instantiations. 6520 if (!S.ActiveTemplateInstantiations.empty()) 6521 return; 6522 6523 BinaryOperatorKind op = E->getOpcode(); 6524 if (E->isValueDependent()) 6525 return; 6526 6527 if (op == BO_LT && IsZero(S, E->getRHS())) { 6528 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 6529 << "< 0" << "false" << HasEnumType(E->getLHS()) 6530 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 6531 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 6532 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 6533 << ">= 0" << "true" << HasEnumType(E->getLHS()) 6534 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 6535 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 6536 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 6537 << "0 >" << "false" << HasEnumType(E->getRHS()) 6538 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 6539 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 6540 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 6541 << "0 <=" << "true" << HasEnumType(E->getRHS()) 6542 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 6543 } 6544} 6545 6546static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, 6547 Expr *Constant, Expr *Other, 6548 llvm::APSInt Value, 6549 bool RhsConstant) { 6550 // Disable warning in template instantiations. 6551 if (!S.ActiveTemplateInstantiations.empty()) 6552 return; 6553 6554 // TODO: Investigate using GetExprRange() to get tighter bounds 6555 // on the bit ranges. 6556 QualType OtherT = Other->getType(); 6557 if (const auto *AT = OtherT->getAs<AtomicType>()) 6558 OtherT = AT->getValueType(); 6559 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 6560 unsigned OtherWidth = OtherRange.Width; 6561 6562 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 6563 6564 // 0 values are handled later by CheckTrivialUnsignedComparison(). 6565 if ((Value == 0) && (!OtherIsBooleanType)) 6566 return; 6567 6568 BinaryOperatorKind op = E->getOpcode(); 6569 bool IsTrue = true; 6570 6571 // Used for diagnostic printout. 6572 enum { 6573 LiteralConstant = 0, 6574 CXXBoolLiteralTrue, 6575 CXXBoolLiteralFalse 6576 } LiteralOrBoolConstant = LiteralConstant; 6577 6578 if (!OtherIsBooleanType) { 6579 QualType ConstantT = Constant->getType(); 6580 QualType CommonT = E->getLHS()->getType(); 6581 6582 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 6583 return; 6584 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 6585 "comparison with non-integer type"); 6586 6587 bool ConstantSigned = ConstantT->isSignedIntegerType(); 6588 bool CommonSigned = CommonT->isSignedIntegerType(); 6589 6590 bool EqualityOnly = false; 6591 6592 if (CommonSigned) { 6593 // The common type is signed, therefore no signed to unsigned conversion. 6594 if (!OtherRange.NonNegative) { 6595 // Check that the constant is representable in type OtherT. 6596 if (ConstantSigned) { 6597 if (OtherWidth >= Value.getMinSignedBits()) 6598 return; 6599 } else { // !ConstantSigned 6600 if (OtherWidth >= Value.getActiveBits() + 1) 6601 return; 6602 } 6603 } else { // !OtherSigned 6604 // Check that the constant is representable in type OtherT. 6605 // Negative values are out of range. 6606 if (ConstantSigned) { 6607 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 6608 return; 6609 } else { // !ConstantSigned 6610 if (OtherWidth >= Value.getActiveBits()) 6611 return; 6612 } 6613 } 6614 } else { // !CommonSigned 6615 if (OtherRange.NonNegative) { 6616 if (OtherWidth >= Value.getActiveBits()) 6617 return; 6618 } else { // OtherSigned 6619 assert(!ConstantSigned && 6620 "Two signed types converted to unsigned types."); 6621 // Check to see if the constant is representable in OtherT. 6622 if (OtherWidth > Value.getActiveBits()) 6623 return; 6624 // Check to see if the constant is equivalent to a negative value 6625 // cast to CommonT. 6626 if (S.Context.getIntWidth(ConstantT) == 6627 S.Context.getIntWidth(CommonT) && 6628 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 6629 return; 6630 // The constant value rests between values that OtherT can represent 6631 // after conversion. Relational comparison still works, but equality 6632 // comparisons will be tautological. 6633 EqualityOnly = true; 6634 } 6635 } 6636 6637 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 6638 6639 if (op == BO_EQ || op == BO_NE) { 6640 IsTrue = op == BO_NE; 6641 } else if (EqualityOnly) { 6642 return; 6643 } else if (RhsConstant) { 6644 if (op == BO_GT || op == BO_GE) 6645 IsTrue = !PositiveConstant; 6646 else // op == BO_LT || op == BO_LE 6647 IsTrue = PositiveConstant; 6648 } else { 6649 if (op == BO_LT || op == BO_LE) 6650 IsTrue = !PositiveConstant; 6651 else // op == BO_GT || op == BO_GE 6652 IsTrue = PositiveConstant; 6653 } 6654 } else { 6655 // Other isKnownToHaveBooleanValue 6656 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 6657 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 6658 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 6659 6660 static const struct LinkedConditions { 6661 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 6662 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 6663 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 6664 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 6665 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 6666 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 6667 6668 } TruthTable = { 6669 // Constant on LHS. | Constant on RHS. | 6670 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 6671 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 6672 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 6673 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 6674 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 6675 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 6676 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 6677 }; 6678 6679 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 6680 6681 enum ConstantValue ConstVal = Zero; 6682 if (Value.isUnsigned() || Value.isNonNegative()) { 6683 if (Value == 0) { 6684 LiteralOrBoolConstant = 6685 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 6686 ConstVal = Zero; 6687 } else if (Value == 1) { 6688 LiteralOrBoolConstant = 6689 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 6690 ConstVal = One; 6691 } else { 6692 LiteralOrBoolConstant = LiteralConstant; 6693 ConstVal = GT_One; 6694 } 6695 } else { 6696 ConstVal = LT_Zero; 6697 } 6698 6699 CompareBoolWithConstantResult CmpRes; 6700 6701 switch (op) { 6702 case BO_LT: 6703 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 6704 break; 6705 case BO_GT: 6706 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 6707 break; 6708 case BO_LE: 6709 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 6710 break; 6711 case BO_GE: 6712 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 6713 break; 6714 case BO_EQ: 6715 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 6716 break; 6717 case BO_NE: 6718 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 6719 break; 6720 default: 6721 CmpRes = Unkwn; 6722 break; 6723 } 6724 6725 if (CmpRes == AFals) { 6726 IsTrue = false; 6727 } else if (CmpRes == ATrue) { 6728 IsTrue = true; 6729 } else { 6730 return; 6731 } 6732 } 6733 6734 // If this is a comparison to an enum constant, include that 6735 // constant in the diagnostic. 6736 const EnumConstantDecl *ED = nullptr; 6737 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 6738 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 6739 6740 SmallString<64> PrettySourceValue; 6741 llvm::raw_svector_ostream OS(PrettySourceValue); 6742 if (ED) 6743 OS << '\'' << *ED << "' (" << Value << ")"; 6744 else 6745 OS << Value; 6746 6747 S.DiagRuntimeBehavior( 6748 E->getOperatorLoc(), E, 6749 S.PDiag(diag::warn_out_of_range_compare) 6750 << OS.str() << LiteralOrBoolConstant 6751 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 6752 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 6753} 6754 6755/// Analyze the operands of the given comparison. Implements the 6756/// fallback case from AnalyzeComparison. 6757static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 6758 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 6759 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 6760} 6761 6762/// \brief Implements -Wsign-compare. 6763/// 6764/// \param E the binary operator to check for warnings 6765static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 6766 // The type the comparison is being performed in. 6767 QualType T = E->getLHS()->getType(); 6768 6769 // Only analyze comparison operators where both sides have been converted to 6770 // the same type. 6771 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 6772 return AnalyzeImpConvsInComparison(S, E); 6773 6774 // Don't analyze value-dependent comparisons directly. 6775 if (E->isValueDependent()) 6776 return AnalyzeImpConvsInComparison(S, E); 6777 6778 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 6779 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 6780 6781 bool IsComparisonConstant = false; 6782 6783 // Check whether an integer constant comparison results in a value 6784 // of 'true' or 'false'. 6785 if (T->isIntegralType(S.Context)) { 6786 llvm::APSInt RHSValue; 6787 bool IsRHSIntegralLiteral = 6788 RHS->isIntegerConstantExpr(RHSValue, S.Context); 6789 llvm::APSInt LHSValue; 6790 bool IsLHSIntegralLiteral = 6791 LHS->isIntegerConstantExpr(LHSValue, S.Context); 6792 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 6793 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 6794 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 6795 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 6796 else 6797 IsComparisonConstant = 6798 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 6799 } else if (!T->hasUnsignedIntegerRepresentation()) 6800 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 6801 6802 // We don't do anything special if this isn't an unsigned integral 6803 // comparison: we're only interested in integral comparisons, and 6804 // signed comparisons only happen in cases we don't care to warn about. 6805 // 6806 // We also don't care about value-dependent expressions or expressions 6807 // whose result is a constant. 6808 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 6809 return AnalyzeImpConvsInComparison(S, E); 6810 6811 // Check to see if one of the (unmodified) operands is of different 6812 // signedness. 6813 Expr *signedOperand, *unsignedOperand; 6814 if (LHS->getType()->hasSignedIntegerRepresentation()) { 6815 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 6816 "unsigned comparison between two signed integer expressions?"); 6817 signedOperand = LHS; 6818 unsignedOperand = RHS; 6819 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 6820 signedOperand = RHS; 6821 unsignedOperand = LHS; 6822 } else { 6823 CheckTrivialUnsignedComparison(S, E); 6824 return AnalyzeImpConvsInComparison(S, E); 6825 } 6826 6827 // Otherwise, calculate the effective range of the signed operand. 6828 IntRange signedRange = GetExprRange(S.Context, signedOperand); 6829 6830 // Go ahead and analyze implicit conversions in the operands. Note 6831 // that we skip the implicit conversions on both sides. 6832 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 6833 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 6834 6835 // If the signed range is non-negative, -Wsign-compare won't fire, 6836 // but we should still check for comparisons which are always true 6837 // or false. 6838 if (signedRange.NonNegative) 6839 return CheckTrivialUnsignedComparison(S, E); 6840 6841 // For (in)equality comparisons, if the unsigned operand is a 6842 // constant which cannot collide with a overflowed signed operand, 6843 // then reinterpreting the signed operand as unsigned will not 6844 // change the result of the comparison. 6845 if (E->isEqualityOp()) { 6846 unsigned comparisonWidth = S.Context.getIntWidth(T); 6847 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 6848 6849 // We should never be unable to prove that the unsigned operand is 6850 // non-negative. 6851 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 6852 6853 if (unsignedRange.Width < comparisonWidth) 6854 return; 6855 } 6856 6857 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 6858 S.PDiag(diag::warn_mixed_sign_comparison) 6859 << LHS->getType() << RHS->getType() 6860 << LHS->getSourceRange() << RHS->getSourceRange()); 6861} 6862 6863/// Analyzes an attempt to assign the given value to a bitfield. 6864/// 6865/// Returns true if there was something fishy about the attempt. 6866static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 6867 SourceLocation InitLoc) { 6868 assert(Bitfield->isBitField()); 6869 if (Bitfield->isInvalidDecl()) 6870 return false; 6871 6872 // White-list bool bitfields. 6873 if (Bitfield->getType()->isBooleanType()) 6874 return false; 6875 6876 // Ignore value- or type-dependent expressions. 6877 if (Bitfield->getBitWidth()->isValueDependent() || 6878 Bitfield->getBitWidth()->isTypeDependent() || 6879 Init->isValueDependent() || 6880 Init->isTypeDependent()) 6881 return false; 6882 6883 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 6884 6885 llvm::APSInt Value; 6886 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 6887 return false; 6888 6889 unsigned OriginalWidth = Value.getBitWidth(); 6890 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 6891 6892 if (OriginalWidth <= FieldWidth) 6893 return false; 6894 6895 // Compute the value which the bitfield will contain. 6896 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 6897 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType()); 6898 6899 // Check whether the stored value is equal to the original value. 6900 TruncatedValue = TruncatedValue.extend(OriginalWidth); 6901 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 6902 return false; 6903 6904 // Special-case bitfields of width 1: booleans are naturally 0/1, and 6905 // therefore don't strictly fit into a signed bitfield of width 1. 6906 if (FieldWidth == 1 && Value == 1) 6907 return false; 6908 6909 std::string PrettyValue = Value.toString(10); 6910 std::string PrettyTrunc = TruncatedValue.toString(10); 6911 6912 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 6913 << PrettyValue << PrettyTrunc << OriginalInit->getType() 6914 << Init->getSourceRange(); 6915 6916 return true; 6917} 6918 6919/// Analyze the given simple or compound assignment for warning-worthy 6920/// operations. 6921static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 6922 // Just recurse on the LHS. 6923 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 6924 6925 // We want to recurse on the RHS as normal unless we're assigning to 6926 // a bitfield. 6927 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 6928 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 6929 E->getOperatorLoc())) { 6930 // Recurse, ignoring any implicit conversions on the RHS. 6931 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 6932 E->getOperatorLoc()); 6933 } 6934 } 6935 6936 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 6937} 6938 6939/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 6940static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 6941 SourceLocation CContext, unsigned diag, 6942 bool pruneControlFlow = false) { 6943 if (pruneControlFlow) { 6944 S.DiagRuntimeBehavior(E->getExprLoc(), E, 6945 S.PDiag(diag) 6946 << SourceType << T << E->getSourceRange() 6947 << SourceRange(CContext)); 6948 return; 6949 } 6950 S.Diag(E->getExprLoc(), diag) 6951 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 6952} 6953 6954/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 6955static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 6956 SourceLocation CContext, unsigned diag, 6957 bool pruneControlFlow = false) { 6958 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 6959} 6960 6961/// Diagnose an implicit cast from a literal expression. Does not warn when the 6962/// cast wouldn't lose information. 6963void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T, 6964 SourceLocation CContext) { 6965 // Try to convert the literal exactly to an integer. If we can, don't warn. 6966 bool isExact = false; 6967 const llvm::APFloat &Value = FL->getValue(); 6968 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 6969 T->hasUnsignedIntegerRepresentation()); 6970 if (Value.convertToInteger(IntegerValue, 6971 llvm::APFloat::rmTowardZero, &isExact) 6972 == llvm::APFloat::opOK && isExact) 6973 return; 6974 6975 // FIXME: Force the precision of the source value down so we don't print 6976 // digits which are usually useless (we don't really care here if we 6977 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 6978 // would automatically print the shortest representation, but it's a bit 6979 // tricky to implement. 6980 SmallString<16> PrettySourceValue; 6981 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 6982 precision = (precision * 59 + 195) / 196; 6983 Value.toString(PrettySourceValue, precision); 6984 6985 SmallString<16> PrettyTargetValue; 6986 if (T->isSpecificBuiltinType(BuiltinType::Bool)) 6987 PrettyTargetValue = Value.isZero() ? "false" : "true"; 6988 else 6989 IntegerValue.toString(PrettyTargetValue); 6990 6991 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer) 6992 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue 6993 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext); 6994} 6995 6996std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 6997 if (!Range.Width) return "0"; 6998 6999 llvm::APSInt ValueInRange = Value; 7000 ValueInRange.setIsSigned(!Range.NonNegative); 7001 ValueInRange = ValueInRange.trunc(Range.Width); 7002 return ValueInRange.toString(10); 7003} 7004 7005static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 7006 if (!isa<ImplicitCastExpr>(Ex)) 7007 return false; 7008 7009 Expr *InnerE = Ex->IgnoreParenImpCasts(); 7010 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 7011 const Type *Source = 7012 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 7013 if (Target->isDependentType()) 7014 return false; 7015 7016 const BuiltinType *FloatCandidateBT = 7017 dyn_cast<BuiltinType>(ToBool ? Source : Target); 7018 const Type *BoolCandidateType = ToBool ? Target : Source; 7019 7020 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 7021 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 7022} 7023 7024void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 7025 SourceLocation CC) { 7026 unsigned NumArgs = TheCall->getNumArgs(); 7027 for (unsigned i = 0; i < NumArgs; ++i) { 7028 Expr *CurrA = TheCall->getArg(i); 7029 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 7030 continue; 7031 7032 bool IsSwapped = ((i > 0) && 7033 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 7034 IsSwapped |= ((i < (NumArgs - 1)) && 7035 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 7036 if (IsSwapped) { 7037 // Warn on this floating-point to bool conversion. 7038 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 7039 CurrA->getType(), CC, 7040 diag::warn_impcast_floating_point_to_bool); 7041 } 7042 } 7043} 7044 7045static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 7046 SourceLocation CC) { 7047 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 7048 E->getExprLoc())) 7049 return; 7050 7051 // Don't warn on functions which have return type nullptr_t. 7052 if (isa<CallExpr>(E)) 7053 return; 7054 7055 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 7056 const Expr::NullPointerConstantKind NullKind = 7057 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 7058 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 7059 return; 7060 7061 // Return if target type is a safe conversion. 7062 if (T->isAnyPointerType() || T->isBlockPointerType() || 7063 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 7064 return; 7065 7066 SourceLocation Loc = E->getSourceRange().getBegin(); 7067 7068 // __null is usually wrapped in a macro. Go up a macro if that is the case. 7069 if (NullKind == Expr::NPCK_GNUNull) { 7070 if (Loc.isMacroID()) { 7071 StringRef MacroName = 7072 Lexer::getImmediateMacroName(Loc, S.SourceMgr, S.getLangOpts()); 7073 if (MacroName == "NULL") 7074 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 7075 } 7076 } 7077 7078 // Only warn if the null and context location are in the same macro expansion. 7079 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 7080 return; 7081 7082 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 7083 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) 7084 << FixItHint::CreateReplacement(Loc, 7085 S.getFixItZeroLiteralForType(T, Loc)); 7086} 7087 7088static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 7089 ObjCArrayLiteral *ArrayLiteral); 7090static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 7091 ObjCDictionaryLiteral *DictionaryLiteral); 7092 7093/// Check a single element within a collection literal against the 7094/// target element type. 7095static void checkObjCCollectionLiteralElement(Sema &S, 7096 QualType TargetElementType, 7097 Expr *Element, 7098 unsigned ElementKind) { 7099 // Skip a bitcast to 'id' or qualified 'id'. 7100 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 7101 if (ICE->getCastKind() == CK_BitCast && 7102 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 7103 Element = ICE->getSubExpr(); 7104 } 7105 7106 QualType ElementType = Element->getType(); 7107 ExprResult ElementResult(Element); 7108 if (ElementType->getAs<ObjCObjectPointerType>() && 7109 S.CheckSingleAssignmentConstraints(TargetElementType, 7110 ElementResult, 7111 false, false) 7112 != Sema::Compatible) { 7113 S.Diag(Element->getLocStart(), 7114 diag::warn_objc_collection_literal_element) 7115 << ElementType << ElementKind << TargetElementType 7116 << Element->getSourceRange(); 7117 } 7118 7119 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 7120 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 7121 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 7122 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 7123} 7124 7125/// Check an Objective-C array literal being converted to the given 7126/// target type. 7127static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 7128 ObjCArrayLiteral *ArrayLiteral) { 7129 if (!S.NSArrayDecl) 7130 return; 7131 7132 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 7133 if (!TargetObjCPtr) 7134 return; 7135 7136 if (TargetObjCPtr->isUnspecialized() || 7137 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 7138 != S.NSArrayDecl->getCanonicalDecl()) 7139 return; 7140 7141 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 7142 if (TypeArgs.size() != 1) 7143 return; 7144 7145 QualType TargetElementType = TypeArgs[0]; 7146 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 7147 checkObjCCollectionLiteralElement(S, TargetElementType, 7148 ArrayLiteral->getElement(I), 7149 0); 7150 } 7151} 7152 7153/// Check an Objective-C dictionary literal being converted to the given 7154/// target type. 7155static void checkObjCDictionaryLiteral( 7156 Sema &S, QualType TargetType, 7157 ObjCDictionaryLiteral *DictionaryLiteral) { 7158 if (!S.NSDictionaryDecl) 7159 return; 7160 7161 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 7162 if (!TargetObjCPtr) 7163 return; 7164 7165 if (TargetObjCPtr->isUnspecialized() || 7166 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 7167 != S.NSDictionaryDecl->getCanonicalDecl()) 7168 return; 7169 7170 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 7171 if (TypeArgs.size() != 2) 7172 return; 7173 7174 QualType TargetKeyType = TypeArgs[0]; 7175 QualType TargetObjectType = TypeArgs[1]; 7176 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 7177 auto Element = DictionaryLiteral->getKeyValueElement(I); 7178 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 7179 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 7180 } 7181} 7182 7183void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 7184 SourceLocation CC, bool *ICContext = nullptr) { 7185 if (E->isTypeDependent() || E->isValueDependent()) return; 7186 7187 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 7188 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 7189 if (Source == Target) return; 7190 if (Target->isDependentType()) return; 7191 7192 // If the conversion context location is invalid don't complain. We also 7193 // don't want to emit a warning if the issue occurs from the expansion of 7194 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 7195 // delay this check as long as possible. Once we detect we are in that 7196 // scenario, we just return. 7197 if (CC.isInvalid()) 7198 return; 7199 7200 // Diagnose implicit casts to bool. 7201 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 7202 if (isa<StringLiteral>(E)) 7203 // Warn on string literal to bool. Checks for string literals in logical 7204 // and expressions, for instance, assert(0 && "error here"), are 7205 // prevented by a check in AnalyzeImplicitConversions(). 7206 return DiagnoseImpCast(S, E, T, CC, 7207 diag::warn_impcast_string_literal_to_bool); 7208 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 7209 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 7210 // This covers the literal expressions that evaluate to Objective-C 7211 // objects. 7212 return DiagnoseImpCast(S, E, T, CC, 7213 diag::warn_impcast_objective_c_literal_to_bool); 7214 } 7215 if (Source->isPointerType() || Source->canDecayToPointerType()) { 7216 // Warn on pointer to bool conversion that is always true. 7217 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 7218 SourceRange(CC)); 7219 } 7220 } 7221 7222 // Check implicit casts from Objective-C collection literals to specialized 7223 // collection types, e.g., NSArray<NSString *> *. 7224 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 7225 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 7226 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 7227 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 7228 7229 // Strip vector types. 7230 if (isa<VectorType>(Source)) { 7231 if (!isa<VectorType>(Target)) { 7232 if (S.SourceMgr.isInSystemMacro(CC)) 7233 return; 7234 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 7235 } 7236 7237 // If the vector cast is cast between two vectors of the same size, it is 7238 // a bitcast, not a conversion. 7239 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 7240 return; 7241 7242 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 7243 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 7244 } 7245 if (auto VecTy = dyn_cast<VectorType>(Target)) 7246 Target = VecTy->getElementType().getTypePtr(); 7247 7248 // Strip complex types. 7249 if (isa<ComplexType>(Source)) { 7250 if (!isa<ComplexType>(Target)) { 7251 if (S.SourceMgr.isInSystemMacro(CC)) 7252 return; 7253 7254 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 7255 } 7256 7257 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 7258 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 7259 } 7260 7261 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 7262 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 7263 7264 // If the source is floating point... 7265 if (SourceBT && SourceBT->isFloatingPoint()) { 7266 // ...and the target is floating point... 7267 if (TargetBT && TargetBT->isFloatingPoint()) { 7268 // ...then warn if we're dropping FP rank. 7269 7270 // Builtin FP kinds are ordered by increasing FP rank. 7271 if (SourceBT->getKind() > TargetBT->getKind()) { 7272 // Don't warn about float constants that are precisely 7273 // representable in the target type. 7274 Expr::EvalResult result; 7275 if (E->EvaluateAsRValue(result, S.Context)) { 7276 // Value might be a float, a float vector, or a float complex. 7277 if (IsSameFloatAfterCast(result.Val, 7278 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 7279 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 7280 return; 7281 } 7282 7283 if (S.SourceMgr.isInSystemMacro(CC)) 7284 return; 7285 7286 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 7287 7288 } 7289 // ... or possibly if we're increasing rank, too 7290 else if (TargetBT->getKind() > SourceBT->getKind()) { 7291 if (S.SourceMgr.isInSystemMacro(CC)) 7292 return; 7293 7294 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 7295 } 7296 return; 7297 } 7298 7299 // If the target is integral, always warn. 7300 if (TargetBT && TargetBT->isInteger()) { 7301 if (S.SourceMgr.isInSystemMacro(CC)) 7302 return; 7303 7304 Expr *InnerE = E->IgnoreParenImpCasts(); 7305 // We also want to warn on, e.g., "int i = -1.234" 7306 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 7307 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 7308 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 7309 7310 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) { 7311 DiagnoseFloatingLiteralImpCast(S, FL, T, CC); 7312 } else { 7313 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer); 7314 } 7315 } 7316 7317 // Detect the case where a call result is converted from floating-point to 7318 // to bool, and the final argument to the call is converted from bool, to 7319 // discover this typo: 7320 // 7321 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 7322 // 7323 // FIXME: This is an incredibly special case; is there some more general 7324 // way to detect this class of misplaced-parentheses bug? 7325 if (Target->isBooleanType() && isa<CallExpr>(E)) { 7326 // Check last argument of function call to see if it is an 7327 // implicit cast from a type matching the type the result 7328 // is being cast to. 7329 CallExpr *CEx = cast<CallExpr>(E); 7330 if (unsigned NumArgs = CEx->getNumArgs()) { 7331 Expr *LastA = CEx->getArg(NumArgs - 1); 7332 Expr *InnerE = LastA->IgnoreParenImpCasts(); 7333 if (isa<ImplicitCastExpr>(LastA) && 7334 InnerE->getType()->isBooleanType()) { 7335 // Warn on this floating-point to bool conversion 7336 DiagnoseImpCast(S, E, T, CC, 7337 diag::warn_impcast_floating_point_to_bool); 7338 } 7339 } 7340 } 7341 return; 7342 } 7343 7344 DiagnoseNullConversion(S, E, T, CC); 7345 7346 if (!Source->isIntegerType() || !Target->isIntegerType()) 7347 return; 7348 7349 // TODO: remove this early return once the false positives for constant->bool 7350 // in templates, macros, etc, are reduced or removed. 7351 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 7352 return; 7353 7354 IntRange SourceRange = GetExprRange(S.Context, E); 7355 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 7356 7357 if (SourceRange.Width > TargetRange.Width) { 7358 // If the source is a constant, use a default-on diagnostic. 7359 // TODO: this should happen for bitfield stores, too. 7360 llvm::APSInt Value(32); 7361 if (E->isIntegerConstantExpr(Value, S.Context)) { 7362 if (S.SourceMgr.isInSystemMacro(CC)) 7363 return; 7364 7365 std::string PrettySourceValue = Value.toString(10); 7366 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 7367 7368 S.DiagRuntimeBehavior(E->getExprLoc(), E, 7369 S.PDiag(diag::warn_impcast_integer_precision_constant) 7370 << PrettySourceValue << PrettyTargetValue 7371 << E->getType() << T << E->getSourceRange() 7372 << clang::SourceRange(CC)); 7373 return; 7374 } 7375 7376 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 7377 if (S.SourceMgr.isInSystemMacro(CC)) 7378 return; 7379 7380 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 7381 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 7382 /* pruneControlFlow */ true); 7383 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 7384 } 7385 7386 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 7387 (!TargetRange.NonNegative && SourceRange.NonNegative && 7388 SourceRange.Width == TargetRange.Width)) { 7389 7390 if (S.SourceMgr.isInSystemMacro(CC)) 7391 return; 7392 7393 unsigned DiagID = diag::warn_impcast_integer_sign; 7394 7395 // Traditionally, gcc has warned about this under -Wsign-compare. 7396 // We also want to warn about it in -Wconversion. 7397 // So if -Wconversion is off, use a completely identical diagnostic 7398 // in the sign-compare group. 7399 // The conditional-checking code will 7400 if (ICContext) { 7401 DiagID = diag::warn_impcast_integer_sign_conditional; 7402 *ICContext = true; 7403 } 7404 7405 return DiagnoseImpCast(S, E, T, CC, DiagID); 7406 } 7407 7408 // Diagnose conversions between different enumeration types. 7409 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 7410 // type, to give us better diagnostics. 7411 QualType SourceType = E->getType(); 7412 if (!S.getLangOpts().CPlusPlus) { 7413 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 7414 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 7415 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 7416 SourceType = S.Context.getTypeDeclType(Enum); 7417 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 7418 } 7419 } 7420 7421 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 7422 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 7423 if (SourceEnum->getDecl()->hasNameForLinkage() && 7424 TargetEnum->getDecl()->hasNameForLinkage() && 7425 SourceEnum != TargetEnum) { 7426 if (S.SourceMgr.isInSystemMacro(CC)) 7427 return; 7428 7429 return DiagnoseImpCast(S, E, SourceType, T, CC, 7430 diag::warn_impcast_different_enum_types); 7431 } 7432 7433 return; 7434} 7435 7436void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 7437 SourceLocation CC, QualType T); 7438 7439void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 7440 SourceLocation CC, bool &ICContext) { 7441 E = E->IgnoreParenImpCasts(); 7442 7443 if (isa<ConditionalOperator>(E)) 7444 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 7445 7446 AnalyzeImplicitConversions(S, E, CC); 7447 if (E->getType() != T) 7448 return CheckImplicitConversion(S, E, T, CC, &ICContext); 7449 return; 7450} 7451 7452void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 7453 SourceLocation CC, QualType T) { 7454 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 7455 7456 bool Suspicious = false; 7457 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 7458 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 7459 7460 // If -Wconversion would have warned about either of the candidates 7461 // for a signedness conversion to the context type... 7462 if (!Suspicious) return; 7463 7464 // ...but it's currently ignored... 7465 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 7466 return; 7467 7468 // ...then check whether it would have warned about either of the 7469 // candidates for a signedness conversion to the condition type. 7470 if (E->getType() == T) return; 7471 7472 Suspicious = false; 7473 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 7474 E->getType(), CC, &Suspicious); 7475 if (!Suspicious) 7476 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 7477 E->getType(), CC, &Suspicious); 7478} 7479 7480/// CheckBoolLikeConversion - Check conversion of given expression to boolean. 7481/// Input argument E is a logical expression. 7482static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 7483 if (S.getLangOpts().Bool) 7484 return; 7485 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 7486} 7487 7488/// AnalyzeImplicitConversions - Find and report any interesting 7489/// implicit conversions in the given expression. There are a couple 7490/// of competing diagnostics here, -Wconversion and -Wsign-compare. 7491void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 7492 QualType T = OrigE->getType(); 7493 Expr *E = OrigE->IgnoreParenImpCasts(); 7494 7495 if (E->isTypeDependent() || E->isValueDependent()) 7496 return; 7497 7498 // For conditional operators, we analyze the arguments as if they 7499 // were being fed directly into the output. 7500 if (isa<ConditionalOperator>(E)) { 7501 ConditionalOperator *CO = cast<ConditionalOperator>(E); 7502 CheckConditionalOperator(S, CO, CC, T); 7503 return; 7504 } 7505 7506 // Check implicit argument conversions for function calls. 7507 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 7508 CheckImplicitArgumentConversions(S, Call, CC); 7509 7510 // Go ahead and check any implicit conversions we might have skipped. 7511 // The non-canonical typecheck is just an optimization; 7512 // CheckImplicitConversion will filter out dead implicit conversions. 7513 if (E->getType() != T) 7514 CheckImplicitConversion(S, E, T, CC); 7515 7516 // Now continue drilling into this expression. 7517 7518 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 7519 // The bound subexpressions in a PseudoObjectExpr are not reachable 7520 // as transitive children. 7521 // FIXME: Use a more uniform representation for this. 7522 for (auto *SE : POE->semantics()) 7523 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 7524 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 7525 } 7526 7527 // Skip past explicit casts. 7528 if (isa<ExplicitCastExpr>(E)) { 7529 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 7530 return AnalyzeImplicitConversions(S, E, CC); 7531 } 7532 7533 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 7534 // Do a somewhat different check with comparison operators. 7535 if (BO->isComparisonOp()) 7536 return AnalyzeComparison(S, BO); 7537 7538 // And with simple assignments. 7539 if (BO->getOpcode() == BO_Assign) 7540 return AnalyzeAssignment(S, BO); 7541 } 7542 7543 // These break the otherwise-useful invariant below. Fortunately, 7544 // we don't really need to recurse into them, because any internal 7545 // expressions should have been analyzed already when they were 7546 // built into statements. 7547 if (isa<StmtExpr>(E)) return; 7548 7549 // Don't descend into unevaluated contexts. 7550 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 7551 7552 // Now just recurse over the expression's children. 7553 CC = E->getExprLoc(); 7554 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 7555 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 7556 for (Stmt *SubStmt : E->children()) { 7557 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 7558 if (!ChildExpr) 7559 continue; 7560 7561 if (IsLogicalAndOperator && 7562 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 7563 // Ignore checking string literals that are in logical and operators. 7564 // This is a common pattern for asserts. 7565 continue; 7566 AnalyzeImplicitConversions(S, ChildExpr, CC); 7567 } 7568 7569 if (BO && BO->isLogicalOp()) { 7570 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 7571 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 7572 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 7573 7574 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 7575 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 7576 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 7577 } 7578 7579 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 7580 if (U->getOpcode() == UO_LNot) 7581 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 7582} 7583 7584} // end anonymous namespace 7585 7586// Helper function for Sema::DiagnoseAlwaysNonNullPointer. 7587// Returns true when emitting a warning about taking the address of a reference. 7588static bool CheckForReference(Sema &SemaRef, const Expr *E, 7589 PartialDiagnostic PD) { 7590 E = E->IgnoreParenImpCasts(); 7591 7592 const FunctionDecl *FD = nullptr; 7593 7594 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 7595 if (!DRE->getDecl()->getType()->isReferenceType()) 7596 return false; 7597 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 7598 if (!M->getMemberDecl()->getType()->isReferenceType()) 7599 return false; 7600 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 7601 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 7602 return false; 7603 FD = Call->getDirectCallee(); 7604 } else { 7605 return false; 7606 } 7607 7608 SemaRef.Diag(E->getExprLoc(), PD); 7609 7610 // If possible, point to location of function. 7611 if (FD) { 7612 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 7613 } 7614 7615 return true; 7616} 7617 7618// Returns true if the SourceLocation is expanded from any macro body. 7619// Returns false if the SourceLocation is invalid, is from not in a macro 7620// expansion, or is from expanded from a top-level macro argument. 7621static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 7622 if (Loc.isInvalid()) 7623 return false; 7624 7625 while (Loc.isMacroID()) { 7626 if (SM.isMacroBodyExpansion(Loc)) 7627 return true; 7628 Loc = SM.getImmediateMacroCallerLoc(Loc); 7629 } 7630 7631 return false; 7632} 7633 7634/// \brief Diagnose pointers that are always non-null. 7635/// \param E the expression containing the pointer 7636/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 7637/// compared to a null pointer 7638/// \param IsEqual True when the comparison is equal to a null pointer 7639/// \param Range Extra SourceRange to highlight in the diagnostic 7640void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 7641 Expr::NullPointerConstantKind NullKind, 7642 bool IsEqual, SourceRange Range) { 7643 if (!E) 7644 return; 7645 7646 // Don't warn inside macros. 7647 if (E->getExprLoc().isMacroID()) { 7648 const SourceManager &SM = getSourceManager(); 7649 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 7650 IsInAnyMacroBody(SM, Range.getBegin())) 7651 return; 7652 } 7653 E = E->IgnoreImpCasts(); 7654 7655 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 7656 7657 if (isa<CXXThisExpr>(E)) { 7658 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 7659 : diag::warn_this_bool_conversion; 7660 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 7661 return; 7662 } 7663 7664 bool IsAddressOf = false; 7665 7666 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 7667 if (UO->getOpcode() != UO_AddrOf) 7668 return; 7669 IsAddressOf = true; 7670 E = UO->getSubExpr(); 7671 } 7672 7673 if (IsAddressOf) { 7674 unsigned DiagID = IsCompare 7675 ? diag::warn_address_of_reference_null_compare 7676 : diag::warn_address_of_reference_bool_conversion; 7677 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 7678 << IsEqual; 7679 if (CheckForReference(*this, E, PD)) { 7680 return; 7681 } 7682 } 7683 7684 auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) { 7685 std::string Str; 7686 llvm::raw_string_ostream S(Str); 7687 E->printPretty(S, nullptr, getPrintingPolicy()); 7688 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 7689 : diag::warn_cast_nonnull_to_bool; 7690 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 7691 << E->getSourceRange() << Range << IsEqual; 7692 }; 7693 7694 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 7695 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 7696 if (auto *Callee = Call->getDirectCallee()) { 7697 if (Callee->hasAttr<ReturnsNonNullAttr>()) { 7698 ComplainAboutNonnullParamOrCall(false); 7699 return; 7700 } 7701 } 7702 } 7703 7704 // Expect to find a single Decl. Skip anything more complicated. 7705 ValueDecl *D = nullptr; 7706 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 7707 D = R->getDecl(); 7708 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 7709 D = M->getMemberDecl(); 7710 } 7711 7712 // Weak Decls can be null. 7713 if (!D || D->isWeak()) 7714 return; 7715 7716 // Check for parameter decl with nonnull attribute 7717 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 7718 if (getCurFunction() && 7719 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 7720 if (PV->hasAttr<NonNullAttr>()) { 7721 ComplainAboutNonnullParamOrCall(true); 7722 return; 7723 } 7724 7725 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 7726 auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV); 7727 assert(ParamIter != FD->param_end()); 7728 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 7729 7730 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 7731 if (!NonNull->args_size()) { 7732 ComplainAboutNonnullParamOrCall(true); 7733 return; 7734 } 7735 7736 for (unsigned ArgNo : NonNull->args()) { 7737 if (ArgNo == ParamNo) { 7738 ComplainAboutNonnullParamOrCall(true); 7739 return; 7740 } 7741 } 7742 } 7743 } 7744 } 7745 } 7746 7747 QualType T = D->getType(); 7748 const bool IsArray = T->isArrayType(); 7749 const bool IsFunction = T->isFunctionType(); 7750 7751 // Address of function is used to silence the function warning. 7752 if (IsAddressOf && IsFunction) { 7753 return; 7754 } 7755 7756 // Found nothing. 7757 if (!IsAddressOf && !IsFunction && !IsArray) 7758 return; 7759 7760 // Pretty print the expression for the diagnostic. 7761 std::string Str; 7762 llvm::raw_string_ostream S(Str); 7763 E->printPretty(S, nullptr, getPrintingPolicy()); 7764 7765 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 7766 : diag::warn_impcast_pointer_to_bool; 7767 enum { 7768 AddressOf, 7769 FunctionPointer, 7770 ArrayPointer 7771 } DiagType; 7772 if (IsAddressOf) 7773 DiagType = AddressOf; 7774 else if (IsFunction) 7775 DiagType = FunctionPointer; 7776 else if (IsArray) 7777 DiagType = ArrayPointer; 7778 else 7779 llvm_unreachable("Could not determine diagnostic."); 7780 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 7781 << Range << IsEqual; 7782 7783 if (!IsFunction) 7784 return; 7785 7786 // Suggest '&' to silence the function warning. 7787 Diag(E->getExprLoc(), diag::note_function_warning_silence) 7788 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 7789 7790 // Check to see if '()' fixit should be emitted. 7791 QualType ReturnType; 7792 UnresolvedSet<4> NonTemplateOverloads; 7793 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 7794 if (ReturnType.isNull()) 7795 return; 7796 7797 if (IsCompare) { 7798 // There are two cases here. If there is null constant, the only suggest 7799 // for a pointer return type. If the null is 0, then suggest if the return 7800 // type is a pointer or an integer type. 7801 if (!ReturnType->isPointerType()) { 7802 if (NullKind == Expr::NPCK_ZeroExpression || 7803 NullKind == Expr::NPCK_ZeroLiteral) { 7804 if (!ReturnType->isIntegerType()) 7805 return; 7806 } else { 7807 return; 7808 } 7809 } 7810 } else { // !IsCompare 7811 // For function to bool, only suggest if the function pointer has bool 7812 // return type. 7813 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 7814 return; 7815 } 7816 Diag(E->getExprLoc(), diag::note_function_to_function_call) 7817 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 7818} 7819 7820 7821/// Diagnoses "dangerous" implicit conversions within the given 7822/// expression (which is a full expression). Implements -Wconversion 7823/// and -Wsign-compare. 7824/// 7825/// \param CC the "context" location of the implicit conversion, i.e. 7826/// the most location of the syntactic entity requiring the implicit 7827/// conversion 7828void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 7829 // Don't diagnose in unevaluated contexts. 7830 if (isUnevaluatedContext()) 7831 return; 7832 7833 // Don't diagnose for value- or type-dependent expressions. 7834 if (E->isTypeDependent() || E->isValueDependent()) 7835 return; 7836 7837 // Check for array bounds violations in cases where the check isn't triggered 7838 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 7839 // ArraySubscriptExpr is on the RHS of a variable initialization. 7840 CheckArrayAccess(E); 7841 7842 // This is not the right CC for (e.g.) a variable initialization. 7843 AnalyzeImplicitConversions(*this, E, CC); 7844} 7845 7846/// CheckBoolLikeConversion - Check conversion of given expression to boolean. 7847/// Input argument E is a logical expression. 7848void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 7849 ::CheckBoolLikeConversion(*this, E, CC); 7850} 7851 7852/// Diagnose when expression is an integer constant expression and its evaluation 7853/// results in integer overflow 7854void Sema::CheckForIntOverflow (Expr *E) { 7855 if (isa<BinaryOperator>(E->IgnoreParenCasts())) 7856 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 7857 else if (auto InitList = dyn_cast<InitListExpr>(E)) 7858 for (Expr *E : InitList->inits()) 7859 if (isa<BinaryOperator>(E->IgnoreParenCasts())) 7860 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 7861} 7862 7863namespace { 7864/// \brief Visitor for expressions which looks for unsequenced operations on the 7865/// same object. 7866class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 7867 typedef EvaluatedExprVisitor<SequenceChecker> Base; 7868 7869 /// \brief A tree of sequenced regions within an expression. Two regions are 7870 /// unsequenced if one is an ancestor or a descendent of the other. When we 7871 /// finish processing an expression with sequencing, such as a comma 7872 /// expression, we fold its tree nodes into its parent, since they are 7873 /// unsequenced with respect to nodes we will visit later. 7874 class SequenceTree { 7875 struct Value { 7876 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 7877 unsigned Parent : 31; 7878 bool Merged : 1; 7879 }; 7880 SmallVector<Value, 8> Values; 7881 7882 public: 7883 /// \brief A region within an expression which may be sequenced with respect 7884 /// to some other region. 7885 class Seq { 7886 explicit Seq(unsigned N) : Index(N) {} 7887 unsigned Index; 7888 friend class SequenceTree; 7889 public: 7890 Seq() : Index(0) {} 7891 }; 7892 7893 SequenceTree() { Values.push_back(Value(0)); } 7894 Seq root() const { return Seq(0); } 7895 7896 /// \brief Create a new sequence of operations, which is an unsequenced 7897 /// subset of \p Parent. This sequence of operations is sequenced with 7898 /// respect to other children of \p Parent. 7899 Seq allocate(Seq Parent) { 7900 Values.push_back(Value(Parent.Index)); 7901 return Seq(Values.size() - 1); 7902 } 7903 7904 /// \brief Merge a sequence of operations into its parent. 7905 void merge(Seq S) { 7906 Values[S.Index].Merged = true; 7907 } 7908 7909 /// \brief Determine whether two operations are unsequenced. This operation 7910 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 7911 /// should have been merged into its parent as appropriate. 7912 bool isUnsequenced(Seq Cur, Seq Old) { 7913 unsigned C = representative(Cur.Index); 7914 unsigned Target = representative(Old.Index); 7915 while (C >= Target) { 7916 if (C == Target) 7917 return true; 7918 C = Values[C].Parent; 7919 } 7920 return false; 7921 } 7922 7923 private: 7924 /// \brief Pick a representative for a sequence. 7925 unsigned representative(unsigned K) { 7926 if (Values[K].Merged) 7927 // Perform path compression as we go. 7928 return Values[K].Parent = representative(Values[K].Parent); 7929 return K; 7930 } 7931 }; 7932 7933 /// An object for which we can track unsequenced uses. 7934 typedef NamedDecl *Object; 7935 7936 /// Different flavors of object usage which we track. We only track the 7937 /// least-sequenced usage of each kind. 7938 enum UsageKind { 7939 /// A read of an object. Multiple unsequenced reads are OK. 7940 UK_Use, 7941 /// A modification of an object which is sequenced before the value 7942 /// computation of the expression, such as ++n in C++. 7943 UK_ModAsValue, 7944 /// A modification of an object which is not sequenced before the value 7945 /// computation of the expression, such as n++. 7946 UK_ModAsSideEffect, 7947 7948 UK_Count = UK_ModAsSideEffect + 1 7949 }; 7950 7951 struct Usage { 7952 Usage() : Use(nullptr), Seq() {} 7953 Expr *Use; 7954 SequenceTree::Seq Seq; 7955 }; 7956 7957 struct UsageInfo { 7958 UsageInfo() : Diagnosed(false) {} 7959 Usage Uses[UK_Count]; 7960 /// Have we issued a diagnostic for this variable already? 7961 bool Diagnosed; 7962 }; 7963 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 7964 7965 Sema &SemaRef; 7966 /// Sequenced regions within the expression. 7967 SequenceTree Tree; 7968 /// Declaration modifications and references which we have seen. 7969 UsageInfoMap UsageMap; 7970 /// The region we are currently within. 7971 SequenceTree::Seq Region; 7972 /// Filled in with declarations which were modified as a side-effect 7973 /// (that is, post-increment operations). 7974 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 7975 /// Expressions to check later. We defer checking these to reduce 7976 /// stack usage. 7977 SmallVectorImpl<Expr *> &WorkList; 7978 7979 /// RAII object wrapping the visitation of a sequenced subexpression of an 7980 /// expression. At the end of this process, the side-effects of the evaluation 7981 /// become sequenced with respect to the value computation of the result, so 7982 /// we downgrade any UK_ModAsSideEffect within the evaluation to 7983 /// UK_ModAsValue. 7984 struct SequencedSubexpression { 7985 SequencedSubexpression(SequenceChecker &Self) 7986 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 7987 Self.ModAsSideEffect = &ModAsSideEffect; 7988 } 7989 ~SequencedSubexpression() { 7990 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend(); 7991 MI != ME; ++MI) { 7992 UsageInfo &U = Self.UsageMap[MI->first]; 7993 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 7994 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue); 7995 SideEffectUsage = MI->second; 7996 } 7997 Self.ModAsSideEffect = OldModAsSideEffect; 7998 } 7999 8000 SequenceChecker &Self; 8001 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 8002 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 8003 }; 8004 8005 /// RAII object wrapping the visitation of a subexpression which we might 8006 /// choose to evaluate as a constant. If any subexpression is evaluated and 8007 /// found to be non-constant, this allows us to suppress the evaluation of 8008 /// the outer expression. 8009 class EvaluationTracker { 8010 public: 8011 EvaluationTracker(SequenceChecker &Self) 8012 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 8013 Self.EvalTracker = this; 8014 } 8015 ~EvaluationTracker() { 8016 Self.EvalTracker = Prev; 8017 if (Prev) 8018 Prev->EvalOK &= EvalOK; 8019 } 8020 8021 bool evaluate(const Expr *E, bool &Result) { 8022 if (!EvalOK || E->isValueDependent()) 8023 return false; 8024 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 8025 return EvalOK; 8026 } 8027 8028 private: 8029 SequenceChecker &Self; 8030 EvaluationTracker *Prev; 8031 bool EvalOK; 8032 } *EvalTracker; 8033 8034 /// \brief Find the object which is produced by the specified expression, 8035 /// if any. 8036 Object getObject(Expr *E, bool Mod) const { 8037 E = E->IgnoreParenCasts(); 8038 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 8039 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 8040 return getObject(UO->getSubExpr(), Mod); 8041 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 8042 if (BO->getOpcode() == BO_Comma) 8043 return getObject(BO->getRHS(), Mod); 8044 if (Mod && BO->isAssignmentOp()) 8045 return getObject(BO->getLHS(), Mod); 8046 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 8047 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 8048 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 8049 return ME->getMemberDecl(); 8050 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8051 // FIXME: If this is a reference, map through to its value. 8052 return DRE->getDecl(); 8053 return nullptr; 8054 } 8055 8056 /// \brief Note that an object was modified or used by an expression. 8057 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 8058 Usage &U = UI.Uses[UK]; 8059 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 8060 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 8061 ModAsSideEffect->push_back(std::make_pair(O, U)); 8062 U.Use = Ref; 8063 U.Seq = Region; 8064 } 8065 } 8066 /// \brief Check whether a modification or use conflicts with a prior usage. 8067 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 8068 bool IsModMod) { 8069 if (UI.Diagnosed) 8070 return; 8071 8072 const Usage &U = UI.Uses[OtherKind]; 8073 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 8074 return; 8075 8076 Expr *Mod = U.Use; 8077 Expr *ModOrUse = Ref; 8078 if (OtherKind == UK_Use) 8079 std::swap(Mod, ModOrUse); 8080 8081 SemaRef.Diag(Mod->getExprLoc(), 8082 IsModMod ? diag::warn_unsequenced_mod_mod 8083 : diag::warn_unsequenced_mod_use) 8084 << O << SourceRange(ModOrUse->getExprLoc()); 8085 UI.Diagnosed = true; 8086 } 8087 8088 void notePreUse(Object O, Expr *Use) { 8089 UsageInfo &U = UsageMap[O]; 8090 // Uses conflict with other modifications. 8091 checkUsage(O, U, Use, UK_ModAsValue, false); 8092 } 8093 void notePostUse(Object O, Expr *Use) { 8094 UsageInfo &U = UsageMap[O]; 8095 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 8096 addUsage(U, O, Use, UK_Use); 8097 } 8098 8099 void notePreMod(Object O, Expr *Mod) { 8100 UsageInfo &U = UsageMap[O]; 8101 // Modifications conflict with other modifications and with uses. 8102 checkUsage(O, U, Mod, UK_ModAsValue, true); 8103 checkUsage(O, U, Mod, UK_Use, false); 8104 } 8105 void notePostMod(Object O, Expr *Use, UsageKind UK) { 8106 UsageInfo &U = UsageMap[O]; 8107 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 8108 addUsage(U, O, Use, UK); 8109 } 8110 8111public: 8112 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 8113 : Base(S.Context), SemaRef(S), Region(Tree.root()), 8114 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 8115 Visit(E); 8116 } 8117 8118 void VisitStmt(Stmt *S) { 8119 // Skip all statements which aren't expressions for now. 8120 } 8121 8122 void VisitExpr(Expr *E) { 8123 // By default, just recurse to evaluated subexpressions. 8124 Base::VisitStmt(E); 8125 } 8126 8127 void VisitCastExpr(CastExpr *E) { 8128 Object O = Object(); 8129 if (E->getCastKind() == CK_LValueToRValue) 8130 O = getObject(E->getSubExpr(), false); 8131 8132 if (O) 8133 notePreUse(O, E); 8134 VisitExpr(E); 8135 if (O) 8136 notePostUse(O, E); 8137 } 8138 8139 void VisitBinComma(BinaryOperator *BO) { 8140 // C++11 [expr.comma]p1: 8141 // Every value computation and side effect associated with the left 8142 // expression is sequenced before every value computation and side 8143 // effect associated with the right expression. 8144 SequenceTree::Seq LHS = Tree.allocate(Region); 8145 SequenceTree::Seq RHS = Tree.allocate(Region); 8146 SequenceTree::Seq OldRegion = Region; 8147 8148 { 8149 SequencedSubexpression SeqLHS(*this); 8150 Region = LHS; 8151 Visit(BO->getLHS()); 8152 } 8153 8154 Region = RHS; 8155 Visit(BO->getRHS()); 8156 8157 Region = OldRegion; 8158 8159 // Forget that LHS and RHS are sequenced. They are both unsequenced 8160 // with respect to other stuff. 8161 Tree.merge(LHS); 8162 Tree.merge(RHS); 8163 } 8164 8165 void VisitBinAssign(BinaryOperator *BO) { 8166 // The modification is sequenced after the value computation of the LHS 8167 // and RHS, so check it before inspecting the operands and update the 8168 // map afterwards. 8169 Object O = getObject(BO->getLHS(), true); 8170 if (!O) 8171 return VisitExpr(BO); 8172 8173 notePreMod(O, BO); 8174 8175 // C++11 [expr.ass]p7: 8176 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 8177 // only once. 8178 // 8179 // Therefore, for a compound assignment operator, O is considered used 8180 // everywhere except within the evaluation of E1 itself. 8181 if (isa<CompoundAssignOperator>(BO)) 8182 notePreUse(O, BO); 8183 8184 Visit(BO->getLHS()); 8185 8186 if (isa<CompoundAssignOperator>(BO)) 8187 notePostUse(O, BO); 8188 8189 Visit(BO->getRHS()); 8190 8191 // C++11 [expr.ass]p1: 8192 // the assignment is sequenced [...] before the value computation of the 8193 // assignment expression. 8194 // C11 6.5.16/3 has no such rule. 8195 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 8196 : UK_ModAsSideEffect); 8197 } 8198 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 8199 VisitBinAssign(CAO); 8200 } 8201 8202 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 8203 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 8204 void VisitUnaryPreIncDec(UnaryOperator *UO) { 8205 Object O = getObject(UO->getSubExpr(), true); 8206 if (!O) 8207 return VisitExpr(UO); 8208 8209 notePreMod(O, UO); 8210 Visit(UO->getSubExpr()); 8211 // C++11 [expr.pre.incr]p1: 8212 // the expression ++x is equivalent to x+=1 8213 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 8214 : UK_ModAsSideEffect); 8215 } 8216 8217 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 8218 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 8219 void VisitUnaryPostIncDec(UnaryOperator *UO) { 8220 Object O = getObject(UO->getSubExpr(), true); 8221 if (!O) 8222 return VisitExpr(UO); 8223 8224 notePreMod(O, UO); 8225 Visit(UO->getSubExpr()); 8226 notePostMod(O, UO, UK_ModAsSideEffect); 8227 } 8228 8229 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 8230 void VisitBinLOr(BinaryOperator *BO) { 8231 // The side-effects of the LHS of an '&&' are sequenced before the 8232 // value computation of the RHS, and hence before the value computation 8233 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 8234 // as if they were unconditionally sequenced. 8235 EvaluationTracker Eval(*this); 8236 { 8237 SequencedSubexpression Sequenced(*this); 8238 Visit(BO->getLHS()); 8239 } 8240 8241 bool Result; 8242 if (Eval.evaluate(BO->getLHS(), Result)) { 8243 if (!Result) 8244 Visit(BO->getRHS()); 8245 } else { 8246 // Check for unsequenced operations in the RHS, treating it as an 8247 // entirely separate evaluation. 8248 // 8249 // FIXME: If there are operations in the RHS which are unsequenced 8250 // with respect to operations outside the RHS, and those operations 8251 // are unconditionally evaluated, diagnose them. 8252 WorkList.push_back(BO->getRHS()); 8253 } 8254 } 8255 void VisitBinLAnd(BinaryOperator *BO) { 8256 EvaluationTracker Eval(*this); 8257 { 8258 SequencedSubexpression Sequenced(*this); 8259 Visit(BO->getLHS()); 8260 } 8261 8262 bool Result; 8263 if (Eval.evaluate(BO->getLHS(), Result)) { 8264 if (Result) 8265 Visit(BO->getRHS()); 8266 } else { 8267 WorkList.push_back(BO->getRHS()); 8268 } 8269 } 8270 8271 // Only visit the condition, unless we can be sure which subexpression will 8272 // be chosen. 8273 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 8274 EvaluationTracker Eval(*this); 8275 { 8276 SequencedSubexpression Sequenced(*this); 8277 Visit(CO->getCond()); 8278 } 8279 8280 bool Result; 8281 if (Eval.evaluate(CO->getCond(), Result)) 8282 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 8283 else { 8284 WorkList.push_back(CO->getTrueExpr()); 8285 WorkList.push_back(CO->getFalseExpr()); 8286 } 8287 } 8288 8289 void VisitCallExpr(CallExpr *CE) { 8290 // C++11 [intro.execution]p15: 8291 // When calling a function [...], every value computation and side effect 8292 // associated with any argument expression, or with the postfix expression 8293 // designating the called function, is sequenced before execution of every 8294 // expression or statement in the body of the function [and thus before 8295 // the value computation of its result]. 8296 SequencedSubexpression Sequenced(*this); 8297 Base::VisitCallExpr(CE); 8298 8299 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 8300 } 8301 8302 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 8303 // This is a call, so all subexpressions are sequenced before the result. 8304 SequencedSubexpression Sequenced(*this); 8305 8306 if (!CCE->isListInitialization()) 8307 return VisitExpr(CCE); 8308 8309 // In C++11, list initializations are sequenced. 8310 SmallVector<SequenceTree::Seq, 32> Elts; 8311 SequenceTree::Seq Parent = Region; 8312 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 8313 E = CCE->arg_end(); 8314 I != E; ++I) { 8315 Region = Tree.allocate(Parent); 8316 Elts.push_back(Region); 8317 Visit(*I); 8318 } 8319 8320 // Forget that the initializers are sequenced. 8321 Region = Parent; 8322 for (unsigned I = 0; I < Elts.size(); ++I) 8323 Tree.merge(Elts[I]); 8324 } 8325 8326 void VisitInitListExpr(InitListExpr *ILE) { 8327 if (!SemaRef.getLangOpts().CPlusPlus11) 8328 return VisitExpr(ILE); 8329 8330 // In C++11, list initializations are sequenced. 8331 SmallVector<SequenceTree::Seq, 32> Elts; 8332 SequenceTree::Seq Parent = Region; 8333 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 8334 Expr *E = ILE->getInit(I); 8335 if (!E) continue; 8336 Region = Tree.allocate(Parent); 8337 Elts.push_back(Region); 8338 Visit(E); 8339 } 8340 8341 // Forget that the initializers are sequenced. 8342 Region = Parent; 8343 for (unsigned I = 0; I < Elts.size(); ++I) 8344 Tree.merge(Elts[I]); 8345 } 8346}; 8347} 8348 8349void Sema::CheckUnsequencedOperations(Expr *E) { 8350 SmallVector<Expr *, 8> WorkList; 8351 WorkList.push_back(E); 8352 while (!WorkList.empty()) { 8353 Expr *Item = WorkList.pop_back_val(); 8354 SequenceChecker(*this, Item, WorkList); 8355 } 8356} 8357 8358void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 8359 bool IsConstexpr) { 8360 CheckImplicitConversions(E, CheckLoc); 8361 CheckUnsequencedOperations(E); 8362 if (!IsConstexpr && !E->isValueDependent()) 8363 CheckForIntOverflow(E); 8364} 8365 8366void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 8367 FieldDecl *BitField, 8368 Expr *Init) { 8369 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 8370} 8371 8372static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 8373 SourceLocation Loc) { 8374 if (!PType->isVariablyModifiedType()) 8375 return; 8376 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 8377 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 8378 return; 8379 } 8380 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 8381 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 8382 return; 8383 } 8384 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 8385 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 8386 return; 8387 } 8388 8389 const ArrayType *AT = S.Context.getAsArrayType(PType); 8390 if (!AT) 8391 return; 8392 8393 if (AT->getSizeModifier() != ArrayType::Star) { 8394 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 8395 return; 8396 } 8397 8398 S.Diag(Loc, diag::err_array_star_in_function_definition); 8399} 8400 8401/// CheckParmsForFunctionDef - Check that the parameters of the given 8402/// function are appropriate for the definition of a function. This 8403/// takes care of any checks that cannot be performed on the 8404/// declaration itself, e.g., that the types of each of the function 8405/// parameters are complete. 8406bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P, 8407 ParmVarDecl *const *PEnd, 8408 bool CheckParameterNames) { 8409 bool HasInvalidParm = false; 8410 for (; P != PEnd; ++P) { 8411 ParmVarDecl *Param = *P; 8412 8413 // C99 6.7.5.3p4: the parameters in a parameter type list in a 8414 // function declarator that is part of a function definition of 8415 // that function shall not have incomplete type. 8416 // 8417 // This is also C++ [dcl.fct]p6. 8418 if (!Param->isInvalidDecl() && 8419 RequireCompleteType(Param->getLocation(), Param->getType(), 8420 diag::err_typecheck_decl_incomplete_type)) { 8421 Param->setInvalidDecl(); 8422 HasInvalidParm = true; 8423 } 8424 8425 // C99 6.9.1p5: If the declarator includes a parameter type list, the 8426 // declaration of each parameter shall include an identifier. 8427 if (CheckParameterNames && 8428 Param->getIdentifier() == nullptr && 8429 !Param->isImplicit() && 8430 !getLangOpts().CPlusPlus) 8431 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 8432 8433 // C99 6.7.5.3p12: 8434 // If the function declarator is not part of a definition of that 8435 // function, parameters may have incomplete type and may use the [*] 8436 // notation in their sequences of declarator specifiers to specify 8437 // variable length array types. 8438 QualType PType = Param->getOriginalType(); 8439 // FIXME: This diagnostic should point the '[*]' if source-location 8440 // information is added for it. 8441 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 8442 8443 // MSVC destroys objects passed by value in the callee. Therefore a 8444 // function definition which takes such a parameter must be able to call the 8445 // object's destructor. However, we don't perform any direct access check 8446 // on the dtor. 8447 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 8448 .getCXXABI() 8449 .areArgsDestroyedLeftToRightInCallee()) { 8450 if (!Param->isInvalidDecl()) { 8451 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 8452 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 8453 if (!ClassDecl->isInvalidDecl() && 8454 !ClassDecl->hasIrrelevantDestructor() && 8455 !ClassDecl->isDependentContext()) { 8456 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 8457 MarkFunctionReferenced(Param->getLocation(), Destructor); 8458 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 8459 } 8460 } 8461 } 8462 } 8463 8464 // Parameters with the pass_object_size attribute only need to be marked 8465 // constant at function definitions. Because we lack information about 8466 // whether we're on a declaration or definition when we're instantiating the 8467 // attribute, we need to check for constness here. 8468 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 8469 if (!Param->getType().isConstQualified()) 8470 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 8471 << Attr->getSpelling() << 1; 8472 } 8473 8474 return HasInvalidParm; 8475} 8476 8477/// CheckCastAlign - Implements -Wcast-align, which warns when a 8478/// pointer cast increases the alignment requirements. 8479void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 8480 // This is actually a lot of work to potentially be doing on every 8481 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 8482 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 8483 return; 8484 8485 // Ignore dependent types. 8486 if (T->isDependentType() || Op->getType()->isDependentType()) 8487 return; 8488 8489 // Require that the destination be a pointer type. 8490 const PointerType *DestPtr = T->getAs<PointerType>(); 8491 if (!DestPtr) return; 8492 8493 // If the destination has alignment 1, we're done. 8494 QualType DestPointee = DestPtr->getPointeeType(); 8495 if (DestPointee->isIncompleteType()) return; 8496 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 8497 if (DestAlign.isOne()) return; 8498 8499 // Require that the source be a pointer type. 8500 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 8501 if (!SrcPtr) return; 8502 QualType SrcPointee = SrcPtr->getPointeeType(); 8503 8504 // Whitelist casts from cv void*. We already implicitly 8505 // whitelisted casts to cv void*, since they have alignment 1. 8506 // Also whitelist casts involving incomplete types, which implicitly 8507 // includes 'void'. 8508 if (SrcPointee->isIncompleteType()) return; 8509 8510 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 8511 if (SrcAlign >= DestAlign) return; 8512 8513 Diag(TRange.getBegin(), diag::warn_cast_align) 8514 << Op->getType() << T 8515 << static_cast<unsigned>(SrcAlign.getQuantity()) 8516 << static_cast<unsigned>(DestAlign.getQuantity()) 8517 << TRange << Op->getSourceRange(); 8518} 8519 8520static const Type* getElementType(const Expr *BaseExpr) { 8521 const Type* EltType = BaseExpr->getType().getTypePtr(); 8522 if (EltType->isAnyPointerType()) 8523 return EltType->getPointeeType().getTypePtr(); 8524 else if (EltType->isArrayType()) 8525 return EltType->getBaseElementTypeUnsafe(); 8526 return EltType; 8527} 8528 8529/// \brief Check whether this array fits the idiom of a size-one tail padded 8530/// array member of a struct. 8531/// 8532/// We avoid emitting out-of-bounds access warnings for such arrays as they are 8533/// commonly used to emulate flexible arrays in C89 code. 8534static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size, 8535 const NamedDecl *ND) { 8536 if (Size != 1 || !ND) return false; 8537 8538 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 8539 if (!FD) return false; 8540 8541 // Don't consider sizes resulting from macro expansions or template argument 8542 // substitution to form C89 tail-padded arrays. 8543 8544 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 8545 while (TInfo) { 8546 TypeLoc TL = TInfo->getTypeLoc(); 8547 // Look through typedefs. 8548 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 8549 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 8550 TInfo = TDL->getTypeSourceInfo(); 8551 continue; 8552 } 8553 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 8554 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 8555 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 8556 return false; 8557 } 8558 break; 8559 } 8560 8561 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 8562 if (!RD) return false; 8563 if (RD->isUnion()) return false; 8564 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 8565 if (!CRD->isStandardLayout()) return false; 8566 } 8567 8568 // See if this is the last field decl in the record. 8569 const Decl *D = FD; 8570 while ((D = D->getNextDeclInContext())) 8571 if (isa<FieldDecl>(D)) 8572 return false; 8573 return true; 8574} 8575 8576void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 8577 const ArraySubscriptExpr *ASE, 8578 bool AllowOnePastEnd, bool IndexNegated) { 8579 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 8580 if (IndexExpr->isValueDependent()) 8581 return; 8582 8583 const Type *EffectiveType = getElementType(BaseExpr); 8584 BaseExpr = BaseExpr->IgnoreParenCasts(); 8585 const ConstantArrayType *ArrayTy = 8586 Context.getAsConstantArrayType(BaseExpr->getType()); 8587 if (!ArrayTy) 8588 return; 8589 8590 llvm::APSInt index; 8591 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 8592 return; 8593 if (IndexNegated) 8594 index = -index; 8595 8596 const NamedDecl *ND = nullptr; 8597 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 8598 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 8599 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 8600 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 8601 8602 if (index.isUnsigned() || !index.isNegative()) { 8603 llvm::APInt size = ArrayTy->getSize(); 8604 if (!size.isStrictlyPositive()) 8605 return; 8606 8607 const Type* BaseType = getElementType(BaseExpr); 8608 if (BaseType != EffectiveType) { 8609 // Make sure we're comparing apples to apples when comparing index to size 8610 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 8611 uint64_t array_typesize = Context.getTypeSize(BaseType); 8612 // Handle ptrarith_typesize being zero, such as when casting to void* 8613 if (!ptrarith_typesize) ptrarith_typesize = 1; 8614 if (ptrarith_typesize != array_typesize) { 8615 // There's a cast to a different size type involved 8616 uint64_t ratio = array_typesize / ptrarith_typesize; 8617 // TODO: Be smarter about handling cases where array_typesize is not a 8618 // multiple of ptrarith_typesize 8619 if (ptrarith_typesize * ratio == array_typesize) 8620 size *= llvm::APInt(size.getBitWidth(), ratio); 8621 } 8622 } 8623 8624 if (size.getBitWidth() > index.getBitWidth()) 8625 index = index.zext(size.getBitWidth()); 8626 else if (size.getBitWidth() < index.getBitWidth()) 8627 size = size.zext(index.getBitWidth()); 8628 8629 // For array subscripting the index must be less than size, but for pointer 8630 // arithmetic also allow the index (offset) to be equal to size since 8631 // computing the next address after the end of the array is legal and 8632 // commonly done e.g. in C++ iterators and range-based for loops. 8633 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 8634 return; 8635 8636 // Also don't warn for arrays of size 1 which are members of some 8637 // structure. These are often used to approximate flexible arrays in C89 8638 // code. 8639 if (IsTailPaddedMemberArray(*this, size, ND)) 8640 return; 8641 8642 // Suppress the warning if the subscript expression (as identified by the 8643 // ']' location) and the index expression are both from macro expansions 8644 // within a system header. 8645 if (ASE) { 8646 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 8647 ASE->getRBracketLoc()); 8648 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 8649 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 8650 IndexExpr->getLocStart()); 8651 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 8652 return; 8653 } 8654 } 8655 8656 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 8657 if (ASE) 8658 DiagID = diag::warn_array_index_exceeds_bounds; 8659 8660 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 8661 PDiag(DiagID) << index.toString(10, true) 8662 << size.toString(10, true) 8663 << (unsigned)size.getLimitedValue(~0U) 8664 << IndexExpr->getSourceRange()); 8665 } else { 8666 unsigned DiagID = diag::warn_array_index_precedes_bounds; 8667 if (!ASE) { 8668 DiagID = diag::warn_ptr_arith_precedes_bounds; 8669 if (index.isNegative()) index = -index; 8670 } 8671 8672 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 8673 PDiag(DiagID) << index.toString(10, true) 8674 << IndexExpr->getSourceRange()); 8675 } 8676 8677 if (!ND) { 8678 // Try harder to find a NamedDecl to point at in the note. 8679 while (const ArraySubscriptExpr *ASE = 8680 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 8681 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 8682 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 8683 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 8684 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 8685 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 8686 } 8687 8688 if (ND) 8689 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 8690 PDiag(diag::note_array_index_out_of_bounds) 8691 << ND->getDeclName()); 8692} 8693 8694void Sema::CheckArrayAccess(const Expr *expr) { 8695 int AllowOnePastEnd = 0; 8696 while (expr) { 8697 expr = expr->IgnoreParenImpCasts(); 8698 switch (expr->getStmtClass()) { 8699 case Stmt::ArraySubscriptExprClass: { 8700 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 8701 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 8702 AllowOnePastEnd > 0); 8703 return; 8704 } 8705 case Stmt::OMPArraySectionExprClass: { 8706 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 8707 if (ASE->getLowerBound()) 8708 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 8709 /*ASE=*/nullptr, AllowOnePastEnd > 0); 8710 return; 8711 } 8712 case Stmt::UnaryOperatorClass: { 8713 // Only unwrap the * and & unary operators 8714 const UnaryOperator *UO = cast<UnaryOperator>(expr); 8715 expr = UO->getSubExpr(); 8716 switch (UO->getOpcode()) { 8717 case UO_AddrOf: 8718 AllowOnePastEnd++; 8719 break; 8720 case UO_Deref: 8721 AllowOnePastEnd--; 8722 break; 8723 default: 8724 return; 8725 } 8726 break; 8727 } 8728 case Stmt::ConditionalOperatorClass: { 8729 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 8730 if (const Expr *lhs = cond->getLHS()) 8731 CheckArrayAccess(lhs); 8732 if (const Expr *rhs = cond->getRHS()) 8733 CheckArrayAccess(rhs); 8734 return; 8735 } 8736 default: 8737 return; 8738 } 8739 } 8740} 8741 8742//===--- CHECK: Objective-C retain cycles ----------------------------------// 8743 8744namespace { 8745 struct RetainCycleOwner { 8746 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 8747 VarDecl *Variable; 8748 SourceRange Range; 8749 SourceLocation Loc; 8750 bool Indirect; 8751 8752 void setLocsFrom(Expr *e) { 8753 Loc = e->getExprLoc(); 8754 Range = e->getSourceRange(); 8755 } 8756 }; 8757} 8758 8759/// Consider whether capturing the given variable can possibly lead to 8760/// a retain cycle. 8761static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 8762 // In ARC, it's captured strongly iff the variable has __strong 8763 // lifetime. In MRR, it's captured strongly if the variable is 8764 // __block and has an appropriate type. 8765 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 8766 return false; 8767 8768 owner.Variable = var; 8769 if (ref) 8770 owner.setLocsFrom(ref); 8771 return true; 8772} 8773 8774static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 8775 while (true) { 8776 e = e->IgnoreParens(); 8777 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 8778 switch (cast->getCastKind()) { 8779 case CK_BitCast: 8780 case CK_LValueBitCast: 8781 case CK_LValueToRValue: 8782 case CK_ARCReclaimReturnedObject: 8783 e = cast->getSubExpr(); 8784 continue; 8785 8786 default: 8787 return false; 8788 } 8789 } 8790 8791 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 8792 ObjCIvarDecl *ivar = ref->getDecl(); 8793 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 8794 return false; 8795 8796 // Try to find a retain cycle in the base. 8797 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 8798 return false; 8799 8800 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 8801 owner.Indirect = true; 8802 return true; 8803 } 8804 8805 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 8806 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 8807 if (!var) return false; 8808 return considerVariable(var, ref, owner); 8809 } 8810 8811 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 8812 if (member->isArrow()) return false; 8813 8814 // Don't count this as an indirect ownership. 8815 e = member->getBase(); 8816 continue; 8817 } 8818 8819 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 8820 // Only pay attention to pseudo-objects on property references. 8821 ObjCPropertyRefExpr *pre 8822 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 8823 ->IgnoreParens()); 8824 if (!pre) return false; 8825 if (pre->isImplicitProperty()) return false; 8826 ObjCPropertyDecl *property = pre->getExplicitProperty(); 8827 if (!property->isRetaining() && 8828 !(property->getPropertyIvarDecl() && 8829 property->getPropertyIvarDecl()->getType() 8830 .getObjCLifetime() == Qualifiers::OCL_Strong)) 8831 return false; 8832 8833 owner.Indirect = true; 8834 if (pre->isSuperReceiver()) { 8835 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 8836 if (!owner.Variable) 8837 return false; 8838 owner.Loc = pre->getLocation(); 8839 owner.Range = pre->getSourceRange(); 8840 return true; 8841 } 8842 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 8843 ->getSourceExpr()); 8844 continue; 8845 } 8846 8847 // Array ivars? 8848 8849 return false; 8850 } 8851} 8852 8853namespace { 8854 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 8855 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 8856 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 8857 Context(Context), Variable(variable), Capturer(nullptr), 8858 VarWillBeReased(false) {} 8859 ASTContext &Context; 8860 VarDecl *Variable; 8861 Expr *Capturer; 8862 bool VarWillBeReased; 8863 8864 void VisitDeclRefExpr(DeclRefExpr *ref) { 8865 if (ref->getDecl() == Variable && !Capturer) 8866 Capturer = ref; 8867 } 8868 8869 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 8870 if (Capturer) return; 8871 Visit(ref->getBase()); 8872 if (Capturer && ref->isFreeIvar()) 8873 Capturer = ref; 8874 } 8875 8876 void VisitBlockExpr(BlockExpr *block) { 8877 // Look inside nested blocks 8878 if (block->getBlockDecl()->capturesVariable(Variable)) 8879 Visit(block->getBlockDecl()->getBody()); 8880 } 8881 8882 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 8883 if (Capturer) return; 8884 if (OVE->getSourceExpr()) 8885 Visit(OVE->getSourceExpr()); 8886 } 8887 void VisitBinaryOperator(BinaryOperator *BinOp) { 8888 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 8889 return; 8890 Expr *LHS = BinOp->getLHS(); 8891 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 8892 if (DRE->getDecl() != Variable) 8893 return; 8894 if (Expr *RHS = BinOp->getRHS()) { 8895 RHS = RHS->IgnoreParenCasts(); 8896 llvm::APSInt Value; 8897 VarWillBeReased = 8898 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 8899 } 8900 } 8901 } 8902 }; 8903} 8904 8905/// Check whether the given argument is a block which captures a 8906/// variable. 8907static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 8908 assert(owner.Variable && owner.Loc.isValid()); 8909 8910 e = e->IgnoreParenCasts(); 8911 8912 // Look through [^{...} copy] and Block_copy(^{...}). 8913 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 8914 Selector Cmd = ME->getSelector(); 8915 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 8916 e = ME->getInstanceReceiver(); 8917 if (!e) 8918 return nullptr; 8919 e = e->IgnoreParenCasts(); 8920 } 8921 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 8922 if (CE->getNumArgs() == 1) { 8923 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 8924 if (Fn) { 8925 const IdentifierInfo *FnI = Fn->getIdentifier(); 8926 if (FnI && FnI->isStr("_Block_copy")) { 8927 e = CE->getArg(0)->IgnoreParenCasts(); 8928 } 8929 } 8930 } 8931 } 8932 8933 BlockExpr *block = dyn_cast<BlockExpr>(e); 8934 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 8935 return nullptr; 8936 8937 FindCaptureVisitor visitor(S.Context, owner.Variable); 8938 visitor.Visit(block->getBlockDecl()->getBody()); 8939 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 8940} 8941 8942static void diagnoseRetainCycle(Sema &S, Expr *capturer, 8943 RetainCycleOwner &owner) { 8944 assert(capturer); 8945 assert(owner.Variable && owner.Loc.isValid()); 8946 8947 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 8948 << owner.Variable << capturer->getSourceRange(); 8949 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 8950 << owner.Indirect << owner.Range; 8951} 8952 8953/// Check for a keyword selector that starts with the word 'add' or 8954/// 'set'. 8955static bool isSetterLikeSelector(Selector sel) { 8956 if (sel.isUnarySelector()) return false; 8957 8958 StringRef str = sel.getNameForSlot(0); 8959 while (!str.empty() && str.front() == '_') str = str.substr(1); 8960 if (str.startswith("set")) 8961 str = str.substr(3); 8962 else if (str.startswith("add")) { 8963 // Specially whitelist 'addOperationWithBlock:'. 8964 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 8965 return false; 8966 str = str.substr(3); 8967 } 8968 else 8969 return false; 8970 8971 if (str.empty()) return true; 8972 return !isLowercase(str.front()); 8973} 8974 8975static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 8976 ObjCMessageExpr *Message) { 8977 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 8978 Message->getReceiverInterface(), 8979 NSAPI::ClassId_NSMutableArray); 8980 if (!IsMutableArray) { 8981 return None; 8982 } 8983 8984 Selector Sel = Message->getSelector(); 8985 8986 Optional<NSAPI::NSArrayMethodKind> MKOpt = 8987 S.NSAPIObj->getNSArrayMethodKind(Sel); 8988 if (!MKOpt) { 8989 return None; 8990 } 8991 8992 NSAPI::NSArrayMethodKind MK = *MKOpt; 8993 8994 switch (MK) { 8995 case NSAPI::NSMutableArr_addObject: 8996 case NSAPI::NSMutableArr_insertObjectAtIndex: 8997 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 8998 return 0; 8999 case NSAPI::NSMutableArr_replaceObjectAtIndex: 9000 return 1; 9001 9002 default: 9003 return None; 9004 } 9005 9006 return None; 9007} 9008 9009static 9010Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 9011 ObjCMessageExpr *Message) { 9012 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 9013 Message->getReceiverInterface(), 9014 NSAPI::ClassId_NSMutableDictionary); 9015 if (!IsMutableDictionary) { 9016 return None; 9017 } 9018 9019 Selector Sel = Message->getSelector(); 9020 9021 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 9022 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 9023 if (!MKOpt) { 9024 return None; 9025 } 9026 9027 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 9028 9029 switch (MK) { 9030 case NSAPI::NSMutableDict_setObjectForKey: 9031 case NSAPI::NSMutableDict_setValueForKey: 9032 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 9033 return 0; 9034 9035 default: 9036 return None; 9037 } 9038 9039 return None; 9040} 9041 9042static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 9043 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 9044 Message->getReceiverInterface(), 9045 NSAPI::ClassId_NSMutableSet); 9046 9047 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 9048 Message->getReceiverInterface(), 9049 NSAPI::ClassId_NSMutableOrderedSet); 9050 if (!IsMutableSet && !IsMutableOrderedSet) { 9051 return None; 9052 } 9053 9054 Selector Sel = Message->getSelector(); 9055 9056 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 9057 if (!MKOpt) { 9058 return None; 9059 } 9060 9061 NSAPI::NSSetMethodKind MK = *MKOpt; 9062 9063 switch (MK) { 9064 case NSAPI::NSMutableSet_addObject: 9065 case NSAPI::NSOrderedSet_setObjectAtIndex: 9066 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 9067 case NSAPI::NSOrderedSet_insertObjectAtIndex: 9068 return 0; 9069 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 9070 return 1; 9071 } 9072 9073 return None; 9074} 9075 9076void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 9077 if (!Message->isInstanceMessage()) { 9078 return; 9079 } 9080 9081 Optional<int> ArgOpt; 9082 9083 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 9084 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 9085 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 9086 return; 9087 } 9088 9089 int ArgIndex = *ArgOpt; 9090 9091 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 9092 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 9093 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 9094 } 9095 9096 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 9097 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 9098 if (ArgRE->isObjCSelfExpr()) { 9099 Diag(Message->getSourceRange().getBegin(), 9100 diag::warn_objc_circular_container) 9101 << ArgRE->getDecl()->getName() << StringRef("super"); 9102 } 9103 } 9104 } else { 9105 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 9106 9107 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 9108 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 9109 } 9110 9111 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 9112 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 9113 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 9114 ValueDecl *Decl = ReceiverRE->getDecl(); 9115 Diag(Message->getSourceRange().getBegin(), 9116 diag::warn_objc_circular_container) 9117 << Decl->getName() << Decl->getName(); 9118 if (!ArgRE->isObjCSelfExpr()) { 9119 Diag(Decl->getLocation(), 9120 diag::note_objc_circular_container_declared_here) 9121 << Decl->getName(); 9122 } 9123 } 9124 } 9125 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 9126 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 9127 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 9128 ObjCIvarDecl *Decl = IvarRE->getDecl(); 9129 Diag(Message->getSourceRange().getBegin(), 9130 diag::warn_objc_circular_container) 9131 << Decl->getName() << Decl->getName(); 9132 Diag(Decl->getLocation(), 9133 diag::note_objc_circular_container_declared_here) 9134 << Decl->getName(); 9135 } 9136 } 9137 } 9138 } 9139 9140} 9141 9142/// Check a message send to see if it's likely to cause a retain cycle. 9143void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 9144 // Only check instance methods whose selector looks like a setter. 9145 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 9146 return; 9147 9148 // Try to find a variable that the receiver is strongly owned by. 9149 RetainCycleOwner owner; 9150 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 9151 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 9152 return; 9153 } else { 9154 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 9155 owner.Variable = getCurMethodDecl()->getSelfDecl(); 9156 owner.Loc = msg->getSuperLoc(); 9157 owner.Range = msg->getSuperLoc(); 9158 } 9159 9160 // Check whether the receiver is captured by any of the arguments. 9161 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 9162 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 9163 return diagnoseRetainCycle(*this, capturer, owner); 9164} 9165 9166/// Check a property assign to see if it's likely to cause a retain cycle. 9167void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 9168 RetainCycleOwner owner; 9169 if (!findRetainCycleOwner(*this, receiver, owner)) 9170 return; 9171 9172 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 9173 diagnoseRetainCycle(*this, capturer, owner); 9174} 9175 9176void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 9177 RetainCycleOwner Owner; 9178 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 9179 return; 9180 9181 // Because we don't have an expression for the variable, we have to set the 9182 // location explicitly here. 9183 Owner.Loc = Var->getLocation(); 9184 Owner.Range = Var->getSourceRange(); 9185 9186 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 9187 diagnoseRetainCycle(*this, Capturer, Owner); 9188} 9189 9190static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 9191 Expr *RHS, bool isProperty) { 9192 // Check if RHS is an Objective-C object literal, which also can get 9193 // immediately zapped in a weak reference. Note that we explicitly 9194 // allow ObjCStringLiterals, since those are designed to never really die. 9195 RHS = RHS->IgnoreParenImpCasts(); 9196 9197 // This enum needs to match with the 'select' in 9198 // warn_objc_arc_literal_assign (off-by-1). 9199 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 9200 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 9201 return false; 9202 9203 S.Diag(Loc, diag::warn_arc_literal_assign) 9204 << (unsigned) Kind 9205 << (isProperty ? 0 : 1) 9206 << RHS->getSourceRange(); 9207 9208 return true; 9209} 9210 9211static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 9212 Qualifiers::ObjCLifetime LT, 9213 Expr *RHS, bool isProperty) { 9214 // Strip off any implicit cast added to get to the one ARC-specific. 9215 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 9216 if (cast->getCastKind() == CK_ARCConsumeObject) { 9217 S.Diag(Loc, diag::warn_arc_retained_assign) 9218 << (LT == Qualifiers::OCL_ExplicitNone) 9219 << (isProperty ? 0 : 1) 9220 << RHS->getSourceRange(); 9221 return true; 9222 } 9223 RHS = cast->getSubExpr(); 9224 } 9225 9226 if (LT == Qualifiers::OCL_Weak && 9227 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 9228 return true; 9229 9230 return false; 9231} 9232 9233bool Sema::checkUnsafeAssigns(SourceLocation Loc, 9234 QualType LHS, Expr *RHS) { 9235 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 9236 9237 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 9238 return false; 9239 9240 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 9241 return true; 9242 9243 return false; 9244} 9245 9246void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 9247 Expr *LHS, Expr *RHS) { 9248 QualType LHSType; 9249 // PropertyRef on LHS type need be directly obtained from 9250 // its declaration as it has a PseudoType. 9251 ObjCPropertyRefExpr *PRE 9252 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 9253 if (PRE && !PRE->isImplicitProperty()) { 9254 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 9255 if (PD) 9256 LHSType = PD->getType(); 9257 } 9258 9259 if (LHSType.isNull()) 9260 LHSType = LHS->getType(); 9261 9262 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 9263 9264 if (LT == Qualifiers::OCL_Weak) { 9265 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 9266 getCurFunction()->markSafeWeakUse(LHS); 9267 } 9268 9269 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 9270 return; 9271 9272 // FIXME. Check for other life times. 9273 if (LT != Qualifiers::OCL_None) 9274 return; 9275 9276 if (PRE) { 9277 if (PRE->isImplicitProperty()) 9278 return; 9279 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 9280 if (!PD) 9281 return; 9282 9283 unsigned Attributes = PD->getPropertyAttributes(); 9284 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 9285 // when 'assign' attribute was not explicitly specified 9286 // by user, ignore it and rely on property type itself 9287 // for lifetime info. 9288 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 9289 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 9290 LHSType->isObjCRetainableType()) 9291 return; 9292 9293 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 9294 if (cast->getCastKind() == CK_ARCConsumeObject) { 9295 Diag(Loc, diag::warn_arc_retained_property_assign) 9296 << RHS->getSourceRange(); 9297 return; 9298 } 9299 RHS = cast->getSubExpr(); 9300 } 9301 } 9302 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 9303 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 9304 return; 9305 } 9306 } 9307} 9308 9309//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 9310 9311namespace { 9312bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 9313 SourceLocation StmtLoc, 9314 const NullStmt *Body) { 9315 // Do not warn if the body is a macro that expands to nothing, e.g: 9316 // 9317 // #define CALL(x) 9318 // if (condition) 9319 // CALL(0); 9320 // 9321 if (Body->hasLeadingEmptyMacro()) 9322 return false; 9323 9324 // Get line numbers of statement and body. 9325 bool StmtLineInvalid; 9326 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 9327 &StmtLineInvalid); 9328 if (StmtLineInvalid) 9329 return false; 9330 9331 bool BodyLineInvalid; 9332 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 9333 &BodyLineInvalid); 9334 if (BodyLineInvalid) 9335 return false; 9336 9337 // Warn if null statement and body are on the same line. 9338 if (StmtLine != BodyLine) 9339 return false; 9340 9341 return true; 9342} 9343} // Unnamed namespace 9344 9345void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 9346 const Stmt *Body, 9347 unsigned DiagID) { 9348 // Since this is a syntactic check, don't emit diagnostic for template 9349 // instantiations, this just adds noise. 9350 if (CurrentInstantiationScope) 9351 return; 9352 9353 // The body should be a null statement. 9354 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 9355 if (!NBody) 9356 return; 9357 9358 // Do the usual checks. 9359 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 9360 return; 9361 9362 Diag(NBody->getSemiLoc(), DiagID); 9363 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 9364} 9365 9366void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 9367 const Stmt *PossibleBody) { 9368 assert(!CurrentInstantiationScope); // Ensured by caller 9369 9370 SourceLocation StmtLoc; 9371 const Stmt *Body; 9372 unsigned DiagID; 9373 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 9374 StmtLoc = FS->getRParenLoc(); 9375 Body = FS->getBody(); 9376 DiagID = diag::warn_empty_for_body; 9377 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 9378 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 9379 Body = WS->getBody(); 9380 DiagID = diag::warn_empty_while_body; 9381 } else 9382 return; // Neither `for' nor `while'. 9383 9384 // The body should be a null statement. 9385 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 9386 if (!NBody) 9387 return; 9388 9389 // Skip expensive checks if diagnostic is disabled. 9390 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 9391 return; 9392 9393 // Do the usual checks. 9394 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 9395 return; 9396 9397 // `for(...);' and `while(...);' are popular idioms, so in order to keep 9398 // noise level low, emit diagnostics only if for/while is followed by a 9399 // CompoundStmt, e.g.: 9400 // for (int i = 0; i < n; i++); 9401 // { 9402 // a(i); 9403 // } 9404 // or if for/while is followed by a statement with more indentation 9405 // than for/while itself: 9406 // for (int i = 0; i < n; i++); 9407 // a(i); 9408 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 9409 if (!ProbableTypo) { 9410 bool BodyColInvalid; 9411 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 9412 PossibleBody->getLocStart(), 9413 &BodyColInvalid); 9414 if (BodyColInvalid) 9415 return; 9416 9417 bool StmtColInvalid; 9418 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 9419 S->getLocStart(), 9420 &StmtColInvalid); 9421 if (StmtColInvalid) 9422 return; 9423 9424 if (BodyCol > StmtCol) 9425 ProbableTypo = true; 9426 } 9427 9428 if (ProbableTypo) { 9429 Diag(NBody->getSemiLoc(), DiagID); 9430 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 9431 } 9432} 9433 9434//===--- CHECK: Warn on self move with std::move. -------------------------===// 9435 9436/// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 9437void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 9438 SourceLocation OpLoc) { 9439 9440 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 9441 return; 9442 9443 if (!ActiveTemplateInstantiations.empty()) 9444 return; 9445 9446 // Strip parens and casts away. 9447 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 9448 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 9449 9450 // Check for a call expression 9451 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 9452 if (!CE || CE->getNumArgs() != 1) 9453 return; 9454 9455 // Check for a call to std::move 9456 const FunctionDecl *FD = CE->getDirectCallee(); 9457 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() || 9458 !FD->getIdentifier()->isStr("move")) 9459 return; 9460 9461 // Get argument from std::move 9462 RHSExpr = CE->getArg(0); 9463 9464 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 9465 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 9466 9467 // Two DeclRefExpr's, check that the decls are the same. 9468 if (LHSDeclRef && RHSDeclRef) { 9469 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 9470 return; 9471 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 9472 RHSDeclRef->getDecl()->getCanonicalDecl()) 9473 return; 9474 9475 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 9476 << LHSExpr->getSourceRange() 9477 << RHSExpr->getSourceRange(); 9478 return; 9479 } 9480 9481 // Member variables require a different approach to check for self moves. 9482 // MemberExpr's are the same if every nested MemberExpr refers to the same 9483 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 9484 // the base Expr's are CXXThisExpr's. 9485 const Expr *LHSBase = LHSExpr; 9486 const Expr *RHSBase = RHSExpr; 9487 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 9488 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 9489 if (!LHSME || !RHSME) 9490 return; 9491 9492 while (LHSME && RHSME) { 9493 if (LHSME->getMemberDecl()->getCanonicalDecl() != 9494 RHSME->getMemberDecl()->getCanonicalDecl()) 9495 return; 9496 9497 LHSBase = LHSME->getBase(); 9498 RHSBase = RHSME->getBase(); 9499 LHSME = dyn_cast<MemberExpr>(LHSBase); 9500 RHSME = dyn_cast<MemberExpr>(RHSBase); 9501 } 9502 9503 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 9504 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 9505 if (LHSDeclRef && RHSDeclRef) { 9506 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 9507 return; 9508 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 9509 RHSDeclRef->getDecl()->getCanonicalDecl()) 9510 return; 9511 9512 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 9513 << LHSExpr->getSourceRange() 9514 << RHSExpr->getSourceRange(); 9515 return; 9516 } 9517 9518 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 9519 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 9520 << LHSExpr->getSourceRange() 9521 << RHSExpr->getSourceRange(); 9522} 9523 9524//===--- Layout compatibility ----------------------------------------------// 9525 9526namespace { 9527 9528bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 9529 9530/// \brief Check if two enumeration types are layout-compatible. 9531bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 9532 // C++11 [dcl.enum] p8: 9533 // Two enumeration types are layout-compatible if they have the same 9534 // underlying type. 9535 return ED1->isComplete() && ED2->isComplete() && 9536 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 9537} 9538 9539/// \brief Check if two fields are layout-compatible. 9540bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 9541 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 9542 return false; 9543 9544 if (Field1->isBitField() != Field2->isBitField()) 9545 return false; 9546 9547 if (Field1->isBitField()) { 9548 // Make sure that the bit-fields are the same length. 9549 unsigned Bits1 = Field1->getBitWidthValue(C); 9550 unsigned Bits2 = Field2->getBitWidthValue(C); 9551 9552 if (Bits1 != Bits2) 9553 return false; 9554 } 9555 9556 return true; 9557} 9558 9559/// \brief Check if two standard-layout structs are layout-compatible. 9560/// (C++11 [class.mem] p17) 9561bool isLayoutCompatibleStruct(ASTContext &C, 9562 RecordDecl *RD1, 9563 RecordDecl *RD2) { 9564 // If both records are C++ classes, check that base classes match. 9565 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 9566 // If one of records is a CXXRecordDecl we are in C++ mode, 9567 // thus the other one is a CXXRecordDecl, too. 9568 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 9569 // Check number of base classes. 9570 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 9571 return false; 9572 9573 // Check the base classes. 9574 for (CXXRecordDecl::base_class_const_iterator 9575 Base1 = D1CXX->bases_begin(), 9576 BaseEnd1 = D1CXX->bases_end(), 9577 Base2 = D2CXX->bases_begin(); 9578 Base1 != BaseEnd1; 9579 ++Base1, ++Base2) { 9580 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 9581 return false; 9582 } 9583 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 9584 // If only RD2 is a C++ class, it should have zero base classes. 9585 if (D2CXX->getNumBases() > 0) 9586 return false; 9587 } 9588 9589 // Check the fields. 9590 RecordDecl::field_iterator Field2 = RD2->field_begin(), 9591 Field2End = RD2->field_end(), 9592 Field1 = RD1->field_begin(), 9593 Field1End = RD1->field_end(); 9594 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 9595 if (!isLayoutCompatible(C, *Field1, *Field2)) 9596 return false; 9597 } 9598 if (Field1 != Field1End || Field2 != Field2End) 9599 return false; 9600 9601 return true; 9602} 9603 9604/// \brief Check if two standard-layout unions are layout-compatible. 9605/// (C++11 [class.mem] p18) 9606bool isLayoutCompatibleUnion(ASTContext &C, 9607 RecordDecl *RD1, 9608 RecordDecl *RD2) { 9609 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 9610 for (auto *Field2 : RD2->fields()) 9611 UnmatchedFields.insert(Field2); 9612 9613 for (auto *Field1 : RD1->fields()) { 9614 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 9615 I = UnmatchedFields.begin(), 9616 E = UnmatchedFields.end(); 9617 9618 for ( ; I != E; ++I) { 9619 if (isLayoutCompatible(C, Field1, *I)) { 9620 bool Result = UnmatchedFields.erase(*I); 9621 (void) Result; 9622 assert(Result); 9623 break; 9624 } 9625 } 9626 if (I == E) 9627 return false; 9628 } 9629 9630 return UnmatchedFields.empty(); 9631} 9632 9633bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 9634 if (RD1->isUnion() != RD2->isUnion()) 9635 return false; 9636 9637 if (RD1->isUnion()) 9638 return isLayoutCompatibleUnion(C, RD1, RD2); 9639 else 9640 return isLayoutCompatibleStruct(C, RD1, RD2); 9641} 9642 9643/// \brief Check if two types are layout-compatible in C++11 sense. 9644bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 9645 if (T1.isNull() || T2.isNull()) 9646 return false; 9647 9648 // C++11 [basic.types] p11: 9649 // If two types T1 and T2 are the same type, then T1 and T2 are 9650 // layout-compatible types. 9651 if (C.hasSameType(T1, T2)) 9652 return true; 9653 9654 T1 = T1.getCanonicalType().getUnqualifiedType(); 9655 T2 = T2.getCanonicalType().getUnqualifiedType(); 9656 9657 const Type::TypeClass TC1 = T1->getTypeClass(); 9658 const Type::TypeClass TC2 = T2->getTypeClass(); 9659 9660 if (TC1 != TC2) 9661 return false; 9662 9663 if (TC1 == Type::Enum) { 9664 return isLayoutCompatible(C, 9665 cast<EnumType>(T1)->getDecl(), 9666 cast<EnumType>(T2)->getDecl()); 9667 } else if (TC1 == Type::Record) { 9668 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 9669 return false; 9670 9671 return isLayoutCompatible(C, 9672 cast<RecordType>(T1)->getDecl(), 9673 cast<RecordType>(T2)->getDecl()); 9674 } 9675 9676 return false; 9677} 9678} 9679 9680//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 9681 9682namespace { 9683/// \brief Given a type tag expression find the type tag itself. 9684/// 9685/// \param TypeExpr Type tag expression, as it appears in user's code. 9686/// 9687/// \param VD Declaration of an identifier that appears in a type tag. 9688/// 9689/// \param MagicValue Type tag magic value. 9690bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 9691 const ValueDecl **VD, uint64_t *MagicValue) { 9692 while(true) { 9693 if (!TypeExpr) 9694 return false; 9695 9696 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 9697 9698 switch (TypeExpr->getStmtClass()) { 9699 case Stmt::UnaryOperatorClass: { 9700 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 9701 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 9702 TypeExpr = UO->getSubExpr(); 9703 continue; 9704 } 9705 return false; 9706 } 9707 9708 case Stmt::DeclRefExprClass: { 9709 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 9710 *VD = DRE->getDecl(); 9711 return true; 9712 } 9713 9714 case Stmt::IntegerLiteralClass: { 9715 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 9716 llvm::APInt MagicValueAPInt = IL->getValue(); 9717 if (MagicValueAPInt.getActiveBits() <= 64) { 9718 *MagicValue = MagicValueAPInt.getZExtValue(); 9719 return true; 9720 } else 9721 return false; 9722 } 9723 9724 case Stmt::BinaryConditionalOperatorClass: 9725 case Stmt::ConditionalOperatorClass: { 9726 const AbstractConditionalOperator *ACO = 9727 cast<AbstractConditionalOperator>(TypeExpr); 9728 bool Result; 9729 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 9730 if (Result) 9731 TypeExpr = ACO->getTrueExpr(); 9732 else 9733 TypeExpr = ACO->getFalseExpr(); 9734 continue; 9735 } 9736 return false; 9737 } 9738 9739 case Stmt::BinaryOperatorClass: { 9740 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 9741 if (BO->getOpcode() == BO_Comma) { 9742 TypeExpr = BO->getRHS(); 9743 continue; 9744 } 9745 return false; 9746 } 9747 9748 default: 9749 return false; 9750 } 9751 } 9752} 9753 9754/// \brief Retrieve the C type corresponding to type tag TypeExpr. 9755/// 9756/// \param TypeExpr Expression that specifies a type tag. 9757/// 9758/// \param MagicValues Registered magic values. 9759/// 9760/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 9761/// kind. 9762/// 9763/// \param TypeInfo Information about the corresponding C type. 9764/// 9765/// \returns true if the corresponding C type was found. 9766bool GetMatchingCType( 9767 const IdentifierInfo *ArgumentKind, 9768 const Expr *TypeExpr, const ASTContext &Ctx, 9769 const llvm::DenseMap<Sema::TypeTagMagicValue, 9770 Sema::TypeTagData> *MagicValues, 9771 bool &FoundWrongKind, 9772 Sema::TypeTagData &TypeInfo) { 9773 FoundWrongKind = false; 9774 9775 // Variable declaration that has type_tag_for_datatype attribute. 9776 const ValueDecl *VD = nullptr; 9777 9778 uint64_t MagicValue; 9779 9780 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 9781 return false; 9782 9783 if (VD) { 9784 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 9785 if (I->getArgumentKind() != ArgumentKind) { 9786 FoundWrongKind = true; 9787 return false; 9788 } 9789 TypeInfo.Type = I->getMatchingCType(); 9790 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 9791 TypeInfo.MustBeNull = I->getMustBeNull(); 9792 return true; 9793 } 9794 return false; 9795 } 9796 9797 if (!MagicValues) 9798 return false; 9799 9800 llvm::DenseMap<Sema::TypeTagMagicValue, 9801 Sema::TypeTagData>::const_iterator I = 9802 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 9803 if (I == MagicValues->end()) 9804 return false; 9805 9806 TypeInfo = I->second; 9807 return true; 9808} 9809} // unnamed namespace 9810 9811void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 9812 uint64_t MagicValue, QualType Type, 9813 bool LayoutCompatible, 9814 bool MustBeNull) { 9815 if (!TypeTagForDatatypeMagicValues) 9816 TypeTagForDatatypeMagicValues.reset( 9817 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 9818 9819 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 9820 (*TypeTagForDatatypeMagicValues)[Magic] = 9821 TypeTagData(Type, LayoutCompatible, MustBeNull); 9822} 9823 9824namespace { 9825bool IsSameCharType(QualType T1, QualType T2) { 9826 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 9827 if (!BT1) 9828 return false; 9829 9830 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 9831 if (!BT2) 9832 return false; 9833 9834 BuiltinType::Kind T1Kind = BT1->getKind(); 9835 BuiltinType::Kind T2Kind = BT2->getKind(); 9836 9837 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 9838 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 9839 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 9840 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 9841} 9842} // unnamed namespace 9843 9844void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 9845 const Expr * const *ExprArgs) { 9846 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 9847 bool IsPointerAttr = Attr->getIsPointer(); 9848 9849 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 9850 bool FoundWrongKind; 9851 TypeTagData TypeInfo; 9852 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 9853 TypeTagForDatatypeMagicValues.get(), 9854 FoundWrongKind, TypeInfo)) { 9855 if (FoundWrongKind) 9856 Diag(TypeTagExpr->getExprLoc(), 9857 diag::warn_type_tag_for_datatype_wrong_kind) 9858 << TypeTagExpr->getSourceRange(); 9859 return; 9860 } 9861 9862 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 9863 if (IsPointerAttr) { 9864 // Skip implicit cast of pointer to `void *' (as a function argument). 9865 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 9866 if (ICE->getType()->isVoidPointerType() && 9867 ICE->getCastKind() == CK_BitCast) 9868 ArgumentExpr = ICE->getSubExpr(); 9869 } 9870 QualType ArgumentType = ArgumentExpr->getType(); 9871 9872 // Passing a `void*' pointer shouldn't trigger a warning. 9873 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 9874 return; 9875 9876 if (TypeInfo.MustBeNull) { 9877 // Type tag with matching void type requires a null pointer. 9878 if (!ArgumentExpr->isNullPointerConstant(Context, 9879 Expr::NPC_ValueDependentIsNotNull)) { 9880 Diag(ArgumentExpr->getExprLoc(), 9881 diag::warn_type_safety_null_pointer_required) 9882 << ArgumentKind->getName() 9883 << ArgumentExpr->getSourceRange() 9884 << TypeTagExpr->getSourceRange(); 9885 } 9886 return; 9887 } 9888 9889 QualType RequiredType = TypeInfo.Type; 9890 if (IsPointerAttr) 9891 RequiredType = Context.getPointerType(RequiredType); 9892 9893 bool mismatch = false; 9894 if (!TypeInfo.LayoutCompatible) { 9895 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 9896 9897 // C++11 [basic.fundamental] p1: 9898 // Plain char, signed char, and unsigned char are three distinct types. 9899 // 9900 // But we treat plain `char' as equivalent to `signed char' or `unsigned 9901 // char' depending on the current char signedness mode. 9902 if (mismatch) 9903 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 9904 RequiredType->getPointeeType())) || 9905 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 9906 mismatch = false; 9907 } else 9908 if (IsPointerAttr) 9909 mismatch = !isLayoutCompatible(Context, 9910 ArgumentType->getPointeeType(), 9911 RequiredType->getPointeeType()); 9912 else 9913 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 9914 9915 if (mismatch) 9916 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 9917 << ArgumentType << ArgumentKind 9918 << TypeInfo.LayoutCompatible << RequiredType 9919 << ArgumentExpr->getSourceRange() 9920 << TypeTagExpr->getSourceRange(); 9921} 9922